Shop: Fourthwall import, sizes and colors, and a cart #31

Merged
jcoffey-dev merged 3 commits from shop/fourthwall into main 2026-10-17 00:13:31 +00:00
26 changed files with 1449 additions and 22 deletions

No files matched your search

+41 -1
View File
@@ -47,6 +47,7 @@ Usage:
hotdog-cms endpoint -config FILE the small server for form submissions and search, behind your web server
hotdog-cms pack add|remove|list|check extensions as files: sections, layouts, styles (docs/packs.md)
hotdog-cms import <from> ... move your own site in: wordpress, wxr, ghost, hugo, jekyll or mkdocs (docs/importing.md)
hotdog-cms import fourthwall bring a Fourthwall shop's products in for the shop pack; run again to sync
hotdog-cms editor -config FILE the editor: sign in with your git platform and work on sites (never on a site's host)
Platforms: GitHub, GitLab, Gitea, Forgejo/Codeberg, Gogs, Bitbucket, or any git server.
@@ -58,6 +59,7 @@ Secrets come from the environment, never flags:
HOTDOG_SMTP_PASSWORD the endpoint's SMTP password
HOTDOG_TURNSTILE_SECRET check Cloudflare Turnstile on forms that use it
HOTDOG_EDITOR_SECRET seal editor sessions (same on every editor serving the same people)
HOTDOG_FOURTHWALL_TOKEN a Fourthwall shop's storefront token (import fourthwall)
hotdog-cms version
Run "hotdog-cms <command> -h" for a command's flags.
@@ -492,12 +494,15 @@ func report(r *build.Result) {
func cmdImport(args []string) error {
if len(args) == 0 {
return errors.New("usage: hotdog-cms import <wordpress|wxr|ghost|hugo|jekyll|mkdocs> [flags] (hotdog-cms import <from> -h for each)\n" + importer.Ownership)
return errors.New("usage: hotdog-cms import <wordpress|wxr|ghost|hugo|jekyll|mkdocs|fourthwall> [flags] (hotdog-cms import <from> -h for each)\n" + importer.Ownership)
}
from, args := args[0], args[1:]
if from == "mkdocs" {
return importMkDocs(args)
}
if from == "fourthwall" {
return importFourthwall(args)
}
fl := flag.NewFlagSet("import "+from, flag.ExitOnError)
siteDir := fl.String("site", ".", "the HotDog CMS site to import into (made with hotdog-cms new)")
posts := fl.String("posts", "articles", "the collection posts go into")
@@ -631,6 +636,41 @@ func importMkDocs(args []string) error {
return nil
}
// importFourthwall brings a Fourthwall shop's products in, and is run again
// whenever the shop changes.
func importFourthwall(args []string) error {
fl := flag.NewFlagSet("import fourthwall", flag.ExitOnError)
siteDir := fl.String("site", ".", "the HotDog CMS site to bring the products into")
collection := fl.String("collection", "all", "the shop's collection to bring in; all is every public product")
dir := fl.String("dir", "products", "where under content/ the products go")
taxonomy := fl.String("taxonomy", "", "a taxonomy in site.yaml (e.g. tags) to file products under the shop's other collections")
checkout := fl.String("checkout", "", "the shop's checkout address, e.g. https://shop.example.com (default: the shop's own, from Fourthwall)")
currency := fl.String("currency", "", "prices in this currency (default: the shop's)")
photos := fl.Int("photos", 6, "at most this many photos a product; 0 for all")
prune := fl.Bool("prune", false, "delete the pages of products that are no longer in the shop")
_ = fl.Parse(args)
token := os.Getenv("HOTDOG_FOURTHWALL_TOKEN")
if token == "" {
return errors.New("set HOTDOG_FOURTHWALL_TOKEN to the shop's storefront token (Fourthwall: Settings → For Developers → Storefront API)")
}
if _, err := os.Stat(filepath.Join(*siteDir, "layouts", "product.html")); err != nil {
ref, err := packs.Add(*siteDir, "shop", false)
if err != nil {
return fmt.Errorf("adding the shop pack: %w", err)
}
fmt.Printf("added the shop pack (%s)\n", ref.Version)
}
rep, err := importer.SyncFourthwall(importer.FourthwallOptions{
SiteDir: *siteDir, Token: token, Collection: *collection, Dir: *dir, Taxonomy: *taxonomy,
Checkout: *checkout, Currency: *currency, Photos: *photos, Prune: *prune, Log: os.Stdout,
})
if err != nil {
return err
}
fmt.Print("\n" + rep.Markdown() + "Then: hotdog-cms check\n")
return nil
}
func cmdPack(args []string) error {
usage := errors.New("usage: hotdog-cms pack add [-force] <name|folder|git-url[@tag]> | remove <name> | list | check <name|folder|git-url>\n(each takes -site DIR before its argument; default .)")
if len(args) == 0 {
+43 -1
View File
@@ -6,7 +6,7 @@
> belong to someone else, and they say so every time they run.
`hotdog-cms import` brings a site in from WordPress, Hugo, Jekyll, Ghost or
MkDocs, into a HotDog CMS site made with `hotdog-cms new`:
MkDocs, or a shop's products from Fourthwall, into a HotDog CMS site made with `hotdog-cms new`:
hotdog-cms new mysite && cd mysite
hotdog-cms import wordpress -url https://old.example.com
@@ -20,6 +20,7 @@ MkDocs, into a HotDog CMS site made with `hotdog-cms new`:
| Hugo | `import hugo -from ../oldsite` (`-rename posts=articles` by default) |
| Jekyll | `import jekyll -from ../oldsite` |
| MkDocs | `import mkdocs -from ../docs-site` (the folder holding `mkdocs.yml`); see [Documentation from MkDocs](#documentation-from-mkdocs) |
| A Fourthwall shop | `import fourthwall` with the storefront token in `HOTDOG_FOURTHWALL_TOKEN`; run it again whenever the shop changes. See [A shop from Fourthwall](#a-shop-from-fourthwall) |
Every importer takes `-site DIR` (default `.`) and `-overwrite`; the blog
importers take `-posts COLLECTION` (default `articles`) too.
@@ -95,6 +96,47 @@ an inline `<svg>`, a `<script>` or a `style=""` is removed, and the report
lists each. If everyone who writes the docs can be trusted with scripts,
`-trust-html` turns the sanitizer off for the site (`markdown.trust_html`).
## A shop from Fourthwall
hotdog-cms new shop && cd shop
export HOTDOG_FOURTHWALL_TOKEN=ptkn_…
hotdog-cms import fourthwall -taxonomy tags
hotdog-cms check
[Fourthwall](https://fourthwall.com) makes things to order and sells them:
its shop takes the payment, the address and any tax, and sends the order. A
HotDog site can be the shop window, with Fourthwall's checkout behind it.
The token is the shop's **storefront token** (Settings → For Developers →
Storefront API): it can only read the catalog, which is public anyway.
- **Every public product becomes a page** for the shop pack (added if the
site hasn't got it), in `content/products/`: the name, a summary from the
description's first paragraph, the description and Fourthwall's details
(fit, care, returns) as Markdown, the price ("From" when sizes cost more),
and Fourthwall's order, as `weight`.
- **Photos are brought into the site**, at most six a product (`-photos`),
so visitors load nothing from Fourthwall until they check out. Photos on a
transparent background stay WebP, with their transparency.
- **Sizes and colors become variants**, each straight to Fourthwall's
checkout, so Buy now needs no script and no cart. With `cart: true` in
`site.yaml`, Add to cart sits beside it (the shop pack's notes say how).
- **Collections become terms** of the taxonomy `-taxonomy` names (`tags`,
or one of your own in `site.yaml`), so a shop's Hats are under /tags/hats/.
- **Run it again** whenever the shop changes. Products are matched by
Fourthwall's id, so a renamed product keeps its page; photos already
brought in aren't fetched again; pages that haven't changed aren't
written. Fourthwall stays the source: edit products there. Front matter
the site adds itself (`featured: true`, say) is kept. A product that has
left the shop is listed, and deleted with `-prune`. Pages that didn't come
from Fourthwall are never touched.
- **Checkout** is the shop's own address, from Fourthwall. If the shop has
a domain of its own for checkout, give it with `-checkout
https://checkout.example.com`.
Fourthwall serves only **public** products, while a shop behind its
password page still sells through its checkout: a way to try the whole site
before opening.
## The WordPress password
Use an **Application Password** (Users → Profile → Application Passwords),
+11
View File
@@ -252,6 +252,14 @@ func prepareWith(siteDir string, s *site.Site, out string, formOverrides map[str
return nil, err
}
}
if s.Config.Cart.On() {
if err := assets.add(out, "hotdog-cart.js", cartScript); err != nil {
return nil, err
}
if err := assets.add(out, "hotdog-cart.css", cartStyle); err != nil {
return nil, err
}
}
if s.Config.Analytics != nil {
if err := assets.add(out, "hotdog-consent.js", consentScript); err != nil {
return nil, err
@@ -286,6 +294,9 @@ func prepareWith(siteDir string, s *site.Site, out string, formOverrides map[str
return u
}
fm["consent"] = func() template.HTML { return consentTags(s.Config, assets) }
fm["cart"] = func() template.HTML { return cartTags(s.Config, assets) }
fm["cartLink"] = func() template.HTML { return cartLink(s.Config) }
fm["cartOn"] = func() bool { return s.Config.Cart.On() }
fm["verificationTags"] = func() template.HTML { return verificationTags(s.Config) }
fm["consentActive"] = func() bool { return s.Config.Analytics != nil }
fm["privacyFacts"] = func() []site.PrivacyFact { return privacyFacts(s.Config, siteForms) }
+39
View File
@@ -0,0 +1,39 @@
package build
import (
_ "embed"
"html/template"
"git.coffeylabs.org/coffey-labs/hotdog-cms/internal/site"
)
// The cart (site.yaml cart: true): a script that keeps what a visitor picks
// in their own browser and opens the shop's checkout with all of it. The
// shop pack's product forms work without it; with it they gain Add to cart.
var (
//go:embed static/hotdog-cart.js
cartScript []byte
//go:embed static/hotdog-cart.css
cartStyle []byte
)
// cartTags is the cart's stylesheet and script, for a theme's head: {{ cart }}.
func cartTags(cfg *site.Config, a *Assets) template.HTML {
if !cfg.Cart.On() {
return ""
}
js, _ := a.URL("hotdog-cart.js")
css, _ := a.URL("hotdog-cart.css")
return template.HTML(`<link rel="stylesheet" href="` + template.HTMLEscapeString(css) + `">` +
`<script src="` + template.HTMLEscapeString(js) + `" defer data-page="` + template.HTMLEscapeString(cfg.Cart.PagePath()) + `"></script>`)
}
// cartLink is a link to the cart with how many things are in it, shown once
// there's something: {{ cartLink }} in a theme's header.
func cartLink(cfg *site.Config) template.HTML {
if !cfg.Cart.On() {
return ""
}
return template.HTML(`<a class="cart-link" href="` + template.HTMLEscapeString(cfg.Cart.PagePath()) + `" data-cart-link hidden>Cart <span data-cart-count>0</span></a>`)
}
+3
View File
@@ -127,6 +127,9 @@ func privacyFacts(cfg *site.Config, siteForms map[string]*forms.Form) []site.Pri
}
out = append(out, site.PrivacyFact{What: "The " + title + " form: what you write in it", Who: who, Why: "To answer you.", Basis: "Your request: nothing is sent unless you send it."})
}
if cfg.Cart.On() {
out = append(out, site.PrivacyFact{What: "What you put in your cart", Who: "Kept in your own browser (local storage); it reaches the shop only when you check out.", Why: "To remember your cart between pages.", Basis: "Your request: you added it."})
}
for _, h := range cfg.Check.AllowThirdParty {
out = append(out, site.PrivacyFact{What: "Content from " + h, Who: h, Why: "Part of what some pages show.", Basis: "Legitimate interest; " + h + " sees your address when your browser fetches it."})
}
+28
View File
@@ -231,6 +231,31 @@ func funcs(s *site.Site, a *Assets, md *site.Markdown, icons Icons) template.Fun
}
return humanSize(fi.Size())
},
// picture "/media/x.jpg" "alt" ["(min-width: 60rem) 25vw, 50vw"] ["class=x"]:
// a picture from media/ with every size it was published at, so a
// grid of small photos doesn't load the large ones.
"picture": func(src, alt any, more ...string) template.HTML {
sizes, attrs := "", ""
if len(more) > 0 {
sizes = more[0]
}
if len(more) > 1 && more[1] != "" {
for _, kv := range strings.Fields(more[1]) {
k, v, _ := strings.Cut(kv, "=")
if !attrName.MatchString(k) {
continue
}
attrs += " " + k
if v != "" {
attrs += `="` + template.HTMLEscapeString(v) + `"`
}
}
}
return template.HTML(md.Picture(fmt.Sprint(src), fmt.Sprint(alt), sizes, attrs))
},
// pictureAt "/media/x.jpg" 480: the address of its smallest size at
// least that wide, for a thumbnail a script shows.
"pictureAt": func(src any, w int) string { return md.SizeURL(fmt.Sprint(src), w) },
// imageSize "/img/x.jpg" -> {w, h}, for og:image dimensions.
"imageSize": func(p string) (map[string]int, error) {
f, err := os.Open(staticPath(s.Dir, p))
@@ -320,3 +345,6 @@ func humanSize(n int64) string {
func staticPath(siteDir, p string) string {
return filepath.Join(siteDir, "static", filepath.FromSlash(path.Clean("/"+p)))
}
// attrName is an attribute picture lets a template add.
var attrName = regexp.MustCompile(`^(class|loading|decoding|fetchpriority|id|data-[a-z-]+)$`)
+11
View File
@@ -508,6 +508,17 @@ func productData(s *site.Site, p *site.Page) map[string]any {
avail = "https://schema.org/OutOfStock"
}
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
for _, v := range vs {
m, _ := v.(map[string]any)
if pr, ok := amount(m["price"]); ok {
lo, hi = min(lo, pr), max(hi, pr)
}
}
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}
}
}
out["brand"] = map[string]any{"@type": "Brand", "name": s.Config.Name}
// Customers' reviews of the product (the reviews pack). A business's
+27
View File
@@ -0,0 +1,27 @@
/* HotDog CMS cart. Colors come from the theme's variables. */
.cart-link[hidden], [data-cart-add][hidden], [data-cart-suggest][hidden], [data-product][hidden] { display: none; }
.cart-link { display: inline-flex; align-items: center; gap: 6px; text-decoration: none; }
.cart-link [data-cart-count] { min-width: 1.4em; padding: 0 6px; border-radius: 999px; background: var(--accent); color: var(--accent-ink, #fff); font-size: .8em; font-weight: 700; text-align: center; }
.cart-added { margin: 0; color: var(--muted); }
.cart-items { list-style: none; margin: 0 0 20px; padding: 0; display: grid; gap: 14px; }
.cart-item { display: grid; grid-template-columns: 72px minmax(0, 1fr) auto auto auto; gap: 14px; align-items: center; padding-bottom: 14px; border-bottom: 1px solid var(--line, rgba(127, 127, 127, .25)); }
.cart-item img { width: 72px; height: 96px; object-fit: contain; border-radius: calc(var(--radius, 8px) - 2px); background: var(--accent-soft); }
.cart-what { display: grid; gap: 2px; }
.cart-what a { font-weight: 650; }
.cart-variant { color: var(--muted); font-size: .9rem; }
.cart-qty { display: inline-flex; align-items: center; gap: 8px; }
.cart-qty button, .cart-remove { font: inherit; cursor: pointer; border: 1px solid var(--line, currentColor); background: none; color: inherit; border-radius: var(--radius, 8px); }
.cart-qty button { width: 2rem; height: 2rem; }
.cart-qty span { min-width: 1.5em; text-align: center; }
.cart-remove { padding: 6px 10px; font-size: .85rem; }
.cart-line { font-weight: 650; min-width: 5em; text-align: right; }
.cart-total { display: grid; justify-items: end; gap: 8px; }
.cart-total p { margin: 0; }
.cart-note { color: var(--muted); font-size: .88rem; }
.cart-empty { font-size: 1.1rem; }
.cart-suggest { margin-top: 40px; }
@media (max-width: 640px) {
.cart-item { grid-template-columns: 64px minmax(0, 1fr) auto; }
.cart-item img { width: 64px; height: 84px; }
.cart-qty, .cart-line, .cart-remove { grid-column: 2 / -1; justify-self: start; }
}
+159
View File
@@ -0,0 +1,159 @@
// HotDog CMS cart: what a visitor picks is kept in their own browser
// (localStorage) and sent nowhere until they choose Check out, which opens
// the shop's checkout with everything in it. Product forms (the shop pack's,
// marked data-cart) still work without this script: Buy now checks out the
// one thing. With it, Add to cart appears beside Buy now.
(() => {
const me = document.currentScript
if (!me) return
const page = me.dataset.page || '/cart/'
const KEY = 'hotdog-cart'
const empty = () => ({ v: 1, checkout: null, items: [] })
const load = () => {
try {
const c = JSON.parse(localStorage.getItem(KEY))
if (c && c.v === 1 && Array.isArray(c.items)) return c
} catch (e) {}
return empty()
}
const save = (c) => {
if (!c.items.length) c = empty()
try { localStorage.setItem(KEY, JSON.stringify(c)) } catch (e) {}
update(c)
}
const count = (c) => c.items.reduce((n, i) => n + i.qty, 0)
const money = (n, cur) => {
try { return new Intl.NumberFormat(document.documentElement.lang || undefined, { style: 'currency', currency: cur || 'USD' }).format(n) } catch (e) { return n.toFixed(2) }
}
const el = (tag, attrs, ...kids) => {
const e = document.createElement(tag)
for (const k in attrs || {}) {
if (k === 'text') e.textContent = attrs[k]
else if (k.startsWith('on')) e.addEventListener(k.slice(2), attrs[k])
else e.setAttribute(k, attrs[k])
}
for (const kid of kids) if (kid) e.append(kid)
return e
}
// The address that checks out the whole cart: one id:quantity per item,
// joined, in the field the checkout reads.
const checkoutURL = (c) => {
const co = c.checkout
const enc = (s) => encodeURIComponent(s).replace(/%3A/g, ':').replace(/%2C/g, ',')
const items = c.items.map((i) => co.item.replace('{id}', i.id).replace('{qty}', i.qty)).join(co.join)
const q = [enc(co.field) + '=' + enc(items)]
for (const k in co.fields || {}) q.push(enc(k) + '=' + enc(co.fields[k]))
return co.action + (co.action.includes('?') ? '&' : '?') + q.join('&')
}
// The count in the header, wherever the theme put {{ cartLink }}.
const update = (c) => {
const n = count(c)
document.querySelectorAll('[data-cart-count]').forEach((e) => { e.textContent = n })
document.querySelectorAll('[data-cart-link]').forEach((e) => { e.hidden = n === 0 })
const view = document.querySelector('[data-cart-view]')
if (view) render(view, c)
}
// Product forms: Add to cart beside Buy now.
document.querySelectorAll('form[data-cart]').forEach((form) => {
const add = form.querySelector('[data-cart-add]')
if (!add) return
add.hidden = false
add.addEventListener('click', () => {
if (!form.reportValidity()) return
const pick = form.querySelector('[data-cart-variant]:checked') || form.querySelector('input[type=hidden][data-cart-variant]')
if (!pick) return
const d = form.dataset
const fields = {}
form.querySelectorAll('input[type=hidden]').forEach((h) => { if (h.name && h.name !== d.field) fields[h.name] = h.value })
const co = { action: form.action, field: d.field, item: d.item || '{id}:{qty}', join: d.join || ',', fields }
const c = load()
if (c.checkout && c.checkout.action !== co.action) {
status(form, 'This comes from a different shop than what’s in your cart. Check out your cart first, then add it.')
return
}
c.checkout = co
const id = pick.dataset.id
const have = c.items.find((i) => i.id === id)
if (have) have.qty = Math.min(have.qty + 1, 99)
else c.items.push({ id, qty: 1, title: d.title, variant: pick.dataset.name || '', price: parseFloat(pick.dataset.price) || 0, currency: d.currency || 'USD', image: d.image || '', href: d.href || location.pathname })
save(c)
status(form, 'Added to your cart.', true)
})
})
const status = (form, text, link) => {
let s = form.querySelector('.cart-added')
if (!s) {
s = el('p', { class: 'cart-added', role: 'status' })
form.append(s)
}
s.replaceChildren(text)
if (link) s.append(' ', el('a', { href: page, text: 'View your cart (' + count(load()) + ')' }))
}
// The cart page.
const render = (view, c) => {
const d = view.dataset
const list = el('ul', { class: 'cart-items' })
let total = 0
let cur = 'USD'
for (const i of c.items) {
total += i.price * i.qty
cur = i.currency || cur
const set = (q) => {
const now = load()
const it = now.items.find((x) => x.id === i.id)
if (!it) return
it.qty = Math.max(0, Math.min(q, 99))
now.items = now.items.filter((x) => x.qty > 0)
save(now)
}
list.append(el('li', { class: 'cart-item' },
i.image ? el('img', { src: i.image, alt: '', width: '72', height: '96', loading: 'lazy' }) : null,
el('div', { class: 'cart-what' },
el('a', { href: i.href, text: i.title }),
i.variant ? el('span', { class: 'cart-variant', text: i.variant }) : null),
el('div', { class: 'cart-qty', role: 'group', 'aria-label': 'How many ' + i.title + (i.variant ? ', ' + i.variant : '') },
el('button', { type: 'button', 'aria-label': 'One fewer', text: '−', onclick: () => set(i.qty - 1) }),
el('span', { 'aria-live': 'polite', text: String(i.qty) }),
el('button', { type: 'button', 'aria-label': 'One more', text: '+', onclick: () => set(i.qty + 1) })),
el('span', { class: 'cart-line', text: money(i.price * i.qty, i.currency) }),
el('button', { type: 'button', class: 'cart-remove', text: 'Remove', onclick: () => set(0) })))
}
if (!c.items.length) {
view.replaceChildren(el('p', { class: 'cart-empty', text: 'Your cart is empty.' }),
d.shop ? el('p', {}, el('a', { class: 'btn', href: d.shop, text: 'Browse the shop' })) : null)
} else {
view.replaceChildren(list,
el('div', { class: 'cart-total' },
el('p', {}, 'Subtotal ', el('strong', { text: money(total, cur) })),
el('p', { class: 'cart-note', text: 'Shipping and any tax are added at checkout, where the prices are confirmed.' }),
el('a', { class: 'btn primary cart-checkout', href: checkoutURL(c), rel: 'noopener', text: 'Check out' })))
}
suggest(c)
}
// Suggestions: products not in the cart, those sharing a tag with
// something in it first, in the shop's own order.
const suggest = (c) => {
const box = document.querySelector('[data-cart-suggest]')
if (!box) return
const want = parseInt(box.dataset.count, 10) || 4
const inCart = new Set(c.items.map((i) => i.href))
const cards = [...box.querySelectorAll('[data-product]')]
const tagsOf = (e) => (e.dataset.tags || '').split(',').filter(Boolean)
const cartTags = new Set(cards.filter((e) => inCart.has(e.dataset.product)).flatMap(tagsOf))
const pick = cards.filter((e) => !inCart.has(e.dataset.product))
.map((e, n) => ({ e, n, score: tagsOf(e).some((t) => cartTags.has(t)) ? 0 : 1 }))
.sort((a, b) => a.score - b.score || a.n - b.n)
.slice(0, want).map((x) => x.e)
cards.forEach((e) => { e.hidden = !pick.includes(e) })
box.hidden = pick.length === 0
}
window.addEventListener('storage', (e) => { if (e.key === KEY) update(load()) })
update(load())
})()
+588
View File
@@ -0,0 +1,588 @@
package importer
import (
"encoding/json"
"errors"
"fmt"
"html"
"io"
"net/http"
"net/url"
"os"
"path"
"path/filepath"
"regexp"
"slices"
"strconv"
"strings"
"time"
"git.coffeylabs.org/coffey-labs/hotdog-cms/internal/media"
)
// Fourthwall: a print-on-demand shop whose Storefront API hands out its
// catalog to anyone with the shop's storefront token. Each product becomes a
// page for the shop pack, with its photos brought into the site, and its
// sizes and colors as variants whose Buy goes to the shop's own checkout
// (cart/checkout?products=<variant>:1), so the site needs no cart and no
// script. Unlike the other imports this one is run again whenever the shop
// changes: Fourthwall stays the source, and a product's page is rewritten
// from it, keeping only the front matter the site added itself.
// FourthwallAPI is the Storefront API.
const FourthwallAPI = "https://storefront-api.fourthwall.com/v1"
// FourthwallOptions says which shop and where its products go.
type FourthwallOptions struct {
SiteDir string
Token string // the storefront token (ptkn_…), from Settings → For Developers
Collection string // the shop's collection to bring in; "all" is every public product
Dir string // where under content/ products go: "products", the shop pack's collection
Taxonomy string // front matter key for the shop's other collections, e.g. "tags"; "" leaves them out
Checkout string // the checkout's address, e.g. https://shop.example.com; "" asks the shop
Currency string // prices in this currency; "" is the shop's own
Photos int // at most this many photos a product; 0 is all of them
Prune bool // delete pages of products no longer in the shop
API string // the API's address; "" is FourthwallAPI
Client *http.Client
Log io.Writer
}
// FourthwallReport is what a sync did.
type FourthwallReport struct {
Written []string // new or changed pages
Unchanged int
Pictures int // photos downloaded
Gone []string // pages whose product left the shop
Removed []string // …deleted, with Prune
Failed map[string]string // photo address → why
Checkout string
}
type fwPaged[T any] struct {
Results []T `json:"results"`
Paging struct {
HasNextPage bool `json:"hasNextPage"`
} `json:"paging"`
}
type fwImage struct {
ID string `json:"id"`
URL string `json:"url"`
Width int `json:"width"`
Height int `json:"height"`
}
type fwProduct struct {
ID string `json:"id"`
Name string `json:"name"`
Slug string `json:"slug"`
Description string `json:"description"`
State struct {
Type string `json:"type"`
} `json:"state"`
Images []fwImage `json:"images"`
Variants []fwVariant `json:"variants"`
Additional []struct {
Title string `json:"title"`
BodyHTML string `json:"bodyHtml"`
} `json:"additionalInformation"`
UpdatedAt string `json:"updatedAt"`
}
type fwVariant struct {
ID string `json:"id"`
Name string `json:"name"`
SKU string `json:"sku"`
UnitPrice struct {
Value float64 `json:"value"`
Currency string `json:"currency"`
} `json:"unitPrice"`
Attributes struct {
Description string `json:"description"`
Color *struct {
Name string `json:"name"`
Swatch string `json:"swatch"`
} `json:"color"`
Size *struct {
Name string `json:"name"`
} `json:"size"`
} `json:"attributes"`
Stock struct {
Type string `json:"type"`
InStock *int `json:"inStock"`
} `json:"stock"`
}
func (v fwVariant) soldOut() bool {
return v.Stock.Type == "LIMITED" && v.Stock.InStock != nil && *v.Stock.InStock <= 0
}
type fwCollection struct {
Name string `json:"name"`
Slug string `json:"slug"`
}
// fourthwallKeys is the front matter a sync owns; anything else in a
// product's page was added on the site and is kept.
var fourthwallKeys = []string{"title", "summary", "price", "price_from", "currency", "weight", "photos", "checkout", "variants", "choose", "buy", "options", "sold_out", "sku", "fourthwall"}
// SyncFourthwall brings a Fourthwall shop's products into a site.
func SyncFourthwall(opt FourthwallOptions) (*FourthwallReport, error) {
if opt.Token == "" {
return nil, errors.New("no storefront token: make one in Fourthwall under Settings → For Developers → Storefront API")
}
if _, err := os.Stat(filepath.Join(opt.SiteDir, "site.yaml")); err != nil {
return nil, fmt.Errorf("no site at %s (run hotdog-cms new first): %w", opt.SiteDir, err)
}
if opt.API == "" {
opt.API = FourthwallAPI
}
if opt.Client == nil {
opt.Client = &http.Client{Timeout: 30 * time.Second}
}
if opt.Log == nil {
opt.Log = io.Discard
}
if opt.Collection == "" {
opt.Collection = "all"
}
opt.Dir = safeDir(opt.Dir)
if opt.Dir == "" {
opt.Dir = "products"
}
get := func(p string, q url.Values, into any) error {
if q == nil {
q = url.Values{}
}
q.Set("storefront_token", opt.Token)
if opt.Currency != "" {
q.Set("currency", opt.Currency)
}
res, err := opt.Client.Get(strings.TrimRight(opt.API, "/") + p + "?" + q.Encode())
if err != nil {
return err
}
defer res.Body.Close()
if res.StatusCode == http.StatusUnauthorized || res.StatusCode == http.StatusForbidden {
return fmt.Errorf("Fourthwall turned the storefront token down (%s)", res.Status)
}
if res.StatusCode != http.StatusOK {
return fmt.Errorf("Fourthwall: %s for %s", res.Status, p)
}
return json.NewDecoder(io.LimitReader(res.Body, 32<<20)).Decode(into)
}
products := func(collection string) ([]fwProduct, error) {
var all []fwProduct
for page := 0; page < 200; page++ {
var pg fwPaged[fwProduct]
q := url.Values{"page": {strconv.Itoa(page)}, "size": {"50"}}
if err := get("/collections/"+url.PathEscape(collection)+"/products", q, &pg); err != nil {
return nil, err
}
all = append(all, pg.Results...)
if !pg.Paging.HasNextPage {
break
}
}
return all, nil
}
rep := &FourthwallReport{Failed: map[string]string{}}
rep.Checkout = strings.TrimRight(opt.Checkout, "/")
if rep.Checkout == "" {
var shop struct {
Domain string `json:"domain"`
PublicDomain string `json:"publicDomain"`
}
if err := get("/shop", nil, &shop); err != nil {
return nil, err
}
if shop.PublicDomain == "" {
return nil, errors.New("Fourthwall didn't say where the shop's checkout is; give it with -checkout")
}
rep.Checkout = "https://" + shop.PublicDomain
}
if u, err := url.Parse(rep.Checkout); err != nil || u.Scheme != "https" || u.Host == "" {
return nil, fmt.Errorf("the checkout address %q isn't an https:// address", rep.Checkout)
}
list, err := products(opt.Collection)
if err != nil {
return nil, err
}
fmt.Fprintf(opt.Log, "%d product(s) in %q\n", len(list), opt.Collection)
// The shop's other collections, as terms of a taxonomy.
terms := map[string][]string{} // product id → collection names
if opt.Taxonomy != "" {
for page := 0; page < 50; page++ {
var pg fwPaged[fwCollection]
if err := get("/collections", url.Values{"page": {strconv.Itoa(page)}, "size": {"50"}}, &pg); err != nil {
return nil, err
}
for _, c := range pg.Results {
if c.Slug == "all" || c.Slug == opt.Collection {
continue
}
in, err := products(c.Slug)
if err != nil {
return nil, err
}
for _, p := range in {
terms[p.ID] = append(terms[p.ID], c.Name)
}
}
if !pg.Paging.HasNextPage {
break
}
}
}
root, err := os.OpenRoot(opt.SiteDir)
if err != nil {
return nil, err
}
defer root.Close()
exists := func(rel string) bool {
_, err := root.Stat(filepath.FromSlash(rel))
return err == nil
}
// The pages a previous sync wrote, by product id.
previous := map[string]string{}
contentDir := path.Join("content", opt.Dir)
if entries, err := os.ReadDir(filepath.Join(opt.SiteDir, filepath.FromSlash(contentDir))); err == nil {
for _, e := range entries {
if e.IsDir() || !strings.HasSuffix(e.Name(), ".md") {
continue
}
rel := path.Join(contentDir, e.Name())
raw, err := root.ReadFile(filepath.FromSlash(rel))
if err != nil {
continue
}
fm, _, err := splitFront(string(raw))
if err != nil {
continue
}
if fw, ok := fm["fourthwall"].(map[string]any); ok {
if id := fmString(fw, "id"); id != "" {
previous[id] = rel
}
}
}
}
seen := map[string]bool{}
for i, p := range list {
if p.ID == "" || len(p.Variants) == 0 {
continue
}
seen[p.ID] = true
slug := slugify(p.Slug)
if slug == "" {
slug = slugify(p.Name)
}
if slug == "" {
slug = "product"
}
rel := path.Join(contentDir, slug+".md")
if old, ok := previous[p.ID]; ok {
rel = old // a product renamed in the shop keeps its page
}
// What the site already has: its own front matter, and the photos a
// previous sync brought in, by Fourthwall's id.
kept := map[string]any{}
havePhoto := map[string]string{}
if raw, err := root.ReadFile(filepath.FromSlash(rel)); err == nil {
fm, _, err := splitFront(string(raw))
if err == nil {
if _, ours := fm["fourthwall"]; !ours {
fmt.Fprintf(opt.Log, " %s is already there and isn't from Fourthwall; left alone\n", rel)
continue
}
for k, v := range fm {
if !slices.Contains(fourthwallKeys, k) && k != opt.Taxonomy {
kept[k] = v
}
}
for _, ph := range listOf(fm["photos"]) {
m, _ := ph.(map[string]any)
if id, img := fmString(m, "source"), fmString(m, "image"); id != "" && img != "" && exists(path.Join("static", img)) {
havePhoto[id] = img
}
}
}
}
// Photos.
mediaDir := path.Join("shop", slug)
images := p.Images
if opt.Photos > 0 && len(images) > opt.Photos {
images = images[:opt.Photos]
}
var photos []map[string]any
using := map[string]bool{}
for n, im := range images {
alt := p.Name
if len(images) > 1 {
alt = fmt.Sprintf("%s, photo %d of %d", p.Name, n+1, len(images))
}
if img, ok := havePhoto[im.ID]; ok {
photos = append(photos, map[string]any{"image": img, "alt": alt, "source": im.ID})
using[img] = true
continue
}
data, err := fetchWith(opt.Client, im.URL)
if err != nil {
rep.Failed[im.URL] = err.Error()
continue
}
img, err := media.Process(data, strconv.Itoa(n+1)+path.Ext(strings.SplitN(im.URL, "?", 2)[0]), mediaDir, func(p string) bool { return exists(p) })
if err != nil {
rep.Failed[im.URL] = err.Error()
continue
}
for _, f := range img.Files {
if err := writeInSite(opt.SiteDir, path.Join("static", f.Path), f.Data); err != nil {
return nil, err
}
}
rep.Pictures++
photos = append(photos, map[string]any{"image": img.URL, "alt": alt, "source": im.ID})
using[img.URL] = true
}
// Photos the product no longer has go, with their smaller sizes.
if entries, err := os.ReadDir(filepath.Join(opt.SiteDir, "static", "media", filepath.FromSlash(mediaDir))); err == nil {
for _, e := range entries {
name := e.Name()
main := name
if m := media.VariantRe.FindStringSubmatch(name); m != nil {
main = m[1]
}
main = strings.TrimSuffix(main, path.Ext(main))
inUse := false
for u := range using {
if strings.TrimSuffix(path.Base(u), path.Ext(u)) == main {
inUse = true
}
}
if !inUse {
_ = root.Remove(filepath.Join("static", "media", filepath.FromSlash(mediaDir), name))
}
}
}
// Variants: one per color and size, each with its own checkout.
// Colors head groups of sizes only when there's more than one.
colors, sized := map[string]bool{}, false
for _, v := range p.Variants {
if c := v.Attributes.Color; c != nil && c.Name != "" {
colors[c.Name] = true
}
if v.Attributes.Size != nil && v.Attributes.Size.Name != "" {
sized = true
}
}
cur := ""
lowest, highest := p.Variants[0].UnitPrice.Value, p.Variants[0].UnitPrice.Value
var variants []map[string]any
allSold := true
for _, v := range p.Variants {
if cur == "" {
cur = v.UnitPrice.Currency
}
lowest = min(lowest, v.UnitPrice.Value)
highest = max(highest, v.UnitPrice.Value)
name := ""
if v.Attributes.Size != nil {
name = v.Attributes.Size.Name
}
m := map[string]any{"price": v.UnitPrice.Value, "id": v.ID, "buy": fwBuy(rep.Checkout, v.ID, cur)}
if c := v.Attributes.Color; c != nil && c.Name != "" {
if len(colors) > 1 {
m["group"] = c.Name
}
if c.Swatch != "" {
m["swatch"] = c.Swatch
}
if name == "" {
name = c.Name
}
}
if name == "" {
name = v.Attributes.Description
}
if name == "" {
name = v.Name
}
m["name"] = name
if v.SKU != "" {
m["sku"] = v.SKU
}
if v.soldOut() {
m["sold_out"] = true
} else {
allSold = false
}
variants = append(variants, m)
}
fm := map[string]any{}
for k, v := range kept {
fm[k] = v
}
fm["title"] = p.Name
if s := plainFirstParagraph(p.Description); s != "" {
fm["summary"] = shortSummary(s)
}
fm["price"] = lowest
if highest > lowest {
fm["price_from"] = true
} else {
delete(fm, "price_from")
}
fm["currency"] = cur
if _, ok := kept["weight"]; !ok {
fm["weight"] = i + 1 // the shop's own order
}
if len(photos) > 0 {
fm["photos"] = photos
}
// The checkout takes any number of variants, as id:quantity,…: one
// with Buy now, all the cart's with a cart.
fm["checkout"] = map[string]any{"action": rep.Checkout + "/cart/checkout", "field": "products", "item": "{id}:{qty}", "join": ",", "fields": map[string]any{"currency": cur}}
fm["variants"] = variants
if sized {
fm["choose"] = "Size"
} else {
delete(fm, "choose")
}
if p.State.Type == "SOLD_OUT" || allSold {
fm["sold_out"] = true
}
if opt.Taxonomy != "" && len(terms[p.ID]) > 0 {
fm[opt.Taxonomy] = terms[p.ID]
}
fm["fourthwall"] = map[string]any{"id": p.ID, "slug": p.Slug, "updated": p.UpdatedAt}
body := ToMarkdown(p.Description).Markdown
for _, a := range p.Additional {
if t := strings.TrimSpace(a.Title); t != "" && strings.TrimSpace(a.BodyHTML) != "" {
body += "\n\n## " + t + "\n\n" + ToMarkdown(a.BodyHTML).Markdown
}
}
doc, err := frontMatterIn(fm, []string{"title", "summary", "price", "price_from", "currency", "weight", "sold_out", "photos", "choose", "variants", "checkout", "fourthwall"})
if err != nil {
return nil, err
}
out := "---\n" + doc + "---\n\n" + strings.TrimSpace(body) + "\n"
if old, err := root.ReadFile(filepath.FromSlash(rel)); err == nil && string(old) == out {
rep.Unchanged++
continue
}
if err := writeInSite(opt.SiteDir, rel, []byte(out)); err != nil {
return nil, err
}
rep.Written = append(rep.Written, rel)
fmt.Fprintf(opt.Log, " %s\n", rel)
}
// Products that have left the shop.
for id, rel := range previous {
if seen[id] {
continue
}
if !opt.Prune {
rep.Gone = append(rep.Gone, rel)
continue
}
if err := root.Remove(filepath.FromSlash(rel)); err == nil {
rep.Removed = append(rep.Removed, rel)
slug := strings.TrimSuffix(path.Base(rel), ".md")
_ = root.RemoveAll(filepath.Join("static", "media", "shop", slug))
}
}
slices.Sort(rep.Gone)
slices.Sort(rep.Removed)
return rep, nil
}
// fwBuy is a variant's checkout: one of it, straight to the shop's checkout.
func fwBuy(checkout, variant, cur string) string {
q := url.Values{"products": {variant + ":1"}}
if cur != "" {
q.Set("currency", cur)
}
return checkout + "/cart/checkout?" + q.Encode()
}
func fetchWith(c *http.Client, u string) ([]byte, error) {
p, err := url.Parse(u)
if err != nil || (p.Scheme != "https" && p.Scheme != "http") {
return nil, fmt.Errorf("not a web address")
}
res, err := c.Get(u)
if err != nil {
return nil, err
}
defer res.Body.Close()
if res.StatusCode != http.StatusOK {
return nil, fmt.Errorf("%s", res.Status)
}
return io.ReadAll(io.LimitReader(res.Body, media.MaxBytes+1))
}
var (
firstPara = regexp.MustCompile(`(?is)<p[^>]*>(.*?)</p>`)
anyTag = regexp.MustCompile(`<[^>]+>`)
fwSpaces = regexp.MustCompile(`\s+`)
)
// plainFirstParagraph is a description's first paragraph as plain text.
func plainFirstParagraph(h string) string {
s := h
if m := firstPara.FindStringSubmatch(h); m != nil {
s = m[1]
}
s = html.UnescapeString(anyTag.ReplaceAllString(s, " "))
return strings.TrimSpace(fwSpaces.ReplaceAllString(s, " "))
}
func listOf(v any) []any {
l, _ := v.([]any)
return l
}
// Markdown is the sync's report, for the person who ran it.
func (r *FourthwallReport) Markdown() string {
var b strings.Builder
fmt.Fprintf(&b, "%d page(s) written, %d unchanged, %d photo(s) brought in. Buy goes to %s.\n", len(r.Written), r.Unchanged, r.Pictures, r.Checkout)
if len(r.Gone) > 0 {
fmt.Fprintf(&b, "\nNo longer in the shop (run again with -prune to delete them):\n")
for _, g := range r.Gone {
fmt.Fprintf(&b, " %s\n", g)
}
}
for _, g := range r.Removed {
fmt.Fprintf(&b, " deleted %s\n", g)
}
if len(r.Failed) > 0 {
fmt.Fprintf(&b, "\nPhotos that couldn't be brought in:\n")
for _, u := range sortedFailed(r.Failed) {
fmt.Fprintf(&b, " %s: %s\n", u, r.Failed[u])
}
}
return b.String()
}
func sortedFailed(m map[string]string) []string {
out := make([]string, 0, len(m))
for k := range m {
out = append(out, k)
}
slices.Sort(out)
return out
}
+163
View File
@@ -0,0 +1,163 @@
package importer
import (
"bytes"
"encoding/json"
"image"
"image/color"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"testing"
"git.coffeylabs.org/coffey-labs/hotdog-cms/internal/media/webpenc"
)
// fakeFourthwall is a Storefront API with a tee (two prices, a sold-out
// size) and a cap, and a collection holding the cap.
func fakeFourthwall(t *testing.T, products *[]map[string]any) *httptest.Server {
t.Helper()
cut := image.NewRGBA(image.Rect(0, 0, 600, 800))
cut.Set(300, 400, color.RGBA{10, 10, 10, 255})
var pic bytes.Buffer
if err := webpenc.Encode(&pic, cut, webpenc.Options{Lossless: true}); err != nil {
t.Fatal(err)
}
var srv *httptest.Server
srv = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if strings.HasPrefix(r.URL.Path, "/img/") {
w.Write(pic.Bytes())
return
}
if r.URL.Query().Get("storefront_token") != "ptkn_test" {
http.Error(w, "no", http.StatusUnauthorized)
return
}
paged := func(v any) {
json.NewEncoder(w).Encode(map[string]any{"results": v, "paging": map[string]any{"hasNextPage": false}})
}
switch r.URL.Path {
case "/shop":
json.NewEncoder(w).Encode(map[string]any{"publicDomain": "shop.example"})
case "/collections":
paged([]any{map[string]any{"name": "All", "slug": "all"}, map[string]any{"name": "Hats", "slug": "hats"}})
case "/collections/all/products":
paged(*products)
case "/collections/hats/products":
var hats []map[string]any
for _, p := range *products {
if p["slug"] == "cap" {
hats = append(hats, p)
}
}
paged(hats)
default:
http.NotFound(w, r)
}
}))
t.Cleanup(srv.Close)
return srv
}
func fwVariantJSON(id, color, size string, price float64, stock any) map[string]any {
attrs := map[string]any{"color": map[string]any{"name": color, "swatch": "#000000"}}
if size != "" {
attrs["size"] = map[string]any{"name": size}
}
st := map[string]any{"type": "UNLIMITED"}
if stock != nil {
st = map[string]any{"type": "LIMITED", "inStock": stock}
}
return map[string]any{"id": id, "name": "x", "sku": "SKU-" + id, "unitPrice": map[string]any{"value": price, "currency": "USD"}, "attributes": attrs, "stock": st}
}
func TestFourthwallSync(t *testing.T) {
var products []map[string]any
srv := fakeFourthwall(t, &products)
img := func(id string) map[string]any {
return map[string]any{"id": id, "url": srv.URL + "/img/" + id + ".webp"}
}
products = []map[string]any{
{"id": "p1", "name": "Plain T-Shirt", "slug": "plain-t-shirt", "description": "<p>A logo on a <em>white</em> tee &amp; more.</p><ul><li>Cotton</li></ul>",
"state": map[string]any{"type": "AVAILABLE"}, "images": []any{img("a"), img("b"), img("c")},
"variants": []any{fwVariantJSON("v1", "White", "S", 24.4, nil), fwVariantJSON("v2", "White", "2XL", 26.4, nil), fwVariantJSON("v3", "White", "3XL", 28.4, 0)},
"additionalInformation": []any{map[string]any{"title": "More details", "bodyHtml": "<ul><li>Relaxed fit</li></ul>"}}},
{"id": "p2", "name": "Cap", "slug": "cap", "description": "<p>A cap.</p>",
"state": map[string]any{"type": "AVAILABLE"}, "images": []any{img("d")},
"variants": []any{fwVariantJSON("c1", "Black", "One size", 21.6, nil)}},
}
dir := starterSite(t)
opt := FourthwallOptions{SiteDir: dir, Token: "ptkn_test", API: srv.URL, Taxonomy: "tags", Photos: 2}
rep, err := SyncFourthwall(opt)
if err != nil {
t.Fatal(err)
}
if len(rep.Written) != 2 || rep.Pictures != 3 || rep.Checkout != "https://shop.example" {
t.Fatalf("report: %+v", rep)
}
tee := read(t, filepath.Join(dir, "content/products/plain-t-shirt.md"))
for _, want := range []string{
"title: Plain T-Shirt\nsummary: A logo on a white tee & more.\nprice: 24.4\nprice_from: true\ncurrency: USD\nweight: 1\n",
"image: /media/shop/plain-t-shirt/1.webp", "alt: Plain T-Shirt, photo 2 of 2", "source: b",
"choose: Size", "name: 2XL", "id: v2", "sold_out: true", "item: '{id}:{qty}'",
"action: https://shop.example/cart/checkout",
"buy: https://shop.example/cart/checkout?currency=USD&products=v1%3A1",
"A logo on a *white* tee & more.", "## More details", "- Relaxed fit",
} {
if !strings.Contains(tee, want) {
t.Errorf("tee page lacks %q:\n%s", want, tee)
}
}
if strings.Contains(tee, "group:") || strings.Contains(tee, "photo 3") {
t.Errorf("one color needs no groups, and -photos 2 keeps two:\n%s", tee)
}
cap := read(t, filepath.Join(dir, "content/products/cap.md"))
if !strings.Contains(cap, "tags: [Hats]") || strings.Contains(cap, "choose:") == false {
t.Errorf("cap page:\n%s", cap)
}
if _, err := os.Stat(filepath.Join(dir, "static/media/shop/plain-t-shirt/2-480w.webp")); err != nil {
t.Fatal("smaller sizes missing")
}
// Run again: nothing changes, nothing is fetched. A key the site added
// stays; a photo the shop dropped goes.
os.WriteFile(filepath.Join(dir, "content/products/cap.md"), []byte(strings.Replace(cap, "title: Cap\n", "title: Cap\nfeatured: true\n", 1)), 0o644)
if rep, err = SyncFourthwall(opt); err != nil || len(rep.Written) != 1 || rep.Unchanged != 1 || rep.Pictures != 0 {
t.Fatalf("second run: %v %+v", err, rep)
}
if !strings.Contains(read(t, filepath.Join(dir, "content/products/cap.md")), "featured: true") {
t.Fatal("the site's own front matter was dropped")
}
products[0]["images"] = []any{img("a")}
if _, err = SyncFourthwall(opt); err != nil {
t.Fatal(err)
}
if _, err := os.Stat(filepath.Join(dir, "static/media/shop/plain-t-shirt/2.webp")); !os.IsNotExist(err) {
t.Fatal("a dropped photo stayed")
}
// A product leaves the shop: reported, then deleted with Prune. A page
// the site wrote itself is never touched.
os.WriteFile(filepath.Join(dir, "content/products/mine.md"), []byte("---\ntitle: Mine\n---\n"), 0o644)
products = products[:1]
if rep, err = SyncFourthwall(opt); err != nil || len(rep.Gone) != 1 || rep.Gone[0] != "content/products/cap.md" {
t.Fatalf("gone: %v %+v", err, rep)
}
opt.Prune = true
if rep, err = SyncFourthwall(opt); err != nil || len(rep.Removed) != 1 {
t.Fatalf("prune: %v %+v", err, rep)
}
if _, err := os.Stat(filepath.Join(dir, "content/products/mine.md")); err != nil {
t.Fatal("pruned the site's own page")
}
if _, err := os.Stat(filepath.Join(dir, "static/media/shop/cap")); !os.IsNotExist(err) {
t.Fatal("the pruned product's photos stayed")
}
opt.Token = "wrong"
if _, err := SyncFourthwall(opt); err == nil || !strings.Contains(err.Error(), "turned the storefront token down") {
t.Fatalf("bad token: %v", err)
}
}
+5 -1
View File
@@ -371,7 +371,11 @@ func oldPath(u string) string {
}
func frontMatter(fm map[string]any) (string, error) {
order := []string{"title", "date", "updated", "summary", "tags", "author", "draft", "image", "image_alt", "format"}
return frontMatterIn(fm, []string{"title", "date", "updated", "summary", "tags", "author", "draft", "image", "image_alt", "format"})
}
// frontMatterIn writes the keys in order first, then the rest A to Z.
func frontMatterIn(fm map[string]any, order []string) (string, error) {
m := &yaml.Node{Kind: yaml.MappingNode}
add := func(k string, v any) error {
var n yaml.Node
+14 -4
View File
@@ -146,10 +146,14 @@ func Process(data []byte, name, dir string, taken func(string) bool) (*Image, er
// The format: photographs stay JPEG; PNG and GIF stay PNG, since they're
// usually screenshots and drawings that JPEG would smear; WebP becomes
// JPEG unless it has transparency.
// JPEG, or stays WebP when it has transparency (a product photographed
// on nothing, say): as a PNG it would be ten times the size.
typ, ext := "image/png", ".png"
if kind == "image/jpeg" {
switch kind {
case "image/jpeg":
typ, ext = "image/jpeg", ".jpg"
case "image/webp":
typ, ext = "image/webp", ".webp"
}
base := slug(strings.TrimSuffix(path.Base(name), path.Ext(name)))
@@ -171,9 +175,12 @@ func Process(data []byte, name, dir string, taken func(string) bool) (*Image, er
img.URL = "/" + stem + ext
}
var buf bytes.Buffer
if typ == "image/jpeg" {
switch typ {
case "image/jpeg":
err = jpeg.Encode(&buf, px, &jpeg.Options{Quality: JPEGQuality})
} else {
case "image/webp":
err = webpenc.Encode(&buf, px, webpenc.Options{Quality: WebPQuality})
default:
err = (&png.Encoder{CompressionLevel: png.BestCompression}).Encode(&buf, px)
}
if err != nil {
@@ -184,6 +191,9 @@ func Process(data []byte, name, dir string, taken func(string) bool) (*Image, er
p = fmt.Sprintf("%s-%dw%s", stem, w, ext)
}
img.Files = append(img.Files, File{Path: p, Width: w, Height: h, Data: buf.Bytes()})
if typ == "image/webp" {
continue // it is the WebP
}
// A WebP beside it, for browsers that take one, when it's smaller.
var wb bytes.Buffer
if err := webpenc.Encode(&wb, px, webpenc.Options{Quality: WebPQuality, Lossless: typ == "image/png"}); err != nil {
+54 -1
View File
@@ -12,6 +12,8 @@ import (
"strings"
"testing"
"git.coffeylabs.org/coffey-labs/hotdog-cms/internal/media/webpenc"
xwebp "golang.org/x/image/webp"
)
@@ -101,7 +103,7 @@ func decodeAny(t *testing.T, f File) image.Image {
err error
)
switch {
case f.WebP:
case f.WebP || strings.HasSuffix(f.Path, ".webp"):
got, err = xwebp.Decode(bytes.NewReader(f.Data))
case strings.HasSuffix(f.Path, ".png"):
got, err = png.Decode(bytes.NewReader(f.Data))
@@ -292,3 +294,54 @@ func TestWebPSmallerAndRight(t *testing.T) {
t.Fatal("WebP colors are wrong")
}
}
// A product photographed on nothing comes as a WebP with transparency: it
// stays WebP, smaller sizes and all, rather than becoming a PNG ten times
// the size. An opaque WebP still becomes JPEG.
func TestWebPWithTransparencyStaysWebP(t *testing.T) {
cut := image.NewRGBA(image.Rect(0, 0, 1200, 1600))
for y := 400; y < 1200; y++ {
for x := 300; x < 900; x++ {
cut.Set(x, y, color.RGBA{uint8(x), uint8(y), 60, 255})
}
}
var b bytes.Buffer
if err := webpenc.Encode(&b, cut, webpenc.Options{Lossless: true}); err != nil {
t.Fatal(err)
}
img, err := Process(b.Bytes(), "1.webp", "shop/tee", none)
if err != nil {
t.Fatal(err)
}
if img.Type != "image/webp" || img.URL != "/media/shop/tee/1.webp" {
t.Fatalf("got %s %s", img.Type, img.URL)
}
var paths []string
for _, f := range img.Files {
paths = append(paths, f.Path)
if !strings.HasSuffix(f.Path, ".webp") {
t.Fatalf("%s isn't WebP", f.Path)
}
if _, _, _, a := decodeAny(t, f).At(5, 5).RGBA(); a != 0 {
t.Fatalf("%s: transparency lost", f.Path)
}
}
if want := "media/shop/tee/1.webp media/shop/tee/1-480w.webp media/shop/tee/1-960w.webp"; strings.Join(paths, " ") != want {
t.Fatalf("files %v", paths)
}
opaque := image.NewRGBA(image.Rect(0, 0, 300, 200))
for i := range opaque.Pix {
opaque.Pix[i] = 200
if i%4 == 3 {
opaque.Pix[i] = 255
}
}
b.Reset()
if err := webpenc.Encode(&b, opaque, webpenc.Options{Quality: 90}); err != nil {
t.Fatal(err)
}
if img, err = Process(b.Bytes(), "2.webp", "shop/tee", none); err != nil || img.Type != "image/jpeg" || img.URL != "/media/shop/tee/2.jpg" {
t.Fatalf("opaque WebP: %v %+v", err, img)
}
}
+17 -3
View File
@@ -159,10 +159,19 @@ func TestBundledPacksBuildAndPass(t *testing.T) {
{"content/products/_index.md", "---\ntitle: Shop\nsummary: Things to buy.\n---\n"},
{"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/cart.md", "---\ntitle: Your cart\nlayout: cart\nsuggest: 3\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/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"},
"products/mug/index.html": {"Sold out", "OutOfStock"},
"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"},
"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"},
"products/mug/index.html": {"Sold out", "OutOfStock"},
}},
{"contact-forms", []page{
{"content/quote.md", "---\ntitle: Get a quote\nsummary: Tell us what you need.\nsections:\n - contact-form:\n heading: Ask for a quote\n form: quote\n email: [email protected]\n phone: (217) 555-0142\n address: |\n 12 Main Street\n Springfield\n note: We answer within **one** working day.\n---\n"},
@@ -305,6 +314,11 @@ func TestBundledPacksBuildAndPass(t *testing.T) {
os.MkdirAll(filepath.Join(dir, "static", "media"), 0o755)
os.WriteFile(filepath.Join(dir, "static", "media", "a.png"), picture, 0o644)
os.WriteFile(filepath.Join(dir, "static", "media", "b.png"), picture, 0o644)
if c.pack == "shop" {
f, _ := os.OpenFile(filepath.Join(dir, "site.yaml"), os.O_APPEND|os.O_WRONLY, 0)
f.WriteString("\ncart: true\n")
f.Close()
}
if c.pack == "breadcrumbs" {
for _, l := range []string{"page.html", "article.html", "list.html"} {
lp := filepath.Join(dir, "layouts", l)
+33
View File
@@ -62,6 +62,9 @@ type Config struct {
// Fediverse is the author's handle (@name@instance), which Mastodon
// credits in link previews: <meta name="fediverse:creator">.
Fediverse string `yaml:"fediverse"`
// Cart turns on the shop's cart (cart: true, or cart: { page: /basket/ }):
// HotDog's cart script, kept in the visitor's browser, for the shop pack.
Cart *CartConfig `yaml:"cart"`
// Cards draws a social card for every page without its own image
// (`cards: true`, or a map to choose the font, colors and logo).
Cards *CardsConfig `yaml:"cards"`
@@ -236,6 +239,9 @@ func LoadConfig(dir string) (*Config, error) {
return nil, fmt.Errorf("site.yaml: url %q has a path; a site lives at the root of its host", c.URL)
}
c.URL = strings.TrimRight(c.URL, "/")
if c.Cart.On() && c.Cart.Page != "" && (!strings.HasPrefix(c.Cart.Page, "/") || strings.HasPrefix(c.Cart.Page, "//")) {
return nil, fmt.Errorf("site.yaml: cart page %q is an address on the site, starting with /", c.Cart.Page)
}
if err := c.Analytics.Validate(); err != nil {
return nil, fmt.Errorf("site.yaml: analytics: %w", err)
}
@@ -451,3 +457,30 @@ type PackRef struct {
Seeded []string `yaml:"-" json:"-"` // forms copied in, now the site's own
Kept []string `yaml:"-" json:"-"` // forms the site already had, left as they were
}
// CartConfig turns the cart on and says where its page is.
type CartConfig struct {
Enabled bool `yaml:"enabled"`
Page string `yaml:"page"` // the cart page's address; /cart/ unless set
}
// UnmarshalYAML takes `cart: true` as well as the map form.
func (c *CartConfig) UnmarshalYAML(n *yaml.Node) error {
if n.Kind == yaml.ScalarNode {
return n.Decode(&c.Enabled)
}
type plain CartConfig
c.Enabled = true
return n.Decode((*plain)(c))
}
// On reports whether the cart is on.
func (c *CartConfig) On() bool { return c != nil && c.Enabled }
// PagePath is the cart page's address.
func (c *CartConfig) PagePath() string {
if c == nil || c.Page == "" {
return "/cart/"
}
return c.Page
}
+56 -4
View File
@@ -14,6 +14,8 @@ import (
"sort"
"strconv"
"strings"
_ "golang.org/x/image/webp" // and of transparent WebP pictures
)
// Pictures in static/media/ are published as the editor writes them: a main
@@ -76,6 +78,12 @@ func LoadMedia(staticDir string) map[string]*MediaPicture {
})
out := map[string]*MediaPicture{}
for stem, f := range byStem {
webpOnly := false
if f.main == "" && f.mainWebP {
// A transparent WebP is kept as WebP, with no JPEG or PNG beside
// it: its sizes are the plain ones.
f.main, f.mainWebP, webpOnly = stem+".webp", false, true
}
if f.main == "" {
continue
}
@@ -93,6 +101,9 @@ func LoadMedia(staticDir string) map[string]*MediaPicture {
for _, sz := range f.sizes {
// Only sizes of this main file's kind, or its WebP copies.
if sz.Width < cfg.Width && (sz.WebP || path.Ext(sz.URL) == mainExt) {
if webpOnly {
sz.WebP = false
}
pic.Sizes = append(pic.Sizes, sz)
}
}
@@ -110,13 +121,51 @@ const defaultImageSizes = "(min-width: 50rem) 50rem, 100vw"
var imgTagRe = regexp.MustCompile(`<img src="(/media/[^"]+)"([^>]*?)\s*/?>`)
// Picture is a picture in media/ for a template: the <img> with its width,
// height and every size it was published at, or a plain <img> for any other
// address. sizes says how wide it's shown ("" for the site's default); attrs
// are more attributes, already escaped.
func (m *Markdown) Picture(src, alt, sizes, attrs string) string {
tag := fmt.Sprintf(`<img src="%s" alt="%s"%s>`, html.EscapeString(src), html.EscapeString(alt), attrs)
if strings.HasPrefix(src, "/media/") {
return string(m.picture([]byte(tag), sizes))
}
return tag
}
// SizeURL is the smallest published size of a picture in media/ at least w
// pixels wide (a WebP where there is one), or src itself.
func (m *Markdown) SizeURL(src string, w int) string {
pic := m.media[src]
if pic == nil {
return src
}
best, bestW := src, 0
for _, sz := range pic.Sizes {
if sz.Width < w && sz.Width != pic.Width {
continue
}
if bestW == 0 || sz.Width < bestW || (sz.Width == bestW && (sz.WebP || strings.HasSuffix(sz.URL, ".webp"))) {
best, bestW = sz.URL, sz.Width
}
}
return best
}
// pictures turns <img> tags pointing at media/ into responsive pictures.
func (m *Markdown) pictures(out []byte) []byte {
if len(m.media) == 0 {
return out
}
return imgTagRe.ReplaceAllFunc(out, func(tag []byte) []byte {
return imgTagRe.ReplaceAllFunc(out, func(tag []byte) []byte { return m.picture(tag, "") })
}
func (m *Markdown) picture(tag []byte, sizes string) []byte {
{
sub := imgTagRe.FindSubmatch(tag)
if sub == nil {
return tag
}
src := html.UnescapeString(string(sub[1]))
pic := m.media[src]
if pic == nil {
@@ -132,13 +181,16 @@ func (m *Markdown) pictures(out []byte) []byte {
plain = append(plain, entry)
}
}
sizes := html.EscapeString(m.imageSizes)
if sizes == "" {
sizes = m.imageSizes
}
sizes = html.EscapeString(sizes)
var b strings.Builder
img := fmt.Sprintf(`<img src="%s"%s width="%d" height="%d"`, html.EscapeString(src), rest, pic.Width, pic.Height)
if len(plain) > 1 {
img += fmt.Sprintf(` srcset="%s" sizes="%s"`, strings.Join(plain, ", "), sizes)
}
if !strings.Contains(rest, "loading=") {
if !strings.Contains(rest, "loading=") && !strings.Contains(rest, "fetchpriority=") {
img += ` loading="lazy" decoding="async"`
}
img += ">"
@@ -147,5 +199,5 @@ func (m *Markdown) pictures(out []byte) []byte {
}
fmt.Fprintf(&b, `<picture><source type="image/webp" srcset="%s" sizes="%s">%s</picture>`, strings.Join(webp, ", "), sizes, img)
return []byte(b.String())
})
}
}
+39
View File
@@ -11,6 +11,7 @@ import (
"testing"
"git.coffeylabs.org/coffey-labs/hotdog-cms/internal/media"
"git.coffeylabs.org/coffey-labs/hotdog-cms/internal/media/webpenc"
)
// mediaSite writes a site whose static/media/ holds a picture as the editor
@@ -68,3 +69,41 @@ func TestMediaPictures(t *testing.T) {
}
}
}
// A transparent WebP is published as WebP only; its sizes go in the <img>'s
// own srcset. Templates get the same through Picture.
func TestWebPOnlyPicture(t *testing.T) {
dir := mediaSite(t)
cut := image.NewRGBA(image.Rect(0, 0, 1200, 1000))
cut.Set(600, 500, color.RGBA{200, 10, 10, 255})
var b bytes.Buffer
if err := webpenc.Encode(&b, cut, webpenc.Options{Lossless: true}); err != nil {
t.Fatal(err)
}
pic, err := media.Process(b.Bytes(), "cut.webp", "shop", func(string) bool { return false })
if err != nil {
t.Fatal(err)
}
for _, f := range pic.Files {
p := filepath.Join(dir, "static", filepath.FromSlash(f.Path))
os.MkdirAll(filepath.Dir(p), 0o755)
os.WriteFile(p, f.Data, 0o644)
}
s, err := Load(dir, Options{})
if err != nil {
t.Fatal(err)
}
got := s.Markdown.Picture("/media/shop/cut.webp", `A "cut" out`, "50vw", ` class="shop-photo" loading="lazy"`)
want := `<img src="/media/shop/cut.webp" alt="A &#34;cut&#34; out" class="shop-photo" loading="lazy" width="1200" height="1000" srcset="/media/shop/cut-480w.webp 480w, /media/shop/cut-960w.webp 960w, /media/shop/cut.webp 1200w" sizes="50vw">`
if got != want {
t.Fatalf("got %s\nwant %s", got, want)
}
// A JPEG offers its WebP copies in a <picture>; the site's default sizes
// stand in when none are given; a picture outside media/ is left plain.
if got := s.Markdown.Picture("/media/2026/10/dock.jpg", "Dock", "", ""); !strings.HasPrefix(got, `<picture><source type="image/webp"`) || !strings.Contains(got, `sizes="(min-width: 50rem) 50rem, 100vw"`) {
t.Fatalf("jpeg: %s", got)
}
if got := s.Markdown.Picture("/img/x.jpg", "X", "", ""); got != `<img src="/img/x.jpg" alt="X">` {
t.Fatalf("outside media: %s", got)
}
}
+14
View File
@@ -13,3 +13,17 @@ a shop with a handful of things to sell. 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.
Sizes and colors are variants, each with its own price and checkout. A
provider whose checkout reads the choice from its address, as Fourthwall's
does, gets a size picker that goes straight to checkout, still without a
script. `hotdog-cms import fourthwall` writes the whole catalog from a
Fourthwall shop (docs/importing.md).
When the checkout takes several things at once, the shop can have a cart:
`cart: true` in site.yaml, `{{ cart }}` in the theme's head, `{{ cartLink }}`
in its header, and a page with `layout: cart`. Product pages then have Add
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.
+16
View File
@@ -15,3 +15,19 @@
.product-actions { display: flex; flex-wrap: wrap; gap: 10px; }
.product-secure { margin: 12px 0 0; color: var(--muted); font-size: .88rem; }
.product-sold-out { display: inline-block; padding: 8px 14px; border-radius: var(--radius); background: var(--accent-soft); font-weight: 650; }
.product-from { font-size: .95rem; font-weight: 600; color: var(--muted); }
.product-form { display: grid; gap: 16px; }
.variants { border: 0; padding: 0; margin: 0; }
.variants legend { font-weight: 650; margin-bottom: 8px; }
.variant-list { display: flex; flex-wrap: wrap; gap: 8px; }
.variant { position: relative; }
.variant input { position: absolute; opacity: 0; inset: 0; margin: 0; cursor: pointer; }
.variant span { display: inline-flex; align-items: baseline; gap: 6px; min-width: 3rem; justify-content: center; padding: 9px 14px; border: 1px solid var(--line, currentColor); border-radius: var(--radius); }
.variant small { color: var(--muted); font-size: .8rem; }
.variant input:checked + span { border-color: var(--accent); box-shadow: inset 0 0 0 1px var(--accent); background: var(--accent-soft); }
.variant input:focus-visible + span { outline: 2px solid var(--accent); outline-offset: 2px; }
.variant-sold span, .btn.variant-sold { opacity: .5; text-decoration: line-through; }
.variant-only { margin: 0; color: var(--muted); }
.product-buy-button { justify-self: start; }
.product-buttons { display: flex; flex-wrap: wrap; gap: 10px; }
.product-buttons [hidden] { display: none; }
+16
View File
@@ -0,0 +1,16 @@
{{ define "main" }}
<link rel="stylesheet" href="{{ asset "packs/shop/shop.css" }}">
{{ $c := default "products" .Params.collection }}{{ $shop := "" }}{{ with index .Site.Lists $c }}{{ $shop = .Path }}{{ end }}
<section class="wrap page cart-page">
<h1>{{ .Title }}</h1>
{{ with .Content }}<div class="prose">{{ . }}</div>{{ end }}
<div class="cart-view" data-cart-view{{ with $shop }} data-shop="{{ . }}"{{ end }}>
{{ if cartOn }}<p class="cart-empty">The cart needs JavaScript. Without it, choose Buy now on a product to check out with just that one.</p>
{{ else }}<p>The cart is off: turn it on with <code>cart: true</code> in site.yaml.</p>{{ end }}
</div>
<section class="cart-suggest" data-cart-suggest data-count="{{ default 4 .Params.suggest }}" hidden>
<h2>{{ default "You might also like" .Params.suggest_heading }}</h2>
<ul class="shop-grid">{{ range limit 48 (collection $c) }}{{ template "product-card" . }}{{ end }}</ul>
</section>
</section>
{{ end }}
+33 -3
View File
@@ -1,18 +1,48 @@
{{ define "main" }}
<link rel="stylesheet" href="{{ asset "packs/shop/shop.css" }}">
{{ $soldOut := eq (printf "%v" .Params.sold_out) "true" }}{{ $cur := .Params.currency }}
{{ $soldOut := eq (printf "%v" .Params.sold_out) "true" }}{{ $cur := .Params.currency }}{{ $base := .Params.price }}
<article class="wrap page product">
{{ with index .Site.Lists .Collection }}<p class="eyebrow"><a href="{{ .Path }}">{{ .Title }}</a></p>{{ end }}
<div class="product-main">
<div class="product-photos">
{{ range $i, $p := .Params.photos }}<img class="{{ if eq $i 0 }}product-photo-main{{ else }}product-photo{{ end }}" src="{{ $p.image }}" alt="{{ $p.alt }}"{{ if gt $i 0 }} loading="lazy"{{ end }}>{{ end }}
{{ range $i, $p := .Params.photos }}{{ if eq $i 0 }}{{ picture $p.image $p.alt "(min-width: 760px) 55vw, 100vw" "class=product-photo-main fetchpriority=high" }}{{ else }}{{ picture $p.image $p.alt "(min-width: 760px) 14vw, 25vw" "class=product-photo loading=lazy" }}{{ end }}{{ end }}
</div>
<div class="product-buy">
<h1>{{ .Title }}</h1>
{{ with .Params.price }}<p class="product-price">{{ money . $cur }}</p>{{ end }}
{{ with .Params.price }}<p class="product-price">{{ if eq (printf "%v" $.Params.price_from) "true" }}<span class="product-from">From</span> {{ end }}{{ money . $cur }}</p>{{ end }}
{{ with .Summary }}<p class="product-summary">{{ . }}</p>{{ end }}
{{ if $soldOut }}
<p class="product-sold-out">Sold out</p>
{{ else if .Params.variants }}
{{ $vs := .Params.variants }}
{{ with .Params.checkout }}
{{/* One form: choose a size or color, and Buy sends it to the checkout. */}}
{{ $field := default "products" .field }}{{ $item := default "{id}" .item }}
<form class="product-form" method="get" action="{{ .action }}" data-cart data-field="{{ $field }}" data-item="{{ $item }}" data-join="{{ default "," .join }}" data-title="{{ $.Title }}" data-href="{{ $.Href }}" data-currency="{{ $cur }}"{{ with $.Params.photos }}{{ with index . 0 }} data-image="{{ pictureAt .image 160 }}"{{ end }}{{ end }}>
{{ range $k, $v := .fields }}<input type="hidden" name="{{ $k }}" value="{{ $v }}">{{ end }}
{{ if eq (len $vs) 1 }}{{ with index $vs 0 }}
<input type="hidden" name="{{ $field }}" value="{{ if .value }}{{ .value }}{{ else }}{{ $item | replace "{id}" (printf "%v" .id) | replace "{qty}" "1" }}{{ end }}" data-cart-variant data-id="{{ default .value .id }}" data-name="{{ with .group }}{{ . }} · {{ end }}{{ .name }}" data-price="{{ .price }}">
{{ with .name }}{{ if ne . "One size" }}<p class="variant-only">{{ with (index $vs 0).group }}{{ . }} · {{ end }}{{ . }}</p>{{ end }}{{ end }}
{{ end }}{{ else }}
{{ $g := "-" }}
{{ range $i, $v := $vs }}{{ $vg := default "" $v.group }}{{ if ne $vg $g }}{{ if ne $i 0 }}</div></fieldset>{{ end }}{{ $g = $vg }}
<fieldset class="variants"><legend>{{ if $vg }}{{ $vg }}{{ else }}{{ default "Choose one" $.Params.choose }}{{ end }}</legend><div class="variant-list">{{ end }}
{{ $sold := eq (printf "%v" $v.sold_out) "true" }}
<label class="variant{{ if $sold }} variant-sold{{ end }}"><input type="radio" name="{{ $field }}" value="{{ if $v.value }}{{ $v.value }}{{ else }}{{ $item | replace "{id}" (printf "%v" $v.id) | replace "{qty}" "1" }}{{ end }}" required{{ if $sold }} disabled{{ end }} data-cart-variant data-id="{{ default $v.value $v.id }}" data-name="{{ with $v.group }}{{ . }} · {{ end }}{{ $v.name }}" data-price="{{ $v.price }}"><span>{{ $v.name }}{{ if $sold }} <small>sold out</small>{{ else if and $v.price (ne (printf "%v" $v.price) (printf "%v" $base)) }} <small>{{ money $v.price $cur }}</small>{{ end }}</span></label>
{{ end }}</div></fieldset>
{{ end }}
<div class="product-buttons">
{{ if cartOn }}<button class="btn primary" type="button" data-cart-add hidden>Add to cart</button>{{ end }}
<button class="btn{{ if not cartOn }} primary{{ end }} product-buy-button" type="submit">{{ default (cond cartOn "Buy now" "Buy") $.Params.button }}</button>
</div>
</form>
{{ else }}
{{/* No checkout form: each size or color is a Buy link of its own. */}}
<div class="product-actions">
{{ range $vs }}{{ if eq (printf "%v" .sold_out) "true" }}<span class="btn variant-sold">{{ with .group }}{{ . }} · {{ end }}{{ .name }} · sold out</span>{{ else }}<a class="btn" href="{{ .buy }}" rel="noopener">{{ with .group }}{{ . }} · {{ end }}{{ .name }}{{ with .price }} · {{ money . $cur }}{{ end }}</a>{{ end }}{{ end }}
</div>
{{ end }}
<p class="product-secure">You'll pay on our payment provider's secure page.</p>
{{ else }}
<div class="product-actions">
{{ with .Params.buy }}<a class="btn primary" href="{{ . }}" rel="noopener">{{ default "Buy" $.Params.button }}</a>{{ end }}
+34 -1
View File
@@ -1,5 +1,5 @@
name: shop
version: 1.0.0
version: 1.2.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.
license: MIT
@@ -28,6 +28,39 @@ notes: |
---
What's in the box, how it ships, and anything else, in Markdown.
Sizes and colors: list them as variants, each with its own buy link and
price; a group (a color) gathers them under a heading, and sold_out: true
crosses one out. price_from: true shows "From" before the price.
variants:
- { group: Black, name: S, price: 24, buy: "https://buy.stripe.com/s" }
- { group: Black, name: XL, price: 26, buy: "https://buy.stripe.com/xl" }
A provider whose checkout takes the choice in its address (Fourthwall's
does) gets a proper picker instead: give the product a checkout form and
each variant the value it sends, and Buy goes to the checkout with the
size or color chosen, still without a script.
checkout: { action: "https://shop.example.com/cart/checkout", field: products, fields: { currency: USD } }
hotdog-cms import fourthwall writes all of this from a Fourthwall shop.
A cart: when the checkout takes several things at once (item: "{id}:{qty}"
and join: "," in the checkout form, as Fourthwall's does), turn on
cart: true in site.yaml, put {{ cart }} in your theme's head and
{{ cartLink }} in its header, and add content/cart.md:
---
title: Your cart
layout: cart
suggest: 4
---
Products then have Add to cart beside Buy now. The cart is kept in the
visitor's browser, and its page suggests other products, those sharing a
tag with what's in the cart first. Without JavaScript, Buy now still
works.
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.
+3 -3
View File
@@ -1,8 +1,8 @@
{{/* One product in a grid: its first photo, name and price. */}}
<li class="shop-card">
<li class="shop-card" data-product="{{ .Href }}"{{ with .Params.tags }} data-tags="{{ range $i, $t := . }}{{ if $i }},{{ end }}{{ $t }}{{ end }}"{{ end }}>
<a href="{{ .Href }}">
{{ with .Params.photos }}{{ with index . 0 }}<img class="shop-photo" src="{{ .image }}" alt="{{ .alt }}" loading="lazy">{{ end }}{{ else }}<span class="shop-photo shop-none" aria-hidden="true"></span>{{ end }}
{{ with .Params.photos }}{{ with index . 0 }}{{ picture .image .alt "(min-width: 760px) 25vw, 50vw" "class=shop-photo loading=lazy" }}{{ end }}{{ else }}<span class="shop-photo shop-none" aria-hidden="true"></span>{{ end }}
<strong>{{ .Title }}</strong>
</a>
<span class="shop-price">{{ with .Params.price }}{{ money . $.Params.currency }}{{ end }}{{ if eq (printf "%v" .Params.sold_out) "true" }} · <em>Sold out</em>{{ end }}</span>
<span class="shop-price">{{ with .Params.price }}{{ if eq (printf "%v" $.Params.price_from) "true" }}From {{ end }}{{ money . $.Params.currency }}{{ end }}{{ if eq (printf "%v" .Params.sold_out) "true" }} · <em>Sold out</em>{{ end }}</span>
</li>
+1
View File
@@ -21,6 +21,7 @@
<link rel="stylesheet" href="{{ asset "styles.css" }}">
{{ with lookCSS }}<link rel="stylesheet" href="{{ . }}">{{ end }}
{{ consent }}
{{ cart }}
<script src="{{ asset "site.js" }}"></script>
{{ range $name, $c := .Site.Config.Collections }}{{ if $c.Feed }}{{ $path := $c.FeedPath }}{{ if not $path }}{{ $path = printf "/%s/feed.xml" $name }}{{ end }}
<link rel="alternate" type="application/atom+xml" title="{{ $.Site.Config.Name }}: {{ $name }}" href="{{ $path }}">{{ end }}{{ end }}
+1
View File
@@ -12,6 +12,7 @@
{{ range menu "main" }}<li><a href="{{ .URL }}"{{ if eq $.Path .URL }} aria-current="page"{{ else if $.InSection .URL }} class="active"{{ end }}>{{ .Name }}</a></li>{{ end }}
</ul>
</nav>
{{ cartLink }}
<div class="theme" role="group" aria-label="Color theme">
<button type="button" data-theme-set="light">Light</button>
<button type="button" data-theme-set="auto">Auto</button>