diff --git a/docs/seasons.md b/docs/seasons.md new file mode 100644 index 0000000..9cc5a0f --- /dev/null +++ b/docs/seasons.md @@ -0,0 +1,51 @@ +# Seasons + +`seasons:` in site.yaml dresses a site for holidays through the year. Each +visitor's browser works out the day from its own date every time a page +loads, so nothing is scheduled and nothing is rebuilt when a holiday starts +or ends. The user guide is on hotdogcms.org (Writing › Holidays); this page +is how it's put together. + +```yaml +seasons: true # or: +seasons: + anchor: header.top # the strip hangs under this; default the window's top + logo: .brand-logo # the day's prop is laid over this + art: # or swap a picture for your own drawings + - { image: logo.svg, art: /img/season/logo-{prop}.svg } + skip: footer # pictures in here keep their usual look + only: [advent, pride] # or except: [halloween] + greetings: false # no greeting on the strip +``` + +`{{ seasons }}` in the head writes the tags (the starter has it). With +seasons off it writes nothing and no file is added. + +## The pieces + +- `internal/seasons/src/core.js`: the dates. Holidays (`HOLIDAYS`, one strip + and prop each; the first that matches dresses the page, all are greeted) + and December's observances (`SCENES`, drawn side by side at the end of the + strip). Lunar dates come from the browser's `Intl` calendars (Chinese, + Hebrew, Islamic, Persian); where a browser lacks one, those holidays don't + show. Easter is computed (Western and Orthodox), Holi and Diwali from the + moon's phases, Dongzhi from the solstice. Advent alone runs on UTC. +- `src/render.js`: the strips and scenes, drawn as SVG in the page. +- `src/run.js`: places the strip, swaps pictures, lays props, handles + `?season=`. +- `src/season.css`: the strip's look. The build links it, and adds where each + kind of prop sits on a logo (`.season-prop-head`, `-eyes`, `-ear`, `-pin`, + `-side`), which a site can restyle. +- `props/*.svg`: each prop on its own, fingerprinted into + `hotdog-seasons/..svg`. + +The build checks `only:` and `except:` against the holiday names, and that a +site's own `art:` has a drawing for every prop (`static/` plus the address, +with `{prop}` filled in). + +## Previewing + +`?season=` shows one holiday, `?season=YYYY-MM-DD` everything that date +shows, `?season=off` nothing and `?season=auto` today again; each lasts for +the browser tab's session. `TZ=UTC node internal/seasons/src/dates-test.js +2026 2027` lists every holiday's days for those years. diff --git a/internal/build/build.go b/internal/build/build.go index 306744d..a748ebd 100644 --- a/internal/build/build.go +++ b/internal/build/build.go @@ -275,6 +275,9 @@ func prepareWith(siteDir string, s *site.Site, out string, formOverrides map[str return nil, err } } + if err := addSeasons(siteDir, s.Config, assets, out); err != nil { + return nil, err + } if s.Config.Analytics != nil { if err := assets.add(out, "hotdog-consent.js", consentScript); err != nil { return nil, err @@ -310,6 +313,7 @@ func prepareWith(siteDir string, s *site.Site, out string, formOverrides map[str } fm["consent"] = func() template.HTML { return consentTags(s.Config, assets) } fm["cart"] = func() template.HTML { return cartTags(s.Config, assets) } + fm["seasons"] = func() (template.HTML, error) { return seasonsTags(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) } diff --git a/internal/build/build_test.go b/internal/build/build_test.go index 80e3512..7f7c4e2 100644 --- a/internal/build/build_test.go +++ b/internal/build/build_test.go @@ -522,3 +522,48 @@ func TestMarkdownOutputs(t *testing.T) { t.Error("a generated tag page got a Markdown copy") } } + +func TestSeasons(t *testing.T) { + dir := writeStarter(t) + res, err := Run(Options{SiteDir: dir}) + if err != nil { + t.Fatal(err) + } + home, _ := os.ReadFile(filepath.Join(res.Out, "index.html")) + if strings.Contains(string(home), "hotdog-seasons") { + t.Error("seasons are on without seasons: in site.yaml") + } + + cfg, _ := os.ReadFile(filepath.Join(dir, "site.yaml")) + os.WriteFile(filepath.Join(dir, "site.yaml"), append(cfg, []byte("seasons:\n logo: .brand-logo\n except: [halloween]\n")...), 0o644) + if res, err = Run(Options{SiteDir: dir}); err != nil { + t.Fatal(err) + } + home, _ = os.ReadFile(filepath.Join(res.Out, "index.html")) + m := regexp.MustCompile(``).FindStringSubmatch(string(home)) + if m == nil || !regexp.MustCompile(``).MatchString(string(home)) { + t.Fatalf("home page has no seasons tags:\n%s", home) + } + if _, err := os.Stat(filepath.Join(res.Out, m[1])); err != nil { + t.Error("script not written") + } + props, _ := filepath.Glob(filepath.Join(res.Out, "hotdog-seasons", "santa.*.svg")) + if len(props) != 1 || !strings.Contains(m[2], "/hotdog-seasons/santa.") { + t.Errorf("santa prop: %v, %s", props, m[2]) + } + + // A holiday that doesn't exist, and art with drawings missing, stop the + // build and say why. + os.WriteFile(filepath.Join(dir, "site.yaml"), append(cfg, []byte("seasons:\n only: [arbor]\n")...), 0o644) + if _, err := Run(Options{SiteDir: dir}); err == nil || !strings.Contains(err.Error(), `no holiday called "arbor"`) { + t.Errorf("unknown holiday: %v", err) + } + os.WriteFile(filepath.Join(dir, "site.yaml"), append(cfg, []byte("seasons:\n art:\n - image: logo.svg\n art: /img/logo-{prop}.svg\n")...), 0o644) + if _, err := Run(Options{SiteDir: dir}); err == nil || !strings.Contains(err.Error(), "missing 17 of 17 drawings") { + t.Errorf("missing art: %v", err) + } + os.WriteFile(filepath.Join(dir, "site.yaml"), append(cfg, []byte("seasons:\n art:\n - image: logo.svg\n art: img/logo.svg\n")...), 0o644) + if _, err := Run(Options{SiteDir: dir}); err == nil || !strings.Contains(err.Error(), "with {prop}") { + t.Errorf("bad art address: %v", err) + } +} diff --git a/internal/build/seasons.go b/internal/build/seasons.go new file mode 100644 index 0000000..5050d83 --- /dev/null +++ b/internal/build/seasons.go @@ -0,0 +1,78 @@ +package build + +import ( + "fmt" + "html/template" + "os" + "path/filepath" + "strings" + + "git.coffeylabs.org/coffey-labs/hotdog-cms/internal/seasons" + "git.coffeylabs.org/coffey-labs/hotdog-cms/internal/site" +) + +// addSeasons checks site.yaml's seasons: block and writes the script, its +// stylesheet and the props, when seasons are on. +func addSeasons(siteDir string, cfg *site.Config, a *Assets, out string) error { + c := cfg.Seasons + if !c.On() { + return nil + } + for _, list := range [][]string{c.Only, c.Except} { + for _, id := range list { + if !seasons.Known(id) { + return fmt.Errorf("site.yaml: seasons: no holiday called %q (they are: %s)", id, strings.Join(seasons.IDs, ", ")) + } + } + } + // A site's own art needs a drawing for every prop it might show. + for _, art := range c.Art { + var missing []string + for _, p := range seasons.PropNames() { + rel := strings.ReplaceAll(strings.TrimPrefix(art.Art, "/"), "{prop}", p) + if _, err := os.Stat(filepath.Join(siteDir, "static", filepath.FromSlash(rel))); err != nil { + missing = append(missing, "static/"+rel) + } + } + if len(missing) > 0 { + return fmt.Errorf("site.yaml: seasons: art for %q is missing %d of %d drawings: %s", art.Image, len(missing), len(seasons.Props), strings.Join(missing, ", ")) + } + } + if out != "" { + if err := os.MkdirAll(filepath.Join(out, "hotdog-seasons"), 0o755); err != nil { + return err + } + } + if err := a.add(out, "hotdog-seasons.js", seasons.Script); err != nil { + return err + } + if err := a.add(out, "hotdog-seasons.css", seasons.Style); err != nil { + return err + } + for name, svg := range seasons.Props { + if err := a.add(out, "hotdog-seasons/"+name+".svg", svg); err != nil { + return err + } + } + return nil +} + +// seasonsTags is {{ seasons }}: the stylesheet and script tags, or nothing +// when seasons are off. +func seasonsTags(cfg *site.Config, a *Assets) (template.HTML, error) { + c := cfg.Seasons + if !c.On() { + return "", nil + } + o := seasons.Options{Anchor: c.Anchor, Logo: c.Logo, Skip: c.Skip, Only: c.Only, Except: c.Except, + Greetings: c.Greetings == nil || *c.Greetings, PropURLs: map[string]string{}} + o.ScriptURL, _ = a.URL("hotdog-seasons.js") + o.CSSURL, _ = a.URL("hotdog-seasons.css") + for name := range seasons.Props { + o.PropURLs[name], _ = a.URL("hotdog-seasons/" + name + ".svg") + } + for _, art := range c.Art { + o.Art = append(o.Art, [2]string{art.Image, strings.ReplaceAll(art.Art, "{prop}", "{p}")}) + } + return seasons.Tags(o) +} diff --git a/internal/seasons/props/birthday.svg b/internal/seasons/props/birthday.svg new file mode 100644 index 0000000..4314ab8 --- /dev/null +++ b/internal/seasons/props/birthday.svg @@ -0,0 +1,6 @@ + + + + + + diff --git a/internal/seasons/props/bunny.svg b/internal/seasons/props/bunny.svg new file mode 100644 index 0000000..6e2ef5d --- /dev/null +++ b/internal/seasons/props/bunny.svg @@ -0,0 +1,4 @@ + + + + diff --git a/internal/seasons/props/crown.svg b/internal/seasons/props/crown.svg new file mode 100644 index 0000000..55ea09d --- /dev/null +++ b/internal/seasons/props/crown.svg @@ -0,0 +1,4 @@ + + + + diff --git a/internal/seasons/props/flowers.svg b/internal/seasons/props/flowers.svg new file mode 100644 index 0000000..1831002 --- /dev/null +++ b/internal/seasons/props/flowers.svg @@ -0,0 +1 @@ + diff --git a/internal/seasons/props/goggles.svg b/internal/seasons/props/goggles.svg new file mode 100644 index 0000000..140979d --- /dev/null +++ b/internal/seasons/props/goggles.svg @@ -0,0 +1,6 @@ + + + + + + diff --git a/internal/seasons/props/holi.svg b/internal/seasons/props/holi.svg new file mode 100644 index 0000000..c1e052e --- /dev/null +++ b/internal/seasons/props/holi.svg @@ -0,0 +1 @@ + diff --git a/internal/seasons/props/lantern.svg b/internal/seasons/props/lantern.svg new file mode 100644 index 0000000..1cfcf75 --- /dev/null +++ b/internal/seasons/props/lantern.svg @@ -0,0 +1,8 @@ + + + + + + + + diff --git a/internal/seasons/props/lucia.svg b/internal/seasons/props/lucia.svg new file mode 100644 index 0000000..f49c798 --- /dev/null +++ b/internal/seasons/props/lucia.svg @@ -0,0 +1,6 @@ + + + + + + diff --git a/internal/seasons/props/marigold.svg b/internal/seasons/props/marigold.svg new file mode 100644 index 0000000..7dcac00 --- /dev/null +++ b/internal/seasons/props/marigold.svg @@ -0,0 +1,4 @@ + + + + diff --git a/internal/seasons/props/mask.svg b/internal/seasons/props/mask.svg new file mode 100644 index 0000000..3ed6fa0 --- /dev/null +++ b/internal/seasons/props/mask.svg @@ -0,0 +1,5 @@ + + + + diff --git a/internal/seasons/props/mlantern.svg b/internal/seasons/props/mlantern.svg new file mode 100644 index 0000000..1c0ab34 --- /dev/null +++ b/internal/seasons/props/mlantern.svg @@ -0,0 +1,9 @@ + + + + + + + + + diff --git a/internal/seasons/props/poppy.svg b/internal/seasons/props/poppy.svg new file mode 100644 index 0000000..56c3856 --- /dev/null +++ b/internal/seasons/props/poppy.svg @@ -0,0 +1,5 @@ + + + + + diff --git a/internal/seasons/props/pride.svg b/internal/seasons/props/pride.svg new file mode 100644 index 0000000..fb8119a --- /dev/null +++ b/internal/seasons/props/pride.svg @@ -0,0 +1 @@ + diff --git a/internal/seasons/props/santa.svg b/internal/seasons/props/santa.svg new file mode 100644 index 0000000..9465e99 --- /dev/null +++ b/internal/seasons/props/santa.svg @@ -0,0 +1,7 @@ + + + + + + + diff --git a/internal/seasons/props/shades.svg b/internal/seasons/props/shades.svg new file mode 100644 index 0000000..688014c --- /dev/null +++ b/internal/seasons/props/shades.svg @@ -0,0 +1,5 @@ + + + + + diff --git a/internal/seasons/props/tophat.svg b/internal/seasons/props/tophat.svg new file mode 100644 index 0000000..fc8d69c --- /dev/null +++ b/internal/seasons/props/tophat.svg @@ -0,0 +1,5 @@ + + + + + diff --git a/internal/seasons/props/witch.svg b/internal/seasons/props/witch.svg new file mode 100644 index 0000000..4e7da8c --- /dev/null +++ b/internal/seasons/props/witch.svg @@ -0,0 +1,4 @@ + + + + diff --git a/internal/seasons/seasons.go b/internal/seasons/seasons.go new file mode 100644 index 0000000..8822bd8 --- /dev/null +++ b/internal/seasons/seasons.go @@ -0,0 +1,166 @@ +// Package seasons dresses a site for holidays through the year: a strip along +// the top of the page, a prop on the logo and a greeting, worked out in each +// visitor's browser from their own date every time a page loads. Nothing is +// scheduled and nothing needs a rebuild when a holiday starts or ends. +// +// The script is src/core.js (the dates), src/render.js (the drawings) and +// src/run.js (the page), wrapped here; src/season.css is its stylesheet and +// props/ holds a drawing of each prop on its own. List a year's dates with +// `TZ=UTC node internal/seasons/src/dates-test.js 2026 2027`. +package seasons + +import ( + "embed" + "encoding/json" + "fmt" + "html/template" + "regexp" + "sort" + "strings" +) + +//go:embed src/core.js src/render.js src/run.js src/season.css +var src embed.FS + +//go:embed props/*.svg +var propFS embed.FS + +// Script is the browser script, Style its stylesheet, and Props each prop's +// drawing (an SVG laid over the site's logo), by prop name. +var ( + Script []byte + Style []byte + Props = map[string][]byte{} +) + +// IDs are the holidays and December observances a site can name in only: +// and except:, in the order the script checks them. +var IDs []string + +const header = `/* HotDog CMS seasons: holidays through the year, worked out on the + * visitor's own clock every time a page loads (internal/seasons). + * Preview: ?season=, ?season=YYYY-MM-DD, ?season=off, + * ?season=auto; each lasts for the browser tab's session. */ +` + +// boot reads the script tag's data-seasons (see Tags) and starts. +const boot = ` + var me = document.currentScript, c = {}; + try { c = JSON.parse(me.getAttribute('data-seasons')) || {}; } catch (e) {} + var props = c.props || {}; + run({ swap: c.art || [], anchor: c.anchor, skip: c.skip, overlay: c.logo, + overlaySrc: function (p) { return props[p]; }, only: c.only, except: c.except, + greet: c.greetings !== false, css: false }); +` + +// overlayCSS places each kind of prop on the logo it's laid over, in +// proportion to the logo (drawn for a square one). A site's own stylesheet can +// move them: .season-prop-head, -eyes, -ear, -pin, -side. +const overlayCSS = `.season-prop{z-index:1;height:auto} +.season-prop-head{left:0;top:-31%;width:110%;transform:rotate(-12deg)} +.season-prop-eyes{left:5%;top:16.5%;width:95%} +.season-prop-ear{left:62%;top:-13%;width:47.5%} +.season-prop-pin{left:60%;top:62%;width:47.5%} +.season-prop-side{left:-55%;top:-7.5%;width:47.5%} +` + +var idRe = regexp.MustCompile(`\bid: '([a-z-]+)'`) + +func init() { + read := func(name string) string { + b, err := src.ReadFile(name) + if err != nil { + panic(err) + } + return string(b) + } + core, render, run := read("src/core.js"), read("src/render.js"), read("src/run.js") + Style = []byte(read("src/season.css") + overlayCSS) + // The stylesheet is linked, not injected (css: false), so the script's + // own copy stays empty. + render = strings.Replace(render, " // CSS (the strip's look) comes from season.css, put in by the build.\n", " var CSS = '';\n", 1) + Script = []byte(header + "(function () {\n" + core + render + run + boot + "})();\n") + + seen := map[string]bool{} + for _, m := range idRe.FindAllStringSubmatch(core, -1) { + if !seen[m[1]] { + seen[m[1]] = true + IDs = append(IDs, m[1]) + } + } + entries, err := propFS.ReadDir("props") + if err != nil { + panic(err) + } + for _, e := range entries { + b, err := propFS.ReadFile("props/" + e.Name()) + if err != nil { + panic(err) + } + Props[strings.TrimSuffix(e.Name(), ".svg")] = b + } +} + +// PropNames lists the props, sorted: the names a site's own art is drawn for. +func PropNames() []string { + names := make([]string, 0, len(Props)) + for n := range Props { + names = append(names, n) + } + sort.Strings(names) + return names +} + +// Known reports whether id names a holiday or an observance. +func Known(id string) bool { + for _, k := range IDs { + if k == id { + return true + } + } + return false +} + +// Options is what Tags needs from site.yaml's seasons: block, plus the +// addresses of the fingerprinted files. +type Options struct { + Anchor, Logo, Skip string + Art [][2]string // [part of an image's address, address with {p} for the prop] + Only, Except []string + Greetings bool + ScriptURL, CSSURL string + PropURLs map[string]string +} + +// Tags is the stylesheet link and the script tag for a page's head. +func Tags(o Options) (template.HTML, error) { + cfg := map[string]any{"props": o.PropURLs} + if o.Anchor != "" { + cfg["anchor"] = o.Anchor + } + if o.Logo != "" { + cfg["logo"] = o.Logo + } + if o.Skip != "" { + cfg["skip"] = o.Skip + } + if len(o.Art) > 0 { + cfg["art"] = o.Art + } + if len(o.Only) > 0 { + cfg["only"] = o.Only + } + if len(o.Except) > 0 { + cfg["except"] = o.Except + } + if !o.Greetings { + cfg["greetings"] = false + } + j, err := json.Marshal(cfg) + if err != nil { + return "", fmt.Errorf("seasons: %w", err) + } + esc := template.HTMLEscapeString + return template.HTML(`` + + ``), nil +} diff --git a/internal/seasons/seasons_test.go b/internal/seasons/seasons_test.go new file mode 100644 index 0000000..bf66177 --- /dev/null +++ b/internal/seasons/seasons_test.go @@ -0,0 +1,65 @@ +package seasons + +import ( + "regexp" + "strings" + "testing" +) + +func TestScriptAndProps(t *testing.T) { + s := string(Script) + for _, want := range []string{"function pick(", "function run(", "data-seasons", "var CSS = '';"} { + if !strings.Contains(s, want) { + t.Errorf("script lacks %q", want) + } + } + if strings.Contains(s, "comes from season.css") { + t.Error("the stylesheet placeholder was left in") + } + for _, id := range []string{"advent", "lunarnewyear", "diwali", "pride", "hanukkah", "christmas", "kwanzaa"} { + if !Known(id) { + t.Errorf("%s isn't a known holiday", id) + } + } + if Known("arbor") { + t.Error("made-up holiday known") + } + // Every prop a holiday wears has a drawing, and the drawings are plain. + for _, p := range regexpAll(`prop: '([a-z]+)'`, s) { + if Props[p] == nil { + t.Errorf("no drawing for the %s prop", p) + } + } + for name, svg := range Props { + low := strings.ToLower(string(svg)) + if strings.Contains(low, "`, ` {{ range $name, $c := .Site.Config.Collections }}{{ if $c.Feed }}{{ $path := $c.FeedPath }}{{ if not $path }}{{ $path = printf "/%s/feed.xml" $name }}{{ end }} {{ end }}{{ end }}