wp-go/internal/theme/wp/components/widget/recentcomments.go
2023-03-28 21:45:20 +08:00

76 lines
2.6 KiB
Go

package widget
import (
"fmt"
"github.com/fthvgb1/wp-go/helper/maps"
"github.com/fthvgb1/wp-go/helper/slice"
str "github.com/fthvgb1/wp-go/helper/strings"
"github.com/fthvgb1/wp-go/internal/cmd/reload"
"github.com/fthvgb1/wp-go/internal/pkg/cache"
"github.com/fthvgb1/wp-go/internal/pkg/constraints/widgets"
"github.com/fthvgb1/wp-go/internal/pkg/models"
"github.com/fthvgb1/wp-go/internal/theme/wp"
"github.com/fthvgb1/wp-go/internal/wpconfig"
"strings"
)
func recentCommentsArgs() map[string]string {
return map[string]string{
"{$before_sidebar}": "",
"{$after_sidebar}": "",
"{$nav}": "",
"{$navCloser}": "",
"{$title}": "",
"{$recent_comments_id}": "recentcomments",
}
}
func recentCommentConf() map[any]any {
return map[any]any{
"number": int64(5),
"title": "近期评论",
}
}
var recentCommentsTemplate = `{$before_widget}
{$nav}
{$title}
<ul id="{$recent_comments_id}">
{$li}
</ul>
{$navCloser}
{$after_widget}
`
func RecentComments(h *wp.Handle, id string) string {
conf := reload.GetAnyValBys("widget-recent-comment-conf", h, func(h *wp.Handle) map[any]any {
commentConf := recentCommentConf()
conf := wpconfig.GetPHPArrayVal("widget_recent-comments", commentConf, int64(2))
conf = maps.FilterZeroMerge(commentConf, conf)
return conf
})
args := reload.GetAnyValBys("widget-recent-comment-args", h, func(h *wp.Handle) map[string]string {
commentsArgs := recentCommentsArgs()
commonArgs := wp.GetComponentsArgs(h, widgets.Widget, map[string]string{})
args := wp.GetComponentsArgs(h, widgets.RecentComments, commentsArgs)
args = maps.FilterZeroMerge(commentsArgs, CommonArgs(), commonArgs, args)
args["{$before_widget}"] = fmt.Sprintf(args["{$before_widget}"], str.Join("recent-comments-", id), str.Join("widget widget_", "recent_comments"))
args["{$title}"] = str.Join(args["{$before_title}"], conf["title"].(string), args["{$after_title}"])
if slice.IsContained(h.CommonThemeMods().ThemeSupport.HTML5, "navigation-widgets") {
args["{$nav}"] = fmt.Sprintf(`<nav aria-label="%s">`, conf["title"])
args["{$navCloser}"] = "</nav>"
}
return args
})
comments := slice.Map(cache.RecentComments(h.C, int(conf["number"].(int64))), func(t models.Comments) string {
return fmt.Sprintf(` <li>
<span class="comment-author-link">%s</span>发表在《
<a href="/p/%v#comment-%v">%s</a>
</li>`, t.CommentAuthor, t.CommentId, t.CommentPostId, t.PostTitle)
})
s := strings.ReplaceAll(recentCommentsTemplate, "{$li}", strings.Join(comments, "\n"))
return h.ComponentFilterFnHook(widgets.RecentComments, str.Replace(s, args))
}