diff --git a/cmd/hotdog-cms/main.go b/cmd/hotdog-cms/main.go index fad8288..b81c1b0 100644 --- a/cmd/hotdog-cms/main.go +++ b/cmd/hotdog-cms/main.go @@ -646,7 +646,7 @@ func importFourthwall(args []string) error { 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") + photos := fl.Int("photos", 6, "at most this many photos a product, or a color when it has several; 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") diff --git a/internal/build/build.go b/internal/build/build.go index 068806f..845cd8e 100644 --- a/internal/build/build.go +++ b/internal/build/build.go @@ -260,6 +260,11 @@ func prepareWith(siteDir string, s *site.Site, out string, formOverrides map[str return nil, err } } + if hasVariantGroups(s) { + if err := assets.add(out, "hotdog-variants.js", variantScript); err != nil { + return nil, err + } + } if s.Config.Analytics != nil { if err := assets.add(out, "hotdog-consent.js", consentScript); err != nil { return nil, err @@ -297,6 +302,7 @@ func prepareWith(siteDir string, s *site.Site, out string, formOverrides map[str 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["variantPicker"] = func() template.HTML { return variantPicker(assets) } 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) } diff --git a/internal/build/cart.go b/internal/build/cart.go index 2ff7235..c11667a 100644 --- a/internal/build/cart.go +++ b/internal/build/cart.go @@ -16,6 +16,8 @@ var ( cartScript []byte //go:embed static/hotdog-cart.css cartStyle []byte + //go:embed static/hotdog-variants.js + variantScript []byte ) // cartTags is the cart's stylesheet and script, for a theme's head: {{ cart }}. @@ -37,3 +39,27 @@ func cartLink(cfg *site.Config) template.HTML { } return template.HTML(`Cart 0`) } + +// variantPicker is the script that turns a product's sizes grouped by color +// into a color drop-down: {{ variantPicker }} in the product layout. The +// build only carries it when some page has grouped variants. +func variantPicker(a *Assets) template.HTML { + js, err := a.URL("hotdog-variants.js") + if err != nil { + return "" + } + return template.HTML(``) +} + +// hasVariantGroups says whether any page lists variants in groups (group:). +func hasVariantGroups(s *site.Site) bool { + for _, p := range s.Pages { + vs, _ := p.Params["variants"].([]any) + for _, v := range vs { + if m, ok := v.(map[string]any); ok && m["group"] != nil && m["group"] != "" { + return true + } + } + } + return false +} diff --git a/internal/build/static/hotdog-variants.js b/internal/build/static/hotdog-variants.js new file mode 100644 index 0000000..2add139 --- /dev/null +++ b/internal/build/static/hotdog-variants.js @@ -0,0 +1,57 @@ +// A product with its sizes grouped by color ({{ variantPicker }}): a +// drop-down picks the color, and only that color's sizes and photos show. +// Without this script the page lists every color's sizes and photos, and +// works the same. +(() => { + const select = document.querySelector("[data-group-select]"); + const form = select && select.closest("form"); + if (!form) return; + const sets = [...form.querySelectorAll("fieldset.variants[data-group]")]; + const slides = [...document.querySelectorAll(".photo-slide")]; + const picks = [...document.querySelectorAll(".photo-pick")]; + + const show = (group) => { + // The size chosen in the color being left, to choose again in the new one. + const was = form.querySelector("input[data-option]:checked"); + const size = was ? was.dataset.option : ""; + for (const set of sets) { + const on = set.dataset.group === group; + // A hidden color's sizes are disabled, so they're never sent or checked. + set.disabled = !on; + if (!on) { + set.hidden = true; + continue; + } + const sizes = [...set.querySelectorAll("input[data-option]")]; + const again = sizes.find((i) => i.dataset.option === size && !i.disabled); + if (again) again.checked = true; + else if (was) was.checked = false; + // A color with one choice needs no row of its own: the drop-down is it. + if (sizes.length === 1 && !sizes[0].disabled) sizes[0].checked = true; + set.hidden = sizes.length === 1; + } + // Photos of this color, and those of no one color. + let first = null; + picks.forEach((pick, i) => { + const g = pick.dataset.group; + const on = !g || g === group; + pick.hidden = !on; + if (slides[i]) slides[i].hidden = !on; + if (on && !first && g) first = pick; + }); + first = first || picks.find((p) => !p.hidden); + if (first) first.querySelector("input").checked = true; + }; + + for (const set of sets) { + const legend = set.querySelector("legend"); + if (legend) legend.textContent = select.dataset.choose; + } + select.closest("[data-group-pick]").hidden = false; + // Coming back to the page, the browser may have kept a size: keep its color. + const kept = form.querySelector("input[data-option]:checked"); + const keptSet = kept && kept.closest("fieldset[data-group]"); + if (keptSet) select.value = keptSet.dataset.group; + select.addEventListener("change", () => show(select.value)); + show(select.value); +})(); diff --git a/internal/importer/fourthwall.go b/internal/importer/fourthwall.go index 9278030..8463305 100644 --- a/internal/importer/fourthwall.go +++ b/internal/importer/fourthwall.go @@ -41,7 +41,7 @@ type FourthwallOptions struct { 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 + Photos int // at most this many photos a product (a color, when it has several); 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 @@ -112,6 +112,63 @@ type fwVariant struct { Type string `json:"type"` InStock *int `json:"inStock"` } `json:"stock"` + Images []fwImage `json:"images"` +} + +// fwPhoto is a product photo and the color it shows, "" when it isn't one +// color's alone. +type fwPhoto struct { + fwImage + group string +} + +// fwPhotos lists a product's photos. With more than one color, and photos +// that say which color they show, each color's come together (at most max +// of them, 0 for all) and carry its name; otherwise they're the product's +// own list, cut to max. +func fwPhotos(p fwProduct, colors []string, max int) []fwPhoto { + var out []fwPhoto + if len(colors) > 1 { + owner := map[string]string{} + for _, v := range p.Variants { + c := v.Attributes.Color + if c == nil || c.Name == "" { + continue + } + for _, im := range v.Images { + if o, ok := owner[im.ID]; ok && o != c.Name { + owner[im.ID] = "" // two colors share it + } else if !ok { + owner[im.ID] = c.Name + } + } + } + if len(owner) > 0 { + count := map[string]int{} + for _, c := range colors { + for _, im := range p.Images { + if owner[im.ID] == c && (max <= 0 || count[c] < max) { + out = append(out, fwPhoto{im, c}) + count[c]++ + } + } + } + for _, im := range p.Images { + if g, ok := owner[im.ID]; (!ok || g == "") && (max <= 0 || count[""] < max) { + out = append(out, fwPhoto{im, ""}) + count[""]++ + } + } + return out + } + } + for _, im := range p.Images { + if max > 0 && len(out) == max { + break + } + out = append(out, fwPhoto{im, ""}) + } + return out } func (v fwVariant) soldOut() bool { @@ -317,21 +374,45 @@ func SyncFourthwall(opt FourthwallOptions) (*FourthwallReport, error) { } } - // Photos. + // The colors, in the shop's order, and whether there are sizes. + var colors []string + sized := false + for _, v := range p.Variants { + if c := v.Attributes.Color; c != nil && c.Name != "" && !slices.Contains(colors, c.Name) { + colors = append(colors, c.Name) + } + if v.Attributes.Size != nil && v.Attributes.Size.Name != "" { + sized = true + } + } + + // Photos: with several colors, each one's own (at most -photos of + // each), marked with the color so the page can show the chosen one's. mediaDir := path.Join("shop", slug) - images := p.Images - if opt.Photos > 0 && len(images) > opt.Photos { - images = images[:opt.Photos] + images := fwPhotos(p, colors, opt.Photos) + of := map[string]int{} + for _, im := range images { + of[im.group]++ } var photos []map[string]any using := map[string]bool{} + seen := map[string]int{} for n, im := range images { + seen[im.group]++ alt := p.Name - if len(images) > 1 { - alt = fmt.Sprintf("%s, photo %d of %d", p.Name, n+1, len(images)) + if im.group != "" { + alt += ", " + im.group + } + if of[im.group] > 1 { + alt = fmt.Sprintf("%s, photo %d of %d", alt, seen[im.group], of[im.group]) + } + photo := map[string]any{"alt": alt, "source": im.ID} + if im.group != "" { + photo["group"] = im.group } if img, ok := havePhoto[im.ID]; ok { - photos = append(photos, map[string]any{"image": img, "alt": alt, "source": im.ID}) + photo["image"] = img + photos = append(photos, photo) using[img] = true continue } @@ -351,7 +432,8 @@ func SyncFourthwall(opt FourthwallOptions) (*FourthwallReport, error) { } } rep.Pictures++ - photos = append(photos, map[string]any{"image": img.URL, "alt": alt, "source": im.ID}) + photo["image"] = img.URL + photos = append(photos, photo) using[img.URL] = true } // Photos the product no longer has go, with their smaller sizes. @@ -377,15 +459,6 @@ func SyncFourthwall(opt FourthwallOptions) (*FourthwallReport, error) { // 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 diff --git a/internal/importer/fourthwall_test.go b/internal/importer/fourthwall_test.go index a9ae946..6a6abba 100644 --- a/internal/importer/fourthwall_test.go +++ b/internal/importer/fourthwall_test.go @@ -161,3 +161,41 @@ func TestFourthwallSync(t *testing.T) { t.Fatalf("bad token: %v", err) } } + +func TestFourthwallPhotosByColor(t *testing.T) { + im := func(ids ...string) []fwImage { + var out []fwImage + for _, id := range ids { + out = append(out, fwImage{ID: id}) + } + return out + } + variant := func(color string, ids ...string) fwVariant { + var v fwVariant + v.Attributes.Color = &struct { + Name string `json:"name"` + Swatch string `json:"swatch"` + }{Name: color} + v.Images = im(ids...) + return v + } + p := fwProduct{Images: im("a", "b", "c", "d", "e"), Variants: []fwVariant{ + variant("Red", "a", "b", "e"), variant("Red", "a", "b", "e"), variant("Blue", "c", "d", "e"), + }} + got := func(ps []fwPhoto) string { + var s []string + for _, p := range ps { + s = append(s, p.ID+"="+p.group) + } + return strings.Join(s, " ") + } + if g := got(fwPhotos(p, []string{"Red", "Blue"}, 0)); g != "a=Red b=Red c=Blue d=Blue e=" { + t.Errorf("every photo, by color, a shared one last: %s", g) + } + if g := got(fwPhotos(p, []string{"Red", "Blue"}, 1)); g != "a=Red c=Blue e=" { + t.Errorf("one of each color: %s", g) + } + if g := got(fwPhotos(p, []string{"Red"}, 2)); g != "a= b=" { + t.Errorf("one color, the product's own list: %s", g) + } +} diff --git a/internal/packs/bundled_test.go b/internal/packs/bundled_test.go index 0ade0cb..8395912 100644 --- a/internal/packs/bundled_test.go +++ b/internal/packs/bundled_test.go @@ -159,6 +159,7 @@ 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/hoodie.md", "---\ntitle: Hoodie\nprice: 40\ncurrency: USD\nweight: 4\nphotos:\n - { image: /media/a.png, alt: Hoodie in red, group: Red }\n - { image: /media/b.png, alt: Hoodie in blue, group: Blue }\nchoose: Size\nvariants:\n - { group: Red, name: S, price: 40, id: r1 }\n - { group: Red, name: M, price: 40, id: r2 }\n - { group: Blue, name: S, price: 40, id: b1 }\ncheckout: { action: \"https://shop.example/cart/checkout\", field: products, item: \"{id}:{qty}\" }\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\ntags: [linux]\nvariants:\n - { group: Black, name: One size, price: 20, value: \"c1:1\" }\ncheckout: { action: \"https://shop.example/cart/checkout\" }\n---\n"}, {"content/cart.md", "---\ntitle: Your cart\nlayout: cart\nsuggest: 3\n---\n"}, @@ -168,18 +169,19 @@ func TestBundledPacksBuildAndPass(t *testing.T) { {"content/picks.md", "---\ntitle: Picks\nsummary: Picks.\nsections:\n - products: { heading: Penguin picks, tag: Linux, more: All Linux things }\n---\n"}, {"content/products/print.md", "---\ntitle: Print\nsummary: A print.\nprice: 30\ncurrency: USD\nweight: 5\nvariants:\n - { group: Matte, name: A4, price: 30, buy: \"https://buy.stripe.com/a4\" }\n - { group: Matte, name: A3, price: 40, buy: \"https://buy.stripe.com/a3\", sold_out: true }\n---\n"}, }, map[string][]string{ - "products/tee/index.html": {`