From 4a501d77b3c2ecd737db39620e226efcba78d873 Mon Sep 17 00:00:00 2001 From: tgiachi Date: Mon, 16 Nov 2026 12:08:07 +0100 Subject: [PATCH] feat(news): blog list with pages, and an archive by year and month - {{news_blog}} lists the posts as entries (title, long date, categories, description, a read more link) 10 to a page; the other pages are written under the index, at page/2/, page/3/ and so on, with a pager. - Archive pages for every year and month that has posts, at /news/2026/ and /news/2026/11/, when templates/archive.html exists, and a {{news_archive}} block. Refs #9 --- internal/build/blog.go | 243 ++++++++++++++++++++++++++++++++++++ internal/build/blog_test.go | 122 ++++++++++++++++++ internal/build/build.go | 3 + internal/build/context.go | 2 +- internal/build/pages.go | 45 ++++++- 5 files changed, 411 insertions(+), 4 deletions(-) create mode 100644 internal/build/blog.go diff --git a/internal/build/blog.go b/internal/build/blog.go new file mode 100644 index 0000000..b0e47cf --- /dev/null +++ b/internal/build/blog.go @@ -0,0 +1,243 @@ +// SPDX-License-Identifier: GPL-3.0-or-later + +package build + +import ( + "fmt" + "strconv" + "strings" + + "git.kmalloc.org/squid/motorino/internal/content" + "git.kmalloc.org/squid/motorino/internal/render" +) + +// newsPerPage is how many posts one page of the blog list has. +const newsPerPage = 10 + +// pageCount returns how many pages n posts make: at least one. +func pageCount(n int) int { + if n <= newsPerPage { + return 1 + } + return (n + newsPerPage - 1) / newsPerPage +} + +// pagePath returns the address of page n of an index: the index itself for the +// first page, then base + "page/2/", "page/3/" and so on. base ends with "/". +func pagePath(base string, n int) string { + if n <= 1 { + return base + } + return base + "page/" + strconv.Itoa(n) + "/" +} + +// pageLabel is "Page 2 of 3" in the language lang, from the string pager_page. +func (b *builder) pageLabel(lang string, n, total int) (string, error) { + text := b.langs[lang].Strings["pager_page"] + if text == "" { + return "", fmt.Errorf("lang/%s.json: the language has no pager_page string, which the pages of the blog list need", lang) + } + return strings.NewReplacer("{n}", strconv.Itoa(n), "{total}", strconv.Itoa(total)).Replace(text), nil +} + +// blogEntry returns one entry of the blog list: the title as a link, the date +// and the categories, the description as a preview and a link to read more. +// lang is the language of the page; a post in another language is marked. +func (b *builder) blogEntry(p content.Post, lang string) (string, error) { + l := b.langs[lang] + more := l.Strings["read_more"] + if more == "" { + return "", fmt.Errorf("lang/%s.json: the language has no read_more string, which the blog list needs", lang) + } + mark := "" + if p.Language != "" && p.Language != lang { + mark = fmt.Sprintf(` hreflang="%s" lang="%s"`, p.Language, p.Language) + } + meta := fmt.Sprintf(``, p.Date.Format(dateOnly), render.Escape(longDate(p.Date, l))) + if links := categoryLinks(p); links != "" { + meta += " · " + links + } + var out strings.Builder + out.WriteString("
\n") + fmt.Fprintf(&out, "

%s

\n", p.Path, mark, render.Escape(p.Title)) + fmt.Fprintf(&out, "

%s

\n", meta) + if p.Description != "" { + fmt.Fprintf(&out, "

%s

\n", render.Escape(p.Description)) + } + fmt.Fprintf(&out, "

%s

\n", p.Path, render.EscapeAttr(more), render.EscapeAttr(p.Title), mark, render.Escape(more)) + out.WriteString("
") + return out.String(), nil +} + +// newsBlog returns the page n of the blog list of the language lang, with the +// pager when the list has more than one page. A site without posts gets the +// news_empty text. +func (b *builder) newsBlog(lang string, n int, ctx map[string]string) (string, error) { + if len(b.posts) == 0 { + return "

\n" + ctx["news_empty"] + "\n

", nil + } + total := pageCount(len(b.posts)) + if n < 1 || n > total { + n = 1 + } + end := n * newsPerPage + if end > len(b.posts) { + end = len(b.posts) + } + entries := make([]string, 0, newsPerPage) + for _, p := range b.posts[(n-1)*newsPerPage : end] { + entry, err := b.blogEntry(p, lang) + if err != nil { + return "", err + } + entries = append(entries, entry) + } + html := strings.Join(entries, "\n") + if total == 1 { + return html, nil + } + pager, err := b.pager(lang, n, total) + if err != nil { + return "", err + } + return html + "\n" + pager, nil +} + +// pager returns the navigation between the pages of the blog list. +func (b *builder) pager(lang string, n, total int) (string, error) { + l := b.langs[lang] + label, newer, older := l.Strings["pager_label"], l.Strings["pager_newer"], l.Strings["pager_older"] + if label == "" || newer == "" || older == "" { + return "", fmt.Errorf("lang/%s.json: the language lacks pager_label, pager_newer or pager_older, which the pages of the blog list need", lang) + } + page, err := b.pageLabel(lang, n, total) + if err != nil { + return "", err + } + var parts []string + if n > 1 { + parts = append(parts, fmt.Sprintf(``, pagePath(b.newsPath, n-1), render.Escape(newer))) + } + parts = append(parts, render.Escape(page)) + if n < total { + parts = append(parts, fmt.Sprintf(``, pagePath(b.newsPath, n+1), render.Escape(older))) + } + return fmt.Sprintf("", render.EscapeAttr(label), strings.Join(parts, "\n·\n")), nil +} + +// archiveMonth is the posts of one month; archiveYear the posts of one year. +type ( + archiveMonth struct { + year, month int + posts []content.Post + } + archiveYear struct { + year int + posts []content.Post + months []archiveMonth + } +) + +// groupArchive groups posts, newest first, by year and by month, as written in +// their dates. The years and the months are newest first too. +func groupArchive(posts []content.Post) []archiveYear { + var years []archiveYear + for _, p := range posts { + y, m := p.Date.Year(), int(p.Date.Month()) + if len(years) == 0 || years[len(years)-1].year != y { + years = append(years, archiveYear{year: y}) + } + year := &years[len(years)-1] + year.posts = append(year.posts, p) + if len(year.months) == 0 || year.months[len(year.months)-1].month != m { + year.months = append(year.months, archiveMonth{year: y, month: m}) + } + month := &year.months[len(year.months)-1] + month.posts = append(month.posts, p) + } + return years +} + +// yearPath and monthPath are the addresses of an archive year and month. +func (b *builder) yearPath(year int) string { return fmt.Sprintf("%s%04d/", b.newsPath, year) } +func (b *builder) monthPath(year, month int) string { + return fmt.Sprintf("%s%04d/%02d/", b.newsPath, year, month) +} + +// hasArchive reports whether the site has the template of an archive page. +func (b *builder) hasArchive() bool { + _, ok := b.templates["archive"] + return ok +} + +// monthList returns the list of the months of a year, each with its posts. +func (b *builder) monthList(y archiveYear, lang string) string { + items := make([]string, len(y.months)) + for i, m := range y.months { + items[i] = fmt.Sprintf(`
  • %s (%d)
  • `, b.monthPath(m.year, m.month), render.Escape(monthYear(m.year, m.month, b.langs[lang])), len(m.posts)) + } + return "" +} + +// newsArchive returns the nested list of the years and the months that have +// posts, or the news_empty text when there are none. It needs the archive pages. +func (b *builder) newsArchive(lang string, ctx map[string]string) (string, error) { + if _, err := b.template("archive"); err != nil { + return "", fmt.Errorf("the {{news_archive}} block needs the archive pages: %w", err) + } + years := groupArchive(b.posts) + if len(years) == 0 { + return "

    \n" + ctx["news_empty"] + "\n

    ", nil + } + items := make([]string, len(years)) + for i, y := range years { + items[i] = fmt.Sprintf("
  • %d (%d)\n%s
  • ", b.yearPath(y.year), y.year, len(y.posts), b.monthList(y, lang)) + } + return "", nil +} + +// renderArchives writes the page of every year and every month that has posts, +// when the site has templates/archive.html. +func (b *builder) renderArchives() error { + if !b.hasArchive() { + return nil + } + tmpl, err := b.template("archive") + if err != nil { + return err + } + lang := b.newsLang + l := b.langs[lang] + page := func(path, name, nav string, posts []content.Post, source string) error { + d := document{ + lang: lang, nav: "news", lead: "news", path: path, title: name, prefixed: true, + description: l.Strings["archive_h"] + ": " + name, source: source, + } + ctx := b.documentContext(d) + ctx["archive_name"] = render.Escape(name) + ctx["archive_nav"] = nav + ctx["archive_posts"] = newsList(posts, lang) + body, err := render.Substitute("templates/archive.html", tmpl, ctx) + if err != nil { + return err + } + return b.frame(d, ctx, body) + } + for _, y := range groupArchive(b.posts) { + year := strconv.Itoa(y.year) + if err := page(b.yearPath(y.year), year, b.monthList(y, lang), y.posts, "the archive of "+year); err != nil { + return err + } + up := "" + if text := l.Strings["archive_up"]; text != "" { + up = fmt.Sprintf("

    %s %s

    ", b.yearPath(y.year), render.Escape(text), year) + } + for _, m := range y.months { + name := monthYear(m.year, m.month, l) + if err := page(b.monthPath(m.year, m.month), name, up, m.posts, "the archive of "+name); err != nil { + return err + } + } + } + return nil +} diff --git a/internal/build/blog_test.go b/internal/build/blog_test.go index 6cedf98..83b112e 100644 --- a/internal/build/blog_test.go +++ b/internal/build/blog_test.go @@ -299,3 +299,125 @@ func TestPostOpenGraphArticle(t *testing.T) { } } } + +// blogIndex is a news index that uses the blog list and the archive. +const blogIndex = "Title: News\nID: news\nDescription: About News.\n-\n# News\n\n{{news_blog}}\n\n## Archive\n\n{{news_archive}}\n" + +// archiveTemplate is the page of a year or a month of the archive. +const archiveTemplate = "

    {{archive_h}}: {{archive_name}}

    \n\n{{archive_nav}}\n\n{{archive_posts}}\n" + +// manyPosts adds n posts, dated one per day from 2026-10-01, to the files. +func manyPosts(files map[string]string, n int) map[string]string { + for i := 1; i <= n; i++ { + day := "2026-10-" + string(rune('0'+i/10)) + string(rune('0'+i%10)) + name := "p" + string(rune('0'+i/10)) + string(rune('0'+i%10)) + files["news/"+name+".md"] = "Title: Post " + name[1:] + "\nDate: " + day + "T12:00:00+0100\nCategories: Many\n-\nText of " + name + ".\n" + } + return files +} + +// TestNewsBlogEntries checks one entry of the blog list and the absence of a pager for a short list. +func TestNewsBlogEntries(t *testing.T) { + out, err := buildWith(t, blogSite(map[string]string{"content/en/news/index.md": blogIndex, "templates/archive.html": archiveTemplate}), nil) + if err != nil { + t.Fatalf("Build() error = %v", err) + } + index := readOut(t, out, "news/index.html") + mustContain(t, "news index", index, + "
    \n

    A shop

    ", + `

    · FLUG

    `, + "

    About the shop.

    ", + `

    Read more

    `, + ) + if got := strings.Count(index, "
    "); got != 3 { + t.Errorf("the index has %d entries, want 3", got) + } + if strings.Contains(index, "News pages") { + t.Error("a list that fits one page has a pager") + } +} + +// TestNewsBlogPagination checks the pages of a long list. +func TestNewsBlogPagination(t *testing.T) { + files := blogSite(map[string]string{"content/en/news/index.md": blogIndex, "templates/archive.html": archiveTemplate}) + out, err := buildWith(t, manyPosts(files, 22), nil) + if err != nil { + t.Fatalf("Build() error = %v", err) + } + first := readOut(t, out, "news/index.html") + mustContain(t, "page 1", first, `