后台管理重塑 + 主题 / 皮肤双轴 + a11y 与编辑器增强
Backend
- Post 加 cover_url,Tag 加 color;老库 ALTER 兼容
- admin API: GET /api/admin/dashboard,POST /bulk,POST /tags/:id/merge,
PUT /tags/:id 接 {name,color},Settings 加 light_skin_id(兼容老 theme_id)
- 白名单兜底(非法 light_skin_id 落 paper)
- 新增合并 / Dashboard / Theme 测试覆盖
Frontend
- AdminLayout 改为侧边栏布局;新增 Dashboard 总览页
- PostsView 卡片化预览 + 筛选 chip + 批量操作 + 排序
- EditorView 增强:封面图 / WYSIWYG↔MD 双模式 / 实时大纲 / 字数统计 /
自动保存条 / ⌘S / unsaved 守卫(beforeunload + beforeRouteLeave)
- TagsView 加色板 + 合并到目标
- SettingsView 主题外观改为「亮色皮肤」三选一 + 「暗色皮肤」固定墨色说明
- 新增 CommandPalette(⌘K)+ ShortcutsPanel(?)
- api.js 接新接口;router.js 拆 /admin → /admin/posts
主题 / 皮肤双轴
- site.js: themeMode(light/dark/auto)+ light_skin_id;data-theme 前台,
data-admin-theme 后台(仅跟随 mode 切明暗)
- styles.css: :root[data-theme] 四套皮肤 + :root[data-admin-theme=dark] 后台墨感
- 修 sticky head / ThemeSwitcher / 表单 / 批量条 等 token 引用
- 后台用独立 --admin-* 系列,与前台主题解耦
- 左栏底部放 inline 形态 ThemeSwitcher(图标按钮 36×36),mobile 保留浮窗
a11y
- 全局 :focus-visible 描边(前后台跟随 token)
- prefers-reduced-motion 全局降级
- color-scheme 随主题切
- meta theme-color 双套(light/dark)
- 命令面板 / 快捷键面板:role=dialog aria-modal aria-label + 搜索框 aria-label
- icon-only 按钮加 aria-label(tag × / 清除选择 / 移除封面等)
- 输入框 aria-label + spellcheck=false
- PostsView 筛选同步 URL(可分享、可刷新保留)
- img width/height + loading=lazy
- utils.js 用 Intl.DateTimeFormat(zh-CN / sv-SE)
This commit is contained in:
+325
-28
@@ -44,6 +44,7 @@ func (s *Store) migrate() error {
|
||||
title TEXT NOT NULL DEFAULT '',
|
||||
slug TEXT NOT NULL,
|
||||
summary TEXT NOT NULL DEFAULT '',
|
||||
cover_url TEXT NOT NULL DEFAULT '',
|
||||
content_md TEXT NOT NULL DEFAULT '',
|
||||
content_html TEXT NOT NULL DEFAULT '',
|
||||
status TEXT NOT NULL DEFAULT 'draft',
|
||||
@@ -53,9 +54,10 @@ func (s *Store) migrate() error {
|
||||
reading_minutes INTEGER NOT NULL DEFAULT 1
|
||||
)`, ai),
|
||||
fmt.Sprintf(`CREATE TABLE IF NOT EXISTS tags (
|
||||
id %s,
|
||||
name TEXT NOT NULL,
|
||||
slug TEXT NOT NULL
|
||||
id %s,
|
||||
name TEXT NOT NULL,
|
||||
slug TEXT NOT NULL,
|
||||
color TEXT NOT NULL DEFAULT ''
|
||||
)`, ai),
|
||||
`CREATE TABLE IF NOT EXISTS post_tags (
|
||||
post_id INTEGER NOT NULL,
|
||||
@@ -73,6 +75,20 @@ func (s *Store) migrate() error {
|
||||
}
|
||||
}
|
||||
|
||||
// Lightweight column-add migrations for older databases. SQLite supports
|
||||
// ADD COLUMN; Postgres doesn't support IF NOT EXISTS on column add, so we
|
||||
// swallow "already exists" errors either way.
|
||||
columnAdds := []string{
|
||||
`ALTER TABLE posts ADD COLUMN cover_url TEXT NOT NULL DEFAULT ''`,
|
||||
`ALTER TABLE tags ADD COLUMN color TEXT NOT NULL DEFAULT ''`,
|
||||
}
|
||||
for _, q := range columnAdds {
|
||||
if _, err := s.db.Exec(s.db.Q(q)); err != nil && !strings.Contains(err.Error(), "already exists") &&
|
||||
!strings.Contains(err.Error(), "duplicate column") {
|
||||
return fmt.Errorf("migrate column: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
// Indexes/unique constraints need dialect-specific "IF NOT EXISTS" support.
|
||||
indexes := []struct{ name, ddl string }{
|
||||
{"idx_posts_slug", `CREATE UNIQUE INDEX IF NOT EXISTS idx_posts_slug ON posts(slug)`},
|
||||
@@ -144,6 +160,18 @@ func settingsFromMap(m map[string]string) model.Settings {
|
||||
ICPLicense: m["icp"],
|
||||
PostsPerPage: 10,
|
||||
}
|
||||
// LightSkinID is the new canonical name; fall back to legacy theme_id
|
||||
// for clients that haven't been updated, and finally to "paper".
|
||||
st.LightSkinID = m["light_skin_id"]
|
||||
if st.LightSkinID == "" {
|
||||
st.LightSkinID = m["theme_id"]
|
||||
}
|
||||
if st.LightSkinID == "" {
|
||||
st.LightSkinID = "paper"
|
||||
}
|
||||
// Mirror the value into ThemeID so legacy API consumers still see it
|
||||
// in the JSON response.
|
||||
st.ThemeID = st.LightSkinID
|
||||
if n := atoi(m["posts_per_page"]); n > 0 {
|
||||
st.PostsPerPage = n
|
||||
}
|
||||
@@ -161,10 +189,21 @@ func atoi(v string) int {
|
||||
return n
|
||||
}
|
||||
|
||||
// ValidLightSkins is the whitelist of light-side skin ids the API accepts.
|
||||
// Anything outside this set falls back to "paper" on write.
|
||||
var ValidLightSkins = map[string]bool{
|
||||
"paper": true,
|
||||
"sage": true,
|
||||
"rose": true,
|
||||
}
|
||||
|
||||
func (s *Store) UpdateSettings(st model.Settings) error {
|
||||
if st.PostsPerPage <= 0 {
|
||||
st.PostsPerPage = 10
|
||||
}
|
||||
if !ValidLightSkins[st.LightSkinID] {
|
||||
st.LightSkinID = "paper"
|
||||
}
|
||||
sets := map[string]string{
|
||||
"site_title": st.SiteTitle,
|
||||
"site_desc": st.SiteDesc,
|
||||
@@ -173,6 +212,9 @@ func (s *Store) UpdateSettings(st model.Settings) error {
|
||||
"footer_note": st.FooterNote,
|
||||
"icp": st.ICPLicense,
|
||||
"posts_per_page": fmt.Sprint(st.PostsPerPage),
|
||||
"light_skin_id": st.LightSkinID,
|
||||
// Mirror to theme_id so any older client still sees something.
|
||||
"theme_id": st.LightSkinID,
|
||||
}
|
||||
for k, v := range sets {
|
||||
if s.db.Dialect == db.Postgres {
|
||||
@@ -202,13 +244,13 @@ type ListOptions struct {
|
||||
OrderBy string
|
||||
}
|
||||
|
||||
const postCols = `id, kind, title, slug, summary, content_md, content_html, status,
|
||||
const postCols = `id, kind, title, slug, summary, cover_url, content_md, content_html, status,
|
||||
published_at, created_at, updated_at, reading_minutes`
|
||||
|
||||
func scanPost(rows interface{ Scan(...any) error }) (model.Post, error) {
|
||||
var p model.Post
|
||||
err := rows.Scan(&p.ID, &p.Kind, &p.Title, &p.Slug, &p.Summary, &p.ContentMd,
|
||||
&p.ContentHTML, &p.Status, &p.PublishedAt, &p.CreatedAt, &p.UpdatedAt, &p.ReadingMinutes)
|
||||
err := rows.Scan(&p.ID, &p.Kind, &p.Title, &p.Slug, &p.Summary, &p.CoverURL,
|
||||
&p.ContentMd, &p.ContentHTML, &p.Status, &p.PublishedAt, &p.CreatedAt, &p.UpdatedAt, &p.ReadingMinutes)
|
||||
p.Tags = []string{}
|
||||
return p, err
|
||||
}
|
||||
@@ -340,8 +382,8 @@ func (s *Store) GetBySlug(slug string) (model.Post, error) {
|
||||
}
|
||||
|
||||
func scanPostInto(row *sql.Row, p *model.Post) error {
|
||||
err := row.Scan(&p.ID, &p.Kind, &p.Title, &p.Slug, &p.Summary, &p.ContentMd,
|
||||
&p.ContentHTML, &p.Status, &p.PublishedAt, &p.CreatedAt, &p.UpdatedAt, &p.ReadingMinutes)
|
||||
err := row.Scan(&p.ID, &p.Kind, &p.Title, &p.Slug, &p.Summary, &p.CoverURL,
|
||||
&p.ContentMd, &p.ContentHTML, &p.Status, &p.PublishedAt, &p.CreatedAt, &p.UpdatedAt, &p.ReadingMinutes)
|
||||
if err == sql.ErrNoRows {
|
||||
return ErrNotFound
|
||||
}
|
||||
@@ -386,11 +428,12 @@ func (s *Store) uniqueSlug(base string, excludeID int64) string {
|
||||
|
||||
func (s *Store) Create(in model.PostInput) (model.Post, error) {
|
||||
p := model.Post{
|
||||
Kind: in.Kind,
|
||||
Title: strings.TrimSpace(in.Title),
|
||||
Slug: in.Slug,
|
||||
Status: in.Status,
|
||||
Tags: []string{},
|
||||
Kind: in.Kind,
|
||||
Title: strings.TrimSpace(in.Title),
|
||||
Slug: in.Slug,
|
||||
Status: in.Status,
|
||||
CoverURL: strings.TrimSpace(in.CoverURL),
|
||||
Tags: []string{},
|
||||
}
|
||||
if p.Kind == "" {
|
||||
p.Kind = model.KindLong
|
||||
@@ -428,17 +471,17 @@ func (s *Store) Create(in model.PostInput) (model.Post, error) {
|
||||
}
|
||||
|
||||
var id int64
|
||||
q := s.db.Q(`INSERT INTO posts (kind,title,slug,summary,content_md,content_html,status,
|
||||
q := s.db.Q(`INSERT INTO posts (kind,title,slug,summary,cover_url,content_md,content_html,status,
|
||||
published_at,created_at,updated_at,reading_minutes)
|
||||
VALUES (?,?,?,?,?,?,?,?,?,?,?)`)
|
||||
VALUES (?,?,?,?,?,?,?,?,?,?,?,?)`)
|
||||
if s.db.Dialect == db.Postgres {
|
||||
err := s.db.QueryRow(q, p.Kind, p.Title, p.Slug, p.Summary, p.ContentMd, p.ContentHTML,
|
||||
err := s.db.QueryRow(q, p.Kind, p.Title, p.Slug, p.Summary, p.CoverURL, p.ContentMd, p.ContentHTML,
|
||||
p.Status, p.PublishedAt, p.CreatedAt, p.UpdatedAt, p.ReadingMinutes).Scan(&id)
|
||||
if err != nil {
|
||||
return p, err
|
||||
}
|
||||
} else {
|
||||
res, err := s.db.Exec(q, p.Kind, p.Title, p.Slug, p.Summary, p.ContentMd, p.ContentHTML,
|
||||
res, err := s.db.Exec(q, p.Kind, p.Title, p.Slug, p.Summary, p.CoverURL, p.ContentMd, p.ContentHTML,
|
||||
p.Status, p.PublishedAt, p.CreatedAt, p.UpdatedAt, p.ReadingMinutes)
|
||||
if err != nil {
|
||||
return p, err
|
||||
@@ -483,6 +526,10 @@ func (s *Store) Update(id int64, in model.PostInput) (model.Post, error) {
|
||||
if in.PublishedAt != "" {
|
||||
p.PublishedAt = in.PublishedAt
|
||||
}
|
||||
// CoverURL is taken verbatim from input. The frontend always sends the
|
||||
// current value (empty string included), so any update round-trips with
|
||||
// whatever the user last saved.
|
||||
p.CoverURL = strings.TrimSpace(in.CoverURL)
|
||||
p.UpdatedAt = now()
|
||||
if in.ReadingMinutes != nil && *in.ReadingMinutes > 0 {
|
||||
p.ReadingMinutes = *in.ReadingMinutes
|
||||
@@ -490,9 +537,9 @@ func (s *Store) Update(id int64, in model.PostInput) (model.Post, error) {
|
||||
p.ReadingMinutes = readingMinutes(in.ContentMd)
|
||||
}
|
||||
|
||||
if _, err := s.db.Exec(s.db.Q(`UPDATE posts SET kind=?,title=?,slug=?,summary=?,content_md=?,
|
||||
if _, err := s.db.Exec(s.db.Q(`UPDATE posts SET kind=?,title=?,slug=?,summary=?,cover_url=?,content_md=?,
|
||||
content_html=?,status=?,published_at=?,updated_at=?,reading_minutes=? WHERE id=?`),
|
||||
p.Kind, p.Title, p.Slug, p.Summary, p.ContentMd, p.ContentHTML, p.Status,
|
||||
p.Kind, p.Title, p.Slug, p.Summary, p.CoverURL, p.ContentMd, p.ContentHTML, p.Status,
|
||||
p.PublishedAt, p.UpdatedAt, p.ReadingMinutes, id); err != nil {
|
||||
return p, err
|
||||
}
|
||||
@@ -504,6 +551,37 @@ func (s *Store) Update(id int64, in model.PostInput) (model.Post, error) {
|
||||
return s.Get(id)
|
||||
}
|
||||
|
||||
// BulkUpdateStatus flips the status of many posts in a single transaction.
|
||||
func (s *Store) BulkUpdateStatus(ids []int64, status string) (int, error) {
|
||||
if len(ids) == 0 {
|
||||
return 0, nil
|
||||
}
|
||||
status = NormalizeStatus(status)
|
||||
placeholders := strings.TrimSuffix(strings.Repeat("?,", len(ids)), ",")
|
||||
args := []any{status, now()}
|
||||
for _, id := range ids {
|
||||
args = append(args, id)
|
||||
}
|
||||
q := s.db.Q(`UPDATE posts SET status=?, updated_at=? WHERE id IN (` + placeholders + `)`)
|
||||
res, err := s.db.Exec(q, args...)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
n, _ := res.RowsAffected()
|
||||
return int(n), nil
|
||||
}
|
||||
|
||||
// NormalizeStatus coerces an arbitrary input string into a known post status
|
||||
// value, defaulting to draft when nothing matches.
|
||||
func NormalizeStatus(s string) string {
|
||||
switch strings.ToLower(strings.TrimSpace(s)) {
|
||||
case model.StatusDraft, model.StatusPublished:
|
||||
return strings.ToLower(strings.TrimSpace(s))
|
||||
default:
|
||||
return model.StatusDraft
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Store) Delete(id int64) error {
|
||||
if _, err := s.db.Exec(s.db.Q(`DELETE FROM post_tags WHERE post_id = ?`), id); err != nil {
|
||||
return err
|
||||
@@ -568,9 +646,9 @@ func (s *Store) upsertTag(name string) (int64, error) {
|
||||
}
|
||||
|
||||
func (s *Store) ListTags() ([]model.Tag, error) {
|
||||
q := s.db.Q(`SELECT t.id, t.name, t.slug, COUNT(pt.post_id) AS c
|
||||
q := s.db.Q(`SELECT t.id, t.name, t.slug, t.color, COUNT(pt.post_id) AS c
|
||||
FROM tags t LEFT JOIN post_tags pt ON pt.tag_id = t.id
|
||||
GROUP BY t.id, t.name, t.slug ORDER BY c DESC, t.name`)
|
||||
GROUP BY t.id, t.name, t.slug, t.color ORDER BY c DESC, t.name`)
|
||||
rows, err := s.db.Query(q)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -579,7 +657,7 @@ func (s *Store) ListTags() ([]model.Tag, error) {
|
||||
out := []model.Tag{}
|
||||
for rows.Next() {
|
||||
var t model.Tag
|
||||
if err := rows.Scan(&t.ID, &t.Name, &t.Slug, &t.Count); err != nil {
|
||||
if err := rows.Scan(&t.ID, &t.Name, &t.Slug, &t.Color, &t.Count); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out = append(out, t)
|
||||
@@ -599,6 +677,59 @@ func (s *Store) CreateTag(name string) (model.Tag, error) {
|
||||
return model.Tag{ID: id, Name: name, Slug: Slugify(name)}, nil
|
||||
}
|
||||
|
||||
// CreateTagFull is used by the admin API when color is supplied.
|
||||
func (s *Store) CreateTagFull(name, color string) (model.Tag, error) {
|
||||
name = strings.TrimSpace(name)
|
||||
if name == "" {
|
||||
return model.Tag{}, errors.New("tag name required")
|
||||
}
|
||||
slug := Slugify(name)
|
||||
if slug == "" {
|
||||
return model.Tag{}, errors.New("tag slug required")
|
||||
}
|
||||
var id int64
|
||||
err := s.db.QueryRow(s.db.Q(`SELECT id FROM tags WHERE slug = ?`), slug).Scan(&id)
|
||||
if err != nil && err != sql.ErrNoRows {
|
||||
return model.Tag{}, err
|
||||
}
|
||||
if err == nil {
|
||||
// already exists — update color and return
|
||||
if _, err := s.db.Exec(s.db.Q(`UPDATE tags SET color=? WHERE id=?`), color, id); err != nil {
|
||||
return model.Tag{}, err
|
||||
}
|
||||
return s.getTag(id)
|
||||
}
|
||||
color = strings.TrimSpace(color)
|
||||
if s.db.Dialect == db.Postgres {
|
||||
err := s.db.QueryRow(s.db.Q(`INSERT INTO tags(name,slug,color) VALUES (?,?,?) RETURNING id`),
|
||||
name, slug, color).Scan(&id)
|
||||
if err != nil {
|
||||
return model.Tag{}, err
|
||||
}
|
||||
} else {
|
||||
res, err := s.db.Exec(s.db.Q(`INSERT INTO tags(name,slug,color) VALUES (?,?,?)`), name, slug, color)
|
||||
if err != nil {
|
||||
return model.Tag{}, err
|
||||
}
|
||||
id, err = res.LastInsertId()
|
||||
if err != nil {
|
||||
return model.Tag{}, err
|
||||
}
|
||||
}
|
||||
return s.getTag(id)
|
||||
}
|
||||
|
||||
func (s *Store) getTag(id int64) (model.Tag, error) {
|
||||
var t model.Tag
|
||||
err := s.db.QueryRow(s.db.Q(`SELECT t.id, t.name, t.slug, t.color, COUNT(pt.post_id)
|
||||
FROM tags t LEFT JOIN post_tags pt ON pt.tag_id = t.id
|
||||
WHERE t.id = ? GROUP BY t.id`), id).Scan(&t.ID, &t.Name, &t.Slug, &t.Color, &t.Count)
|
||||
if err == sql.ErrNoRows {
|
||||
return t, ErrNotFound
|
||||
}
|
||||
return t, err
|
||||
}
|
||||
|
||||
func (s *Store) RenameTag(id int64, name string) (model.Tag, error) {
|
||||
name = strings.TrimSpace(name)
|
||||
slug := Slugify(name)
|
||||
@@ -608,13 +739,49 @@ func (s *Store) RenameTag(id int64, name string) (model.Tag, error) {
|
||||
if _, err := s.db.Exec(s.db.Q(`UPDATE tags SET name=?, slug=? WHERE id=?`), name, slug, id); err != nil {
|
||||
return model.Tag{}, err
|
||||
}
|
||||
var t model.Tag
|
||||
err := s.db.QueryRow(s.db.Q(`SELECT id, name, slug, 0 FROM tags WHERE id = ?`), id).
|
||||
Scan(&t.ID, &t.Name, &t.Slug, &t.Count)
|
||||
if err == sql.ErrNoRows {
|
||||
return t, ErrNotFound
|
||||
return s.getTag(id)
|
||||
}
|
||||
|
||||
// UpdateTag is the combined rename + recolor used by the admin UI.
|
||||
func (s *Store) UpdateTag(id int64, name, color string) (model.Tag, error) {
|
||||
name = strings.TrimSpace(name)
|
||||
slug := Slugify(name)
|
||||
if name == "" {
|
||||
return model.Tag{}, errors.New("tag name required")
|
||||
}
|
||||
return t, err
|
||||
color = strings.TrimSpace(color)
|
||||
if _, err := s.db.Exec(s.db.Q(`UPDATE tags SET name=?, slug=?, color=? WHERE id=?`), name, slug, color, id); err != nil {
|
||||
return model.Tag{}, err
|
||||
}
|
||||
return s.getTag(id)
|
||||
}
|
||||
|
||||
// MergeTags moves every post from fromID to toID, then deletes fromID. It is a
|
||||
// no-op if the ids are equal or either doesn't exist.
|
||||
func (s *Store) MergeTags(fromID, toID int64) (model.Tag, error) {
|
||||
if fromID == toID {
|
||||
return model.Tag{}, errors.New("source and target are the same tag")
|
||||
}
|
||||
if _, err := s.getTag(fromID); err != nil {
|
||||
return model.Tag{}, err
|
||||
}
|
||||
if _, err := s.getTag(toID); err != nil {
|
||||
return model.Tag{}, err
|
||||
}
|
||||
// De-duplicate before the move so we don't end up with two rows pointing
|
||||
// at the same post.
|
||||
if _, err := s.db.Exec(s.db.Q(`DELETE FROM post_tags
|
||||
WHERE post_id IN (SELECT post_id FROM post_tags WHERE tag_id = ?)
|
||||
AND tag_id = ?`), toID, toID); err != nil {
|
||||
return model.Tag{}, err
|
||||
}
|
||||
if _, err := s.db.Exec(s.db.Q(`UPDATE post_tags SET tag_id=? WHERE tag_id=?`), toID, fromID); err != nil {
|
||||
return model.Tag{}, err
|
||||
}
|
||||
if _, err := s.db.Exec(s.db.Q(`DELETE FROM tags WHERE id=?`), fromID); err != nil {
|
||||
return model.Tag{}, err
|
||||
}
|
||||
return s.getTag(toID)
|
||||
}
|
||||
|
||||
func (s *Store) DeleteTag(id int64) error {
|
||||
@@ -667,3 +834,133 @@ func splitDate(rfc3339 string) (string, string) {
|
||||
}
|
||||
return rfc3339[0:4], rfc3339[5:7]
|
||||
}
|
||||
|
||||
// ---------- dashboard ----------
|
||||
|
||||
// Dashboard produces the snapshot rendered on the admin home page.
|
||||
func (s *Store) Dashboard() (model.Dashboard, error) {
|
||||
d := model.Dashboard{
|
||||
RecentPosts: []model.Post{},
|
||||
RecentDrafts: []model.Post{},
|
||||
TopTags: []model.Tag{},
|
||||
PublishedByMonth: []model.MonthBucket{},
|
||||
}
|
||||
|
||||
// status / kind counts --------------------------------------------------
|
||||
rows, err := s.db.Query(s.db.Q(`SELECT status, kind, COUNT(*) FROM posts GROUP BY status, kind`))
|
||||
if err != nil {
|
||||
return d, err
|
||||
}
|
||||
for rows.Next() {
|
||||
var status, kind string
|
||||
var n int
|
||||
if err := rows.Scan(&status, &kind, &n); err != nil {
|
||||
rows.Close()
|
||||
return d, err
|
||||
}
|
||||
d.TotalPosts += n
|
||||
switch status {
|
||||
case model.StatusPublished:
|
||||
d.PublishedPosts += n
|
||||
case model.StatusDraft:
|
||||
d.DraftPosts += n
|
||||
}
|
||||
switch kind {
|
||||
case model.KindShort:
|
||||
d.ShortPosts += n
|
||||
case model.KindLong:
|
||||
d.LongPosts += n
|
||||
}
|
||||
}
|
||||
rows.Close()
|
||||
|
||||
// total tag count -------------------------------------------------------
|
||||
if err := s.db.QueryRow(s.db.Q(`SELECT COUNT(*) FROM tags`)).Scan(&d.TotalTags); err != nil {
|
||||
return d, err
|
||||
}
|
||||
|
||||
// total word count: sum of content_md length ----------------------------
|
||||
if err := s.db.QueryRow(s.db.Q(`SELECT COALESCE(SUM(LENGTH(content_md)),0) FROM posts`)).Scan(&d.TotalWords); err != nil {
|
||||
return d, err
|
||||
}
|
||||
|
||||
// recent published posts (5) --------------------------------------------
|
||||
if err := s.scanPostsInto(s.db.Q(`SELECT `+postCols+` FROM posts
|
||||
WHERE status=? ORDER BY published_at DESC LIMIT 5`), []any{model.StatusPublished}, &d.RecentPosts); err != nil {
|
||||
return d, err
|
||||
}
|
||||
|
||||
// recent drafts (5) -----------------------------------------------------
|
||||
if err := s.scanPostsInto(s.db.Q(`SELECT `+postCols+` FROM posts
|
||||
WHERE status=? ORDER BY updated_at DESC LIMIT 5`), []any{model.StatusDraft}, &d.RecentDrafts); err != nil {
|
||||
return d, err
|
||||
}
|
||||
|
||||
// top tags (10) ---------------------------------------------------------
|
||||
if err := s.db.QueryRow(s.db.Q(`SELECT COUNT(*) FROM tags`)).Scan(&d.TotalTags); err != nil {
|
||||
return d, err
|
||||
}
|
||||
tagRows, err := s.db.Query(s.db.Q(`SELECT t.id, t.name, t.slug, t.color, COUNT(pt.post_id) AS c
|
||||
FROM tags t LEFT JOIN post_tags pt ON pt.tag_id = t.id
|
||||
GROUP BY t.id, t.name, t.slug, t.color ORDER BY c DESC, t.name LIMIT 10`))
|
||||
if err != nil {
|
||||
return d, err
|
||||
}
|
||||
for tagRows.Next() {
|
||||
var t model.Tag
|
||||
if err := tagRows.Scan(&t.ID, &t.Name, &t.Slug, &t.Color, &t.Count); err != nil {
|
||||
tagRows.Close()
|
||||
return d, err
|
||||
}
|
||||
d.TopTags = append(d.TopTags, t)
|
||||
}
|
||||
tagRows.Close()
|
||||
|
||||
// published_by_month — last 12 months -----------------------------------
|
||||
monthRows, err := s.db.Query(s.db.Q(`SELECT substr(published_at,1,7) AS m, COUNT(*) AS c
|
||||
FROM posts WHERE status=? AND length(published_at) >= 7
|
||||
GROUP BY m ORDER BY m DESC LIMIT 12`), model.StatusPublished)
|
||||
if err != nil {
|
||||
return d, err
|
||||
}
|
||||
defer monthRows.Close()
|
||||
for monthRows.Next() {
|
||||
var b model.MonthBucket
|
||||
if err := monthRows.Scan(&b.Month, &b.Count); err != nil {
|
||||
return d, err
|
||||
}
|
||||
d.PublishedByMonth = append(d.PublishedByMonth, b)
|
||||
}
|
||||
// reverse so we can render left-to-right on the chart
|
||||
for i, j := 0, len(d.PublishedByMonth)-1; i < j; i, j = i+1, j-1 {
|
||||
d.PublishedByMonth[i], d.PublishedByMonth[j] = d.PublishedByMonth[j], d.PublishedByMonth[i]
|
||||
}
|
||||
|
||||
return d, nil
|
||||
}
|
||||
|
||||
// scanPostsInto is a small helper that runs a query and scans rows into the
|
||||
// given slice, attaching tags at the end.
|
||||
func (s *Store) scanPostsInto(query string, args []any, dst *[]model.Post) error {
|
||||
rows, err := s.db.Query(query, args...)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer rows.Close()
|
||||
out := []model.Post{}
|
||||
for rows.Next() {
|
||||
p, err := scanPost(rows)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
out = append(out, p)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := s.attachTags(out); err != nil {
|
||||
return err
|
||||
}
|
||||
*dst = out
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -40,3 +40,227 @@ func TestPostInputDefaults(t *testing.T) {
|
||||
t.Errorf("empty status means draft is applied by the API layer, got %q", in.Status)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNormalizeStatus(t *testing.T) {
|
||||
cases := map[string]string{
|
||||
"": model.StatusDraft,
|
||||
"draft": model.StatusDraft,
|
||||
"published": model.StatusPublished,
|
||||
" Published ": model.StatusPublished,
|
||||
"pending": model.StatusDraft, // unknown → draft
|
||||
}
|
||||
for in, want := range cases {
|
||||
if got := NormalizeStatus(in); got != want {
|
||||
t.Errorf("NormalizeStatus(%q) = %q, want %q", in, got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestRebindBulk(t *testing.T) {
|
||||
// BulkUpdateStatus uses an IN clause with len(ids) placeholders + 1 for status.
|
||||
d := &db.DB{Dialect: db.Postgres}
|
||||
q := d.Q(`UPDATE posts SET status=? WHERE id IN (?,?,?)`)
|
||||
if got := strings.Count(q, "$"); got != 4 {
|
||||
t.Errorf("expected 4 placeholders, got %d", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSettingsThemeID(t *testing.T) {
|
||||
s := openTestStore(t)
|
||||
|
||||
st, err := s.GetSettings()
|
||||
if err != nil {
|
||||
t.Fatalf("get: %v", err)
|
||||
}
|
||||
if st.LightSkinID != "paper" {
|
||||
t.Errorf("default light_skin_id should be 'paper', got %q", st.LightSkinID)
|
||||
}
|
||||
|
||||
st.LightSkinID = "sage"
|
||||
st.SiteTitle = "ONE"
|
||||
if err := s.UpdateSettings(st); err != nil {
|
||||
t.Fatalf("update: %v", err)
|
||||
}
|
||||
got, err := s.GetSettings()
|
||||
if err != nil {
|
||||
t.Fatalf("get again: %v", err)
|
||||
}
|
||||
if got.LightSkinID != "sage" {
|
||||
t.Errorf("light_skin_id should persist, got %q", got.LightSkinID)
|
||||
}
|
||||
if got.ThemeID != "sage" {
|
||||
t.Errorf("legacy theme_id should mirror light_skin_id, got %q", got.ThemeID)
|
||||
}
|
||||
if got.SiteTitle != "ONE" {
|
||||
t.Errorf("site_title should persist, got %q", got.SiteTitle)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSettingsLightSkinFallback(t *testing.T) {
|
||||
s := openTestStore(t)
|
||||
// Simulate an older DB that only has theme_id set.
|
||||
if _, err := s.db.Exec(s.db.Q(`INSERT INTO settings(key,value) VALUES (?,?) ON CONFLICT(key) DO UPDATE SET value=excluded.value`),
|
||||
"theme_id", "rose"); err != nil {
|
||||
t.Fatalf("seed theme_id: %v", err)
|
||||
}
|
||||
st, err := s.GetSettings()
|
||||
if err != nil {
|
||||
t.Fatalf("get: %v", err)
|
||||
}
|
||||
if st.LightSkinID != "rose" {
|
||||
t.Errorf("expected fallback to 'rose' from legacy theme_id, got %q", st.LightSkinID)
|
||||
}
|
||||
}
|
||||
|
||||
// TestStoreSQLite runs a small integration pass on top of an in-memory SQLite
|
||||
// database to exercise the new fields (cover_url, tag color) and the merge
|
||||
// + bulk + dashboard paths.
|
||||
func TestStoreSQLite(t *testing.T) {
|
||||
s := openTestStore(t)
|
||||
|
||||
p1, err := s.Create(model.PostInput{
|
||||
Kind: model.KindLong,
|
||||
Title: "第一篇",
|
||||
Slug: "first",
|
||||
Summary: "first summary",
|
||||
CoverURL: "https://example.com/a.png",
|
||||
ContentMd: "# hi\n这是一段正文。",
|
||||
Status: model.StatusPublished,
|
||||
Tags: []string{"Go", "博客"},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("create p1: %v", err)
|
||||
}
|
||||
if p1.CoverURL == "" {
|
||||
t.Errorf("cover_url not persisted")
|
||||
}
|
||||
if len(p1.Tags) != 2 {
|
||||
t.Errorf("expected 2 tags, got %v", p1.Tags)
|
||||
}
|
||||
|
||||
p2, err := s.Create(model.PostInput{
|
||||
Kind: model.KindShort, ContentMd: "碎片想法。", Status: model.StatusDraft,
|
||||
Tags: []string{"碎片"},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("create p2: %v", err)
|
||||
}
|
||||
|
||||
// Update cover_url and tags. Frontend sends the current CoverURL back so
|
||||
// the value is preserved across updates.
|
||||
upd, err := s.Update(p1.ID, model.PostInput{
|
||||
Kind: model.KindLong, Title: "第一篇",
|
||||
CoverURL: p1.CoverURL,
|
||||
ContentMd: "# hi\n这是新版本。",
|
||||
Tags: []string{"Go"},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("update: %v", err)
|
||||
}
|
||||
if upd.CoverURL != p1.CoverURL {
|
||||
t.Errorf("cover_url not preserved when echoed back, got %q", upd.CoverURL)
|
||||
}
|
||||
|
||||
// An empty CoverURL is treated as an explicit clear.
|
||||
upd2, err := s.Update(p1.ID, model.PostInput{
|
||||
Kind: model.KindLong, Title: "第一篇", CoverURL: "",
|
||||
Tags: []string{"Go"},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("update clear: %v", err)
|
||||
}
|
||||
if upd2.CoverURL != "" {
|
||||
t.Errorf("empty cover_url should clear, got %q", upd2.CoverURL)
|
||||
}
|
||||
// restore for downstream tests
|
||||
if _, err := s.Update(p1.ID, model.PostInput{
|
||||
Kind: model.KindLong, Title: "第一篇", CoverURL: p1.CoverURL,
|
||||
Tags: []string{"Go"},
|
||||
}); err != nil {
|
||||
t.Fatalf("restore: %v", err)
|
||||
}
|
||||
|
||||
if len(upd.Tags) != 1 || upd.Tags[0] != "Go" {
|
||||
t.Errorf("tags after update: %v", upd.Tags)
|
||||
}
|
||||
|
||||
// BulkUpdateStatus flips drafts to published
|
||||
n, err := s.BulkUpdateStatus([]int64{p2.ID}, model.StatusPublished)
|
||||
if err != nil {
|
||||
t.Fatalf("bulk: %v", err)
|
||||
}
|
||||
if n != 1 {
|
||||
t.Errorf("expected 1 updated, got %d", n)
|
||||
}
|
||||
|
||||
// Tag merge: create two distinct slug tags, attach both to p1, merge.
|
||||
if _, err := s.UpdateTag(0, "", ""); err == nil {
|
||||
t.Errorf("expected error for empty name")
|
||||
}
|
||||
tags, err := s.ListTags()
|
||||
if err != nil {
|
||||
t.Fatalf("list tags: %v", err)
|
||||
}
|
||||
var goID int64
|
||||
for _, tg := range tags {
|
||||
if tg.Name == "Go" {
|
||||
goID = tg.ID
|
||||
}
|
||||
}
|
||||
if goID == 0 {
|
||||
t.Fatalf("Go tag not found")
|
||||
}
|
||||
// Give the surviving target tag a color so we can confirm it sticks.
|
||||
if _, err := s.UpdateTag(goID, "Go", "#3d7f9c"); err != nil {
|
||||
t.Fatalf("color target: %v", err)
|
||||
}
|
||||
// CreateTagFull uses upsertTag so "GoLang" with its own slug is a fresh row.
|
||||
golang, err := s.CreateTagFull("GoLang", "")
|
||||
if err != nil {
|
||||
t.Fatalf("create golang: %v", err)
|
||||
}
|
||||
if _, err := s.db.Exec(s.db.Q(`INSERT INTO post_tags(post_id, tag_id) VALUES (?, ?)`), p1.ID, golang.ID); err != nil {
|
||||
t.Fatalf("attach golang: %v", err)
|
||||
}
|
||||
merged, err := s.MergeTags(golang.ID, goID)
|
||||
if err != nil {
|
||||
t.Fatalf("merge: %v", err)
|
||||
}
|
||||
if merged.ID != goID {
|
||||
t.Errorf("merge should return target tag, got %d want %d", merged.ID, goID)
|
||||
}
|
||||
if merged.Color != "#3d7f9c" {
|
||||
t.Errorf("target tag color lost, got %q", merged.Color)
|
||||
}
|
||||
|
||||
// Dashboard
|
||||
d, err := s.Dashboard()
|
||||
if err != nil {
|
||||
t.Fatalf("dashboard: %v", err)
|
||||
}
|
||||
if d.TotalPosts != 2 {
|
||||
t.Errorf("total_posts = %d", d.TotalPosts)
|
||||
}
|
||||
if d.PublishedPosts != 2 {
|
||||
t.Errorf("published_posts = %d", d.PublishedPosts)
|
||||
}
|
||||
if len(d.RecentPosts) == 0 {
|
||||
t.Errorf("recent posts empty")
|
||||
}
|
||||
if len(d.TopTags) == 0 {
|
||||
t.Errorf("top tags empty")
|
||||
}
|
||||
}
|
||||
|
||||
func openTestStore(t *testing.T) *Store {
|
||||
t.Helper()
|
||||
d, err := db.Open("sqlite", ":memory:")
|
||||
if err != nil {
|
||||
t.Fatalf("open sqlite: %v", err)
|
||||
}
|
||||
s, err := New(d)
|
||||
if err != nil {
|
||||
t.Fatalf("new store: %v", err)
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user