huge blog refactor

tidying up data structures; improvements to blog admin UI/UX, etc.
This commit is contained in:
ari melody 2025-11-08 12:54:31 +00:00
parent eaa2f6587d
commit 0c2aaa0b38
Signed by: ari
GPG key ID: CF99829C92678188
18 changed files with 432 additions and 239 deletions

View file

@ -23,17 +23,19 @@ func Handler(app *model.AppState) http.Handler {
}
type (
blogPost struct {
*model.BlogPost
Author *model.Account
}
blogPostGroup struct {
blogPostCollection struct {
Year int
Posts []*blogPost
Posts []*model.BlogPost
}
)
func (c *blogPostCollection) Clone() blogPostCollection {
return blogPostCollection{
Year: c.Year,
Posts: slices.Clone(c.Posts),
}
}
func serveBlogIndex(app *model.AppState) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
session := r.Context().Value("session").(*model.Session)
@ -45,44 +47,36 @@ func serveBlogIndex(app *model.AppState) http.Handler {
return
}
collections := []*blogPostGroup{}
collectionPosts := []*blogPost{}
collectionYear := -1
collections := []*blogPostCollection{}
collection := blogPostCollection{
Posts: []*model.BlogPost{},
Year: -1,
}
for i, post := range posts {
author, err := controller.GetAccountByID(app.DB, post.AuthorID)
if err != nil {
fmt.Fprintf(os.Stderr, "WARN: Failed to retrieve author of blog %s: %v\n", post.ID, err)
continue
if i == 0 {
collection.Year = post.PublishDate.Year()
}
if collectionYear == -1 {
collectionYear = post.CreatedAt.Year()
}
authoredPost := blogPost{
BlogPost: post,
Author: author,
}
if post.CreatedAt.Year() != collectionYear || i == len(posts) - 1 {
if i == len(posts) - 1 {
collectionPosts = append([]*blogPost{&authoredPost}, collectionPosts...)
if post.PublishDate.Year() != collection.Year {
clone := collection.Clone()
collections = append(collections, &clone)
collection = blogPostCollection{
Year: post.PublishDate.Year(),
Posts: []*model.BlogPost{},
}
collections = append(collections, &blogPostGroup{
Year: collectionYear,
Posts: slices.Clone(collectionPosts),
})
collectionPosts = []*blogPost{}
collectionYear = post.CreatedAt.Year()
}
collectionPosts = append(collectionPosts, &authoredPost)
collection.Posts = append(collection.Posts, post)
if i == len(posts) - 1 {
collections = append(collections, &collection)
}
}
type blogsData struct {
core.AdminPageData
TotalPosts int
Collections []*blogPostGroup
Collections []*blogPostCollection
}
err = templates.BlogsTemplate.Execute(w, blogsData{
@ -108,7 +102,11 @@ func serveBlogPost(app *model.AppState) http.Handler {
post, err := controller.GetBlogPost(app.DB, blogID)
if err != nil {
fmt.Printf("can't find blog with ID %s\n", blogID)
fmt.Fprintf(os.Stderr, "WARN: Failed to fetch blog %s: %v\n", blogID, err)
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
if post == nil {
http.NotFound(w, r)
return
}