From 7c26d6de9beeef1b3aefe3bceded66a78868893f Mon Sep 17 00:00:00 2001 From: John Coffey Date: Fri, 16 Oct 2026 15:47:50 -0700 Subject: [PATCH 1/3] Pictures: transparent WebP stays WebP; picture for templates A WebP with transparency (a product photographed on nothing, as print shops supply them) was turned into a lossless PNG, often ten times the size and slow to make. It now stays WebP, lossy with its transparency, at each size; an opaque WebP still becomes JPEG. The media index takes a picture whose only file is a WebP. Templates get what Markdown pictures had: picture "/media/x.webp" "alt" "sizes" "class=x loading=lazy" writes the with its width, height and every published size, and pictureAt "/media/x.webp" 160 is the address of the smallest size at least that wide. --- internal/build/funcs.go | 28 +++++++++++++++++ internal/media/media.go | 18 ++++++++--- internal/media/media_test.go | 55 ++++++++++++++++++++++++++++++++- internal/site/media.go | 60 +++++++++++++++++++++++++++++++++--- internal/site/media_test.go | 39 +++++++++++++++++++++++ 5 files changed, 191 insertions(+), 9 deletions(-) diff --git a/internal/build/funcs.go b/internal/build/funcs.go index cd858f8..1503138 100644 --- a/internal/build/funcs.go +++ b/internal/build/funcs.go @@ -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-]+)$`) diff --git a/internal/media/media.go b/internal/media/media.go index 7146a52..dcb11b0 100644 --- a/internal/media/media.go +++ b/internal/media/media.go @@ -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 { diff --git a/internal/media/media_test.go b/internal/media/media_test.go index 8e68a08..efaa976 100644 --- a/internal/media/media_test.go +++ b/internal/media/media_test.go @@ -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) + } +} diff --git a/internal/site/media.go b/internal/site/media.go index 52109ac..cf9b440 100644 --- a/internal/site/media.go +++ b/internal/site/media.go @@ -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(`]*?)\s*/?>`) +// Picture is a picture in media/ for a template: the with its width, +// height and every size it was published at, or a plain 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(`%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 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(` 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, `%s`, strings.Join(webp, ", "), sizes, img) return []byte(b.String()) - }) + } } diff --git a/internal/site/media_test.go b/internal/site/media_test.go index bde6acb..58e58eb 100644 --- a/internal/site/media_test.go +++ b/internal/site/media_test.go @@ -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 '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 := `A "cut" out` + if got != want { + t.Fatalf("got %s\nwant %s", got, want) + } + // A JPEG offers its WebP copies in a ; 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, `` { + t.Fatalf("outside media: %s", got) + } +} -- 2.54.0 From 0a2e0f33f6edba51a651d3ed75813325e5519fea Mon Sep 17 00:00:00 2001 From: John Coffey Date: Fri, 16 Oct 2026 15:47:57 -0700 Subject: [PATCH 2/3] Shop: Fourthwall import, sizes and colors, and a cart hotdog-cms import fourthwall brings a Fourthwall shop's public products in as shop pack pages, with the storefront token from HOTDOG_FOURTHWALL_TOKEN: description and details as Markdown, photos brought into the site, sizes and colors as variants, collections as terms of a taxonomy. It's run again whenever the shop changes: products are matched by id, unchanged pages and photos are left alone, front matter the site added is kept, and products that left the shop are listed (deleted with -prune). The shop pack (1.2.0) takes variants: each with a price and a buy link, or, when the product has a checkout form (Fourthwall's reads the choice from its address), a size picker whose Buy now goes straight to the checkout. Both work without a script. Prices that vary show "From", and search engines get an AggregateOffer. cart: true in site.yaml turns on a cart: HotDog's cart script, kept in the visitor's browser and sent nowhere until checkout, which opens the shop's checkout with every item (id:quantity, joined). Product pages get Add to cart beside Buy now; the cart page (layout: cart) lists, changes and removes items and suggests other products, those sharing a tag first. Themes put {{ cart }} in the head and {{ cartLink }} in the header, as the starter now does, and the privacy notice says where the cart is kept. --- cmd/hotdog-cms/main.go | 42 +- docs/importing.md | 44 +- internal/build/build.go | 11 + internal/build/cart.go | 39 ++ internal/build/consent.go | 3 + internal/build/schema.go | 11 + internal/build/static/hotdog-cart.css | 27 ++ internal/build/static/hotdog-cart.js | 159 +++++++ internal/importer/fourthwall.go | 588 ++++++++++++++++++++++++++ internal/importer/fourthwall_test.go | 163 +++++++ internal/importer/write.go | 6 +- internal/packs/bundled_test.go | 20 +- internal/site/config.go | 33 ++ packs/shop/README.md | 14 + packs/shop/assets/shop.css | 16 + packs/shop/layouts/cart.html | 16 + packs/shop/layouts/product.html | 36 +- packs/shop/pack.yaml | 35 +- packs/shop/partials/product-card.html | 6 +- starter/site/partials/head.html | 1 + starter/site/partials/nav.html | 1 + 21 files changed, 1258 insertions(+), 13 deletions(-) create mode 100644 internal/build/cart.go create mode 100644 internal/build/static/hotdog-cart.css create mode 100644 internal/build/static/hotdog-cart.js create mode 100644 internal/importer/fourthwall.go create mode 100644 internal/importer/fourthwall_test.go create mode 100644 packs/shop/layouts/cart.html diff --git a/cmd/hotdog-cms/main.go b/cmd/hotdog-cms/main.go index dc8c889..fad8288 100644 --- a/cmd/hotdog-cms/main.go +++ b/cmd/hotdog-cms/main.go @@ -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 ... 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 -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 [flags] (hotdog-cms import -h for each)\n" + importer.Ownership) + return errors.New("usage: hotdog-cms import [flags] (hotdog-cms import -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] | remove | list | check \n(each takes -site DIR before its argument; default .)") if len(args) == 0 { diff --git a/docs/importing.md b/docs/importing.md index 8bb9a09..229000d 100644 --- a/docs/importing.md +++ b/docs/importing.md @@ -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 ``, a `0`) +} diff --git a/internal/build/consent.go b/internal/build/consent.go index 48a11c9..f8e78a5 100644 --- a/internal/build/consent.go +++ b/internal/build/consent.go @@ -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."}) } diff --git a/internal/build/schema.go b/internal/build/schema.go index 1a37731..8e168a3 100644 --- a/internal/build/schema.go +++ b/internal/build/schema.go @@ -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 diff --git a/internal/build/static/hotdog-cart.css b/internal/build/static/hotdog-cart.css new file mode 100644 index 0000000..b784332 --- /dev/null +++ b/internal/build/static/hotdog-cart.css @@ -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; } +} diff --git a/internal/build/static/hotdog-cart.js b/internal/build/static/hotdog-cart.js new file mode 100644 index 0000000..d377363 --- /dev/null +++ b/internal/build/static/hotdog-cart.js @@ -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()) +})() diff --git a/internal/importer/fourthwall.go b/internal/importer/fourthwall.go new file mode 100644 index 0000000..9278030 --- /dev/null +++ b/internal/importer/fourthwall.go @@ -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=: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)]*>(.*?)

`) + 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 +} diff --git a/internal/importer/fourthwall_test.go b/internal/importer/fourthwall_test.go new file mode 100644 index 0000000..4d390d4 --- /dev/null +++ b/internal/importer/fourthwall_test.go @@ -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": "Tux T-Shirt", "slug": "tux-t-shirt", "description": "

Tux on a white tee & more.

  • Cotton
", + "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": "
  • Relaxed fit
"}}}, + {"id": "p2", "name": "Cap", "slug": "cap", "description": "

A cap.

", + "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/tux-t-shirt.md")) + for _, want := range []string{ + "title: Tux T-Shirt\nsummary: Tux on a white tee & more.\nprice: 24.4\nprice_from: true\ncurrency: USD\nweight: 1\n", + "image: /media/shop/tux-t-shirt/1.webp", "alt: Tux 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", + "Tux 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/tux-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/tux-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) + } +} diff --git a/internal/importer/write.go b/internal/importer/write.go index 3f21f32..57a012a 100644 --- a/internal/importer/write.go +++ b/internal/importer/write.go @@ -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 diff --git a/internal/packs/bundled_test.go b/internal/packs/bundled_test.go index adc531b..6ba227d 100644 --- a/internal/packs/bundled_test.go +++ b/internal/packs/bundled_test.go @@ -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 · Sold out"}, - "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": {`
`, ``, "Size", `name="products" value="v1:1" required data-cart-variant data-id="v1" data-name="S" data-price="24">`, "2XL $26.00", `value="v3:1" required disabled data-cart-variant`, "3XL sold out", `data-cart-add hidden>Add to cart`, `product-buy-button" type="submit">Buy now`, ` {{ range $name, $c := .Site.Config.Collections }}{{ if $c.Feed }}{{ $path := $c.FeedPath }}{{ if not $path }}{{ $path = printf "/%s/feed.xml" $name }}{{ end }} {{ end }}{{ end }} diff --git a/starter/site/partials/nav.html b/starter/site/partials/nav.html index 505705e..1d20adf 100644 --- a/starter/site/partials/nav.html +++ b/starter/site/partials/nav.html @@ -12,6 +12,7 @@ {{ range menu "main" }}
  • {{ .Name }}
  • {{ end }} + {{ cartLink }}
    -- 2.54.0 From 4935aa0fbc374064cd5bc8c73a26c516294c0091 Mon Sep 17 00:00:00 2001 From: John Coffey Date: Fri, 16 Oct 2026 15:57:16 -0700 Subject: [PATCH 3/3] Fourthwall test: a plain example product --- internal/importer/fourthwall_test.go | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/internal/importer/fourthwall_test.go b/internal/importer/fourthwall_test.go index 4d390d4..a9ae946 100644 --- a/internal/importer/fourthwall_test.go +++ b/internal/importer/fourthwall_test.go @@ -80,7 +80,7 @@ func TestFourthwallSync(t *testing.T) { return map[string]any{"id": id, "url": srv.URL + "/img/" + id + ".webp"} } products = []map[string]any{ - {"id": "p1", "name": "Tux T-Shirt", "slug": "tux-t-shirt", "description": "

    Tux on a white tee & more.

    • Cotton
    ", + {"id": "p1", "name": "Plain T-Shirt", "slug": "plain-t-shirt", "description": "

    A logo on a white tee & more.

    • Cotton
    ", "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": "
    • Relaxed fit
    "}}}, @@ -97,14 +97,14 @@ func TestFourthwallSync(t *testing.T) { 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/tux-t-shirt.md")) + tee := read(t, filepath.Join(dir, "content/products/plain-t-shirt.md")) for _, want := range []string{ - "title: Tux T-Shirt\nsummary: Tux on a white tee & more.\nprice: 24.4\nprice_from: true\ncurrency: USD\nweight: 1\n", - "image: /media/shop/tux-t-shirt/1.webp", "alt: Tux T-Shirt, photo 2 of 2", "source: b", + "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", - "Tux on a *white* tee & more.", "## More details", "- Relaxed fit", + "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) @@ -117,7 +117,7 @@ func TestFourthwallSync(t *testing.T) { 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/tux-t-shirt/2-480w.webp")); err != nil { + if _, err := os.Stat(filepath.Join(dir, "static/media/shop/plain-t-shirt/2-480w.webp")); err != nil { t.Fatal("smaller sizes missing") } @@ -134,7 +134,7 @@ func TestFourthwallSync(t *testing.T) { if _, err = SyncFourthwall(opt); err != nil { t.Fatal(err) } - if _, err := os.Stat(filepath.Join(dir, "static/media/shop/tux-t-shirt/2.webp")); !os.IsNotExist(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") } -- 2.54.0