motorino/internal/build/blog.go
tgiachi 6987541f88 fix(news): group the archive by the month as written, drop the empty lists
- groupArchive compared each post with the last group only, so two posts near midnight
  at the end of a month, written with different offsets, listed the same month twice and
  the build failed with "both published as". Posts are grouped by their own year and
  month, newest first.
- {{news_archive}} is empty when there are no posts, so the index says there is no news
  once, and the heading of an empty {{news_archive}} or {{categories_list}} goes with it.
- tests for exactly ten posts, eleven posts, a single post, a title with quotes, an
  ampersand, a tag and non Latin letters, and a neighbour written in another language

Refs #9
2026-11-16 12:48:17 +01:00

239 lines
7.7 KiB
Go

// SPDX-License-Identifier: GPL-3.0-or-later
package build
import (
"fmt"
"sort"
"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
}
// 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 "<p>\n" + ctx["news_empty"] + "\n</p>", 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.newsPanel(p, lang, true)
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(`<a href="%s" rel="prev">%s</a>`, pagePath(b.newsPath, n-1), render.Escape(newer)))
}
parts = append(parts, render.Escape(page))
if n < total {
parts = append(parts, fmt.Sprintf(`<a href="%s" rel="next">%s</a>`, pagePath(b.newsPath, n+1), render.Escape(older)))
}
return fmt.Sprintf("<nav aria-label=\"%s\">\n<p>\n%s\n</p>\n</nav>", render.EscapeAttr(label), strings.Join(parts, "\n&middot;\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 by year and by month, as written in their dates.
// The years and the months are newest first, and the posts of a group keep the
// order they were given. A post is put in its group by its own year and month,
// not by the group before it: two posts near midnight at the end of a month,
// written with different offsets, can be in the order of their instants and in
// the opposite order of their months.
func groupArchive(posts []content.Post) []archiveYear {
type key struct{ year, month int }
years := map[int]*archiveYear{}
months := map[key]*archiveMonth{}
for _, p := range posts {
y, m := p.Date.Year(), int(p.Date.Month())
year := years[y]
if year == nil {
year = &archiveYear{year: y}
years[y] = year
}
year.posts = append(year.posts, p)
month := months[key{y, m}]
if month == nil {
month = &archiveMonth{year: y, month: m}
months[key{y, m}] = month
}
month.posts = append(month.posts, p)
}
var out []archiveYear
for _, year := range years {
for k, month := range months {
if k.year == year.year {
year.months = append(year.months, *month)
}
}
sort.Slice(year.months, func(i, j int) bool { return year.months[i].month > year.months[j].month })
out = append(out, *year)
}
sort.Slice(out, func(i, j int) bool { return out[i].year > out[j].year })
return out
}
// 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(`<li><a href="%s">%s</a> (%d)</li>`, b.monthPath(m.year, m.month), render.Escape(monthYear(m.year, m.month, b.langs[lang])), len(m.posts))
}
return "<ul>\n" + strings.Join(items, "\n") + "\n</ul>"
}
// newsArchive returns the nested list of the years and the months that have
// posts, or nothing when there are none: the blog list says there is no news. 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 "", nil
}
items := make([]string, len(years))
for i, y := range years {
items[i] = fmt.Sprintf("<li><a href=\"%s\">%d</a> (%d)\n%s</li>", b.yearPath(y.year), y.year, len(y.posts), b.monthList(y, lang))
}
return "<ul>\n" + strings.Join(items, "\n") + "\n</ul>", 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
panels, err := b.newsPanels(posts, lang)
if err != nil {
return err
}
ctx["archive_posts"] = panels
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("<p><a href=\"%s\">%s %s</a></p>", 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
}