Compare commits
14
Commits
v3.2.1-beta
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
18600ab49d | ||
|
|
daf3594316 | ||
|
|
9f4ce426a8 | ||
|
|
02fb8751fd | ||
|
|
cb737b7ae3 | ||
|
|
470584400f | ||
|
|
eb9876fde3 | ||
|
|
0eb46b0d74 | ||
|
|
cb1410f0b0 | ||
|
|
6b8990c55e | ||
|
|
3d81d2c717 | ||
|
|
b34a173d83 | ||
|
|
a11338094e | ||
|
|
45fcbd890d |
No files matched your search
@@ -48,6 +48,7 @@ task dev # API with hot reload + Vite HMR → http://localhost:51
|
||||
| [docs/docker.md](docs/docker.md) | Running RenewCMS in Docker: image, Compose, data volume, backups, reverse proxy, tags, upgrades, publishing |
|
||||
| [docs/configuration.md](docs/configuration.md) | Every environment variable |
|
||||
| [docs/architecture.md](docs/architecture.md) | Backend layering and how the SPA is embedded |
|
||||
| [docs/performance.md](docs/performance.md) | Measured costs, such as the `?seo=` article filter |
|
||||
| [docs/api.md](docs/api.md) | API reference: authentication, API keys, routes and the activity log |
|
||||
| [docs/api/articles.md](docs/api/articles.md) | Reading articles: pagination, search, `format` and body schemas |
|
||||
| [docs/image-variants.md](docs/image-variants.md) | Image variants and their cache |
|
||||
|
||||
+45
-11
@@ -4,10 +4,12 @@ import (
|
||||
domainAPIKey "RenewCMS/internal/domain/apikey"
|
||||
domainArticle "RenewCMS/internal/domain/article"
|
||||
domainAudit "RenewCMS/internal/domain/audit"
|
||||
domainAuthor "RenewCMS/internal/domain/author"
|
||||
domainImage "RenewCMS/internal/domain/image"
|
||||
domainInvite "RenewCMS/internal/domain/invite"
|
||||
domainMail "RenewCMS/internal/domain/mail"
|
||||
domainPurge "RenewCMS/internal/domain/purge"
|
||||
domainSite "RenewCMS/internal/domain/site"
|
||||
domainUpdate "RenewCMS/internal/domain/update"
|
||||
domainUser "RenewCMS/internal/domain/user"
|
||||
"RenewCMS/internal/infrastructure/auditing"
|
||||
@@ -46,7 +48,21 @@ type UseCases struct {
|
||||
GetArticleUseCase *useCases.GetArticleUseCase
|
||||
ListArticlesUseCase *useCases.ListArticlesUseCase
|
||||
UpdateArticleUseCase *useCases.UpdateArticleUseCase
|
||||
ResolveArticleSEOUseCase *useCases.ResolveArticleSEOUseCase
|
||||
CheckArticleSEOUseCase *useCases.CheckArticleSEOUseCase
|
||||
ListSitemapUseCase *useCases.ListSitemapUseCase
|
||||
DeleteArticleUseCase *useCases.DeleteArticleUseCase
|
||||
ListAuthorsUseCase *useCases.ListAuthorsUseCase
|
||||
CreateAuthorUseCase *useCases.CreateAuthorUseCase
|
||||
CreateMyAuthorUseCase *useCases.CreateMyAuthorUseCase
|
||||
UpdateAuthorUseCase *useCases.UpdateAuthorUseCase
|
||||
DeleteAuthorUseCase *useCases.DeleteAuthorUseCase
|
||||
GetMyAuthorUseCase *useCases.GetMyAuthorUseCase
|
||||
ListSitesUseCase *useCases.ListSitesUseCase
|
||||
CreateSiteUseCase *useCases.CreateSiteUseCase
|
||||
UpdateSiteUseCase *useCases.UpdateSiteUseCase
|
||||
SetDefaultSiteUseCase *useCases.SetDefaultSiteUseCase
|
||||
DeleteSiteUseCase *useCases.DeleteSiteUseCase
|
||||
GetUserUseCase *useCases.GetUserUseCase
|
||||
CreateUserUseCase *useCases.CreateUserUseCase
|
||||
AuthenticateUserUseCase *useCases.AuthenticateUserUseCase
|
||||
@@ -123,6 +139,8 @@ func (c *UseCases) RunSchedulers(ctx context.Context) {
|
||||
|
||||
type Repositories struct {
|
||||
ArticleRepo domainArticle.Repository
|
||||
SiteRepo domainSite.Repository
|
||||
AuthorRepo domainAuthor.Repository
|
||||
UserRepo domainUser.Repository
|
||||
ImageRepo domainImage.Repository
|
||||
VariantRepo domainImage.VariantRepository
|
||||
@@ -241,7 +259,7 @@ func openDatabase(settings config.Settings) *database.Connection {
|
||||
if err != nil {
|
||||
panic("Unable to open the database: " + err.Error())
|
||||
}
|
||||
if err := database.Migrate(connection.DB); err != nil {
|
||||
if err := database.Migrate(connection.DB, settings.PublicURL); err != nil {
|
||||
panic("Failed to migrate database: " + err.Error())
|
||||
}
|
||||
return connection
|
||||
@@ -261,6 +279,8 @@ func getRepositories(connection *database.Connection, settings config.Settings)
|
||||
variantFiles := persistence.NewVariantFileRepository(db)
|
||||
return &Repositories{
|
||||
ArticleRepo: persistence.NewArticleRepository(db),
|
||||
SiteRepo: persistence.NewSiteRepository(db),
|
||||
AuthorRepo: persistence.NewAuthorRepository(db),
|
||||
UserRepo: persistence.NewUserRepository(db),
|
||||
ImageRepo: persistence.NewImageRepository(db),
|
||||
VariantRepo: persistence.NewVariantRepository(db),
|
||||
@@ -293,9 +313,9 @@ func getUseCases(repos *Repositories, imageStorage domainImage.Storage, settings
|
||||
renderer := markdown.NewConverter()
|
||||
keyGenerator := hashing.NewSHA256KeyGenerator()
|
||||
recorder := auditing.NewRecorder(repos.AuditRepo, time.Now, log.Default())
|
||||
mergeMedia := useCases.NewMergeMediaUseCase(repos.ImageRepo, repos.ArticleRepo, imageStorage, repos.VariantFileRepo, recorder)
|
||||
mergeMedia := useCases.NewMergeMediaUseCase(repos.ImageRepo, repos.ArticleRepo, imageStorage, repos.VariantFileRepo, recorder, repos.SiteRepo, repos.AuthorRepo)
|
||||
|
||||
runPurge := useCases.NewRunPurgeUseCase(repos.ImageRepo, repos.ArticleRepo, mergeMedia, repos.PurgeSettingsRepo, time.Now, log.Default(), recorder)
|
||||
runPurge := useCases.NewRunPurgeUseCase(repos.ImageRepo, repos.ArticleRepo, mergeMedia, repos.PurgeSettingsRepo, time.Now, log.Default(), recorder, repos.SiteRepo, repos.AuthorRepo)
|
||||
purgeScheduler := useCases.NewPurgeSchedulerUseCase(repos.PurgeSettingsRepo, runPurge, recorder)
|
||||
activityCleanup := useCases.NewCleanupActivityUseCase(repos.AuditRepo, repos.AuditSettingsRepo, recorder)
|
||||
|
||||
@@ -306,11 +326,25 @@ func getUseCases(repos *Repositories, imageStorage domainImage.Storage, settings
|
||||
PurgeScheduler: scheduler.NewSystemRunner(purgeScheduler, log.Default()),
|
||||
ActivityCleanupScheduler: scheduler.NewSystemCleanupRunner(activityCleanup, log.Default()),
|
||||
Token: jwtauth.New("HS256", []byte(settings.JWTSecret), nil),
|
||||
CreateArticleUseCase: useCases.NewCreateArticleUseCase(repos.ArticleRepo, renderer, recorder),
|
||||
CreateArticleUseCase: useCases.NewCreateArticleUseCase(repos.ArticleRepo, renderer, recorder, repos.SiteRepo, repos.AuthorRepo),
|
||||
GetArticleUseCase: useCases.NewGetArticleUseCase(repos.ArticleRepo, renderer),
|
||||
ListArticlesUseCase: useCases.NewListArticlesUseCase(repos.ArticleRepo, renderer),
|
||||
UpdateArticleUseCase: useCases.NewUpdateArticleUseCase(repos.ArticleRepo, renderer, recorder),
|
||||
ListArticlesUseCase: useCases.NewListArticlesUseCase(repos.ArticleRepo, renderer, repos.SiteRepo),
|
||||
UpdateArticleUseCase: useCases.NewUpdateArticleUseCase(repos.ArticleRepo, renderer, recorder, repos.SiteRepo, repos.AuthorRepo, repos.ImageRepo),
|
||||
DeleteArticleUseCase: useCases.NewDeleteArticleUseCase(repos.ArticleRepo, recorder),
|
||||
ResolveArticleSEOUseCase: useCases.NewResolveArticleSEOUseCase(repos.ArticleRepo, repos.SiteRepo, repos.ImageRepo),
|
||||
CheckArticleSEOUseCase: useCases.NewCheckArticleSEOUseCase(repos.ArticleRepo, repos.SiteRepo, repos.ImageRepo),
|
||||
ListSitemapUseCase: useCases.NewListSitemapUseCase(repos.ArticleRepo, repos.SiteRepo),
|
||||
ListAuthorsUseCase: useCases.NewListAuthorsUseCase(repos.AuthorRepo, repos.UserRepo),
|
||||
CreateAuthorUseCase: useCases.NewCreateAuthorUseCase(repos.AuthorRepo, repos.UserRepo, repos.ImageRepo, recorder),
|
||||
CreateMyAuthorUseCase: useCases.NewCreateMyAuthorUseCase(repos.AuthorRepo, repos.UserRepo, recorder),
|
||||
UpdateAuthorUseCase: useCases.NewUpdateAuthorUseCase(repos.AuthorRepo, repos.UserRepo, repos.ImageRepo, recorder),
|
||||
DeleteAuthorUseCase: useCases.NewDeleteAuthorUseCase(repos.AuthorRepo, recorder),
|
||||
GetMyAuthorUseCase: useCases.NewGetMyAuthorUseCase(repos.AuthorRepo),
|
||||
ListSitesUseCase: useCases.NewListSitesUseCase(repos.SiteRepo),
|
||||
CreateSiteUseCase: useCases.NewCreateSiteUseCase(repos.SiteRepo, repos.ImageRepo, recorder),
|
||||
UpdateSiteUseCase: useCases.NewUpdateSiteUseCase(repos.SiteRepo, repos.ImageRepo, recorder),
|
||||
SetDefaultSiteUseCase: useCases.NewSetDefaultSiteUseCase(repos.SiteRepo, recorder),
|
||||
DeleteSiteUseCase: useCases.NewDeleteSiteUseCase(repos.SiteRepo, recorder),
|
||||
GetUserUseCase: useCases.NewGetUserUseCase(repos.UserRepo),
|
||||
CreateUserUseCase: useCases.NewCreateUserUseCase(repos.UserRepo, hasher, repos.MailRepo, settings.PublicURL, recorder),
|
||||
AuthenticateUserUseCase: useCases.NewAuthenticateUserUseCase(repos.UserRepo, hasher, recorder),
|
||||
@@ -329,14 +363,14 @@ func getUseCases(repos *Repositories, imageStorage domainImage.Storage, settings
|
||||
SendMailUseCase: useCases.NewSendMailUseCase(repos.MailRepo),
|
||||
CreateImageUseCase: useCases.NewCreateImageUseCase(repos.ImageRepo, imageStorage, recorder),
|
||||
OpenMediaUseCase: useCases.NewOpenMediaUseCase(imageStorage),
|
||||
ListMediaUseCase: useCases.NewListMediaUseCase(repos.ImageRepo, repos.ArticleRepo, repos.UserRepo, repos.VariantFileRepo),
|
||||
ListMediaUseCase: useCases.NewListMediaUseCase(repos.ImageRepo, repos.ArticleRepo, repos.UserRepo, repos.VariantFileRepo, repos.SiteRepo, repos.AuthorRepo),
|
||||
RenameMediaUseCase: useCases.NewRenameMediaUseCase(repos.ImageRepo, recorder),
|
||||
DeleteMediaUseCase: useCases.NewDeleteMediaUseCase(repos.ImageRepo, imageStorage, repos.VariantFileRepo, recorder),
|
||||
DeleteMediaUseCase: useCases.NewDeleteMediaUseCase(repos.ImageRepo, imageStorage, repos.VariantFileRepo, recorder, repos.SiteRepo, repos.AuthorRepo, repos.ArticleRepo),
|
||||
MergeMediaUseCase: mergeMedia,
|
||||
GetMediaUsageUseCase: useCases.NewGetMediaUsageUseCase(repos.ImageRepo, repos.ArticleRepo),
|
||||
GetMediaUsageUseCase: useCases.NewGetMediaUsageUseCase(repos.ImageRepo, repos.ArticleRepo, repos.SiteRepo, repos.AuthorRepo),
|
||||
GetPurgeSettingsUseCase: useCases.NewGetPurgeSettingsUseCase(repos.PurgeSettingsRepo),
|
||||
UpdatePurgeSettingsUseCase: useCases.NewUpdatePurgeSettingsUseCase(repos.PurgeSettingsRepo, time.Now),
|
||||
PreviewPurgeUseCase: useCases.NewPreviewPurgeUseCase(repos.ImageRepo, repos.ArticleRepo),
|
||||
PreviewPurgeUseCase: useCases.NewPreviewPurgeUseCase(repos.ImageRepo, repos.ArticleRepo, repos.SiteRepo, repos.AuthorRepo),
|
||||
RunPurgeUseCase: runPurge,
|
||||
GetSettingsUseCase: useCases.NewGetSettingsUseCase(settings.Version),
|
||||
GetUpdateStatusUseCase: useCases.NewGetUpdateStatusUseCase(repos.UpdateStore, repos.UpdateJobs, repos.UpdateHelper, repos.UpdateResults, repos.RestartRequests, settings.Version, settings.Container, time.Now),
|
||||
@@ -348,7 +382,7 @@ func getUseCases(repos *Repositories, imageStorage domainImage.Storage, settings
|
||||
ListAPIKeysUseCase: useCases.NewListAPIKeysUseCase(repos.APIKeyRepo, repos.UserRepo, time.Now),
|
||||
RevokeAPIKeyUseCase: useCases.NewRevokeAPIKeyUseCase(repos.APIKeyRepo, repos.UserRepo, time.Now, recorder),
|
||||
AuthenticateAPIKeyUseCase: useCases.NewAuthenticateAPIKeyUseCase(repos.APIKeyRepo, keyGenerator, repos.UserRepo, time.Now),
|
||||
ListActivityUseCase: useCases.NewListActivityUseCase(repos.AuditRepo, repos.UserRepo, repos.ArticleRepo, repos.ImageRepo, repos.APIKeyRepo, time.Now),
|
||||
ListActivityUseCase: useCases.NewListActivityUseCase(repos.AuditRepo, repos.UserRepo, repos.ArticleRepo, repos.ImageRepo, repos.APIKeyRepo, time.Now, repos.SiteRepo, repos.AuthorRepo),
|
||||
GetActivitySummaryUseCase: useCases.NewGetActivitySummaryUseCase(repos.AuditRepo, time.Now),
|
||||
ExportActivityUseCase: useCases.NewExportActivityUseCase(repos.AuditRepo, time.Now),
|
||||
GetActivityRetentionUseCase: useCases.NewGetActivityRetentionUseCase(repos.AuditSettingsRepo, repos.AuditRepo, time.Now),
|
||||
|
||||
@@ -29,7 +29,7 @@ type Handler struct {
|
||||
type filterQuery struct {
|
||||
Q string `validate:"max=200"`
|
||||
Actor string `validate:"max=40"`
|
||||
Category string `validate:"omitempty,oneof=articles media users api_keys auth system"`
|
||||
Category string `validate:"omitempty,oneof=articles media users api_keys auth system sites authors"`
|
||||
Outcome string `validate:"omitempty,oneof=all success failed"`
|
||||
Security string `validate:"omitempty,oneof=true"`
|
||||
Range string `validate:"omitempty,oneof=today 7d 30d all custom"`
|
||||
|
||||
@@ -5,18 +5,24 @@ import (
|
||||
"RenewCMS/api/pkg/claims"
|
||||
validator "RenewCMS/api/pkg/validator"
|
||||
domain "RenewCMS/internal/domain/article"
|
||||
"RenewCMS/internal/domain/author"
|
||||
"RenewCMS/internal/domain/image"
|
||||
"RenewCMS/internal/domain/site"
|
||||
"RenewCMS/internal/infrastructure/useCases"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"log"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
playground "github.com/go-playground/validator/v10"
|
||||
)
|
||||
|
||||
type Handler struct {
|
||||
@@ -44,36 +50,102 @@ func NewHandler(create *useCases.CreateArticleUseCase, get *useCases.GetArticleU
|
||||
}
|
||||
}
|
||||
|
||||
type articleResponse struct {
|
||||
type baseArticleResponse struct {
|
||||
ID uint32 `json:"id"`
|
||||
Title string `json:"title"`
|
||||
Body json.RawMessage `json:"body"`
|
||||
BodyFormat domain.BodyFormat `json:"body_format"`
|
||||
IsOnline bool `json:"is_online"`
|
||||
SiteID uint32 `json:"site_id"`
|
||||
Authors []author.Byline `json:"authors"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
func toArticleResponse(article domain.Article, format domain.BodyFormat) (articleResponse, error) {
|
||||
type articleResponse struct {
|
||||
baseArticleResponse
|
||||
Slug string `json:"slug"`
|
||||
Excerpt string `json:"excerpt"`
|
||||
SEOTitle string `json:"seo_title"`
|
||||
SEODescription string `json:"seo_description"`
|
||||
CoverImageID *uint32 `json:"cover_image_id"`
|
||||
CoverImageAlt string `json:"cover_image_alt"`
|
||||
SocialTitle string `json:"social_title"`
|
||||
SocialDescription string `json:"social_description"`
|
||||
SocialImageID *uint32 `json:"social_image_id"`
|
||||
CanonicalURL string `json:"canonical_url"`
|
||||
Noindex bool `json:"noindex"`
|
||||
SEODismissed []string `json:"seo_dismissed"`
|
||||
}
|
||||
|
||||
type listItemResponse struct {
|
||||
baseArticleResponse
|
||||
Excerpt string `json:"excerpt"`
|
||||
Slug string `json:"slug"`
|
||||
SEOStatus string `json:"seo_status"`
|
||||
SEOSuggestions int `json:"seo_suggestions"`
|
||||
}
|
||||
|
||||
func toBaseResponse(article domain.Article, format domain.BodyFormat) (baseArticleResponse, error) {
|
||||
body := json.RawMessage(article.Body)
|
||||
if format != domain.BodyFormatJSON {
|
||||
encoded, err := json.Marshal(article.Body)
|
||||
if err != nil {
|
||||
return articleResponse{}, err
|
||||
return baseArticleResponse{}, err
|
||||
}
|
||||
body = encoded
|
||||
}
|
||||
return articleResponse{
|
||||
authors := article.Authors
|
||||
if authors == nil {
|
||||
authors = []author.Byline{}
|
||||
}
|
||||
return baseArticleResponse{
|
||||
ID: article.ID,
|
||||
Title: article.Title,
|
||||
Body: body,
|
||||
BodyFormat: format,
|
||||
IsOnline: article.IsOnline,
|
||||
SiteID: article.SiteID,
|
||||
Authors: authors,
|
||||
CreatedAt: article.CreatedAt,
|
||||
UpdatedAt: article.UpdatedAt,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func toArticleResponse(article domain.Article, format domain.BodyFormat) (articleResponse, error) {
|
||||
base, err := toBaseResponse(article, format)
|
||||
if err != nil {
|
||||
return articleResponse{}, err
|
||||
}
|
||||
dismissed := article.SEODismissed
|
||||
if dismissed == nil {
|
||||
dismissed = []string{}
|
||||
}
|
||||
return articleResponse{
|
||||
baseArticleResponse: base,
|
||||
Slug: article.Slug,
|
||||
Excerpt: article.Excerpt,
|
||||
SEOTitle: article.SEOTitle,
|
||||
SEODescription: article.SEODescription,
|
||||
CoverImageID: article.CoverImageID,
|
||||
CoverImageAlt: article.CoverImageAlt,
|
||||
SocialTitle: article.SocialTitle,
|
||||
SocialDescription: article.SocialDescription,
|
||||
SocialImageID: article.SocialImageID,
|
||||
CanonicalURL: article.CanonicalURL,
|
||||
Noindex: article.Noindex,
|
||||
SEODismissed: dismissed,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func toListItemResponse(article domain.Article, summary domain.SEOSummary, format domain.BodyFormat) (listItemResponse, error) {
|
||||
base, err := toBaseResponse(article, format)
|
||||
if err != nil {
|
||||
return listItemResponse{}, err
|
||||
}
|
||||
return listItemResponse{baseArticleResponse: base, Excerpt: article.Excerpt, Slug: article.Slug, SEOStatus: summary.Status, SEOSuggestions: summary.Suggestions}, nil
|
||||
}
|
||||
|
||||
func encodeArticle(article domain.Article, format domain.BodyFormat) ([]byte, error) {
|
||||
response, err := toArticleResponse(article, format)
|
||||
if err != nil {
|
||||
@@ -151,17 +223,21 @@ func (h *Handler) PostArticle(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
|
||||
creatorId, _ := claims.UserId(r)
|
||||
createdArticle, err := h.CreateUseCase.CreateArticle(r.Context(), useCases.CreateArticleCommand{
|
||||
Title: localArticle.Title,
|
||||
Body: localArticle.Body,
|
||||
Format: format,
|
||||
Title: localArticle.Title,
|
||||
Body: localArticle.Body,
|
||||
Format: format,
|
||||
CreatedBy: creatorId,
|
||||
})
|
||||
if err != nil {
|
||||
if errors.Is(err, domain.ErrInvalidTitle) {
|
||||
http.Error(w, apperr.ArticleTitleErrorMessage, http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
http.Error(w, "Failed to create article", http.StatusInternalServerError)
|
||||
if !writeKnownArticleError(w, err) {
|
||||
http.Error(w, "Failed to create article", http.StatusInternalServerError)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
@@ -169,11 +245,62 @@ func (h *Handler) PostArticle(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
|
||||
func writeArticleErrorResponse(w http.ResponseWriter, err error) {
|
||||
if !writeKnownArticleError(w, err) {
|
||||
http.Error(w, "Internal server error", http.StatusInternalServerError)
|
||||
}
|
||||
}
|
||||
|
||||
func writeKnownArticleError(w http.ResponseWriter, err error) bool {
|
||||
if errors.Is(err, domain.ErrArticleNotFound) {
|
||||
http.Error(w, apperr.ArticleNotFoundErrorMessage, http.StatusNotFound)
|
||||
return
|
||||
return true
|
||||
}
|
||||
http.Error(w, "Internal server error", http.StatusInternalServerError)
|
||||
if errors.Is(err, site.ErrSiteNotFound) {
|
||||
http.Error(w, apperr.SiteNotFoundErrorMessage, http.StatusNotFound)
|
||||
return true
|
||||
}
|
||||
if errors.Is(err, author.ErrAuthorNotFound) {
|
||||
http.Error(w, apperr.AuthorNotFoundErrorMessage, http.StatusNotFound)
|
||||
return true
|
||||
}
|
||||
if errors.Is(err, domain.ErrSlugTaken) {
|
||||
writeSlugTaken(w, err)
|
||||
return true
|
||||
}
|
||||
if errors.Is(err, domain.ErrInvalidSlug) {
|
||||
http.Error(w, apperr.InvalidSlugErrorMessage, http.StatusBadRequest)
|
||||
return true
|
||||
}
|
||||
if errors.Is(err, domain.ErrInvalidCanonicalURL) {
|
||||
http.Error(w, apperr.InvalidURLErrorMessage, http.StatusUnprocessableEntity)
|
||||
return true
|
||||
}
|
||||
if errors.Is(err, image.ErrImageNotFound) {
|
||||
http.Error(w, apperr.ArticleImageNotFoundErrorMessage, http.StatusBadRequest)
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func writeSlugTaken(w http.ResponseWriter, err error) {
|
||||
var conflict *domain.SlugTakenError
|
||||
if errors.As(err, &conflict) && conflict.Suggestion != "" {
|
||||
w.Header().Set(apperr.SlugSuggestionHeader, conflict.Suggestion)
|
||||
}
|
||||
http.Error(w, apperr.ArticleSlugTakenErrorMessage, http.StatusConflict)
|
||||
}
|
||||
|
||||
func writeValidationError(w http.ResponseWriter, err error) {
|
||||
var failures playground.ValidationErrors
|
||||
if errors.As(err, &failures) {
|
||||
for _, failure := range failures {
|
||||
if failure.Tag() == validator.ArticleSlugTag {
|
||||
http.Error(w, apperr.InvalidSlugErrorMessage, http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
http.Error(w, err.Error(), http.StatusBadRequest)
|
||||
}
|
||||
|
||||
func writeArticleJsonResponse(w http.ResponseWriter, status int, article domain.Article, format domain.BodyFormat) {
|
||||
@@ -212,8 +339,99 @@ func (h *Handler) setIsOnline(w http.ResponseWriter, r *http.Request, isOnline b
|
||||
writeArticleJsonResponse(w, http.StatusOK, updatedArticle, format)
|
||||
}
|
||||
|
||||
type optionalImageID struct {
|
||||
Set bool
|
||||
Value *uint32 `validate:"omitempty,gte=1"`
|
||||
}
|
||||
|
||||
func (o *optionalImageID) UnmarshalJSON(data []byte) error {
|
||||
o.Set = true
|
||||
if string(data) == "null" {
|
||||
o.Value = nil
|
||||
return nil
|
||||
}
|
||||
var value uint32
|
||||
if err := json.Unmarshal(data, &value); err != nil {
|
||||
return err
|
||||
}
|
||||
o.Value = &value
|
||||
return nil
|
||||
}
|
||||
|
||||
func (o optionalImageID) toNullable() domain.Nullable[uint32] {
|
||||
return domain.Nullable[uint32]{Set: o.Set, Value: o.Value}
|
||||
}
|
||||
|
||||
type UpdateArticleBody struct {
|
||||
Body string `json:"body"`
|
||||
Body *string `json:"body"`
|
||||
SiteID *uint32 `json:"site_id" validate:"omitempty,gte=1"`
|
||||
AuthorIDs *[]uint32 `json:"author_ids" validate:"omitempty,dive,gte=1"`
|
||||
Slug *string `json:"slug" validate:"omitempty,articleslug"`
|
||||
Excerpt *string `json:"excerpt" validate:"omitempty,max=300"`
|
||||
SEOTitle *string `json:"seo_title" validate:"omitempty,max=120"`
|
||||
SEODescription *string `json:"seo_description" validate:"omitempty,max=320"`
|
||||
CoverImageID optionalImageID `json:"cover_image_id"`
|
||||
CoverImageAlt *string `json:"cover_image_alt" validate:"omitempty,max=200"`
|
||||
SocialTitle *string `json:"social_title" validate:"omitempty,max=120"`
|
||||
SocialDescription *string `json:"social_description" validate:"omitempty,max=320"`
|
||||
SocialImageID optionalImageID `json:"social_image_id"`
|
||||
CanonicalURL *string `json:"canonical_url" validate:"omitempty,max=2048"`
|
||||
Noindex *bool `json:"noindex"`
|
||||
SEODismissed *[]string `json:"seo_dismissed" validate:"omitempty,dive,oneof=title_long title_empty desc_short desc_long cover_alt cover_none slug_long no_au no_h body_alt short"`
|
||||
}
|
||||
|
||||
var nonNullableArticleFields = []string{"body", "site_id", "author_ids", "slug", "excerpt", "seo_title", "seo_description", "cover_image_alt", "social_title", "social_description", "canonical_url", "noindex", "seo_dismissed"}
|
||||
|
||||
var nullableArticleFields = []string{"cover_image_id", "social_image_id"}
|
||||
|
||||
func hasDuplicates(ids []uint32) bool {
|
||||
seen := make(map[uint32]bool, len(ids))
|
||||
for _, id := range ids {
|
||||
if seen[id] {
|
||||
return true
|
||||
}
|
||||
seen[id] = true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func countKnownFields(fields map[string]json.RawMessage, nonNullable []string) (int, bool) {
|
||||
known := 0
|
||||
for name, value := range fields {
|
||||
switch {
|
||||
case slices.Contains(nonNullable, name):
|
||||
if string(value) == "null" {
|
||||
return 0, false
|
||||
}
|
||||
known++
|
||||
case slices.Contains(nullableArticleFields, name):
|
||||
known++
|
||||
}
|
||||
}
|
||||
return known, true
|
||||
}
|
||||
|
||||
func readUpdateArticleBody(r *http.Request) (UpdateArticleBody, bool) {
|
||||
raw, err := io.ReadAll(r.Body)
|
||||
if err != nil {
|
||||
return UpdateArticleBody{}, false
|
||||
}
|
||||
var fields map[string]json.RawMessage
|
||||
if err := json.Unmarshal(raw, &fields); err != nil {
|
||||
return UpdateArticleBody{}, false
|
||||
}
|
||||
known, ok := countKnownFields(fields, nonNullableArticleFields)
|
||||
if !ok || known == 0 {
|
||||
return UpdateArticleBody{}, false
|
||||
}
|
||||
var request UpdateArticleBody
|
||||
if err := json.Unmarshal(raw, &request); err != nil {
|
||||
return UpdateArticleBody{}, false
|
||||
}
|
||||
if request.AuthorIDs != nil && hasDuplicates(*request.AuthorIDs) {
|
||||
return UpdateArticleBody{}, false
|
||||
}
|
||||
return request, true
|
||||
}
|
||||
|
||||
func (h *Handler) UpdateArticleBody(w http.ResponseWriter, r *http.Request) {
|
||||
@@ -228,18 +446,35 @@ func (h *Handler) UpdateArticleBody(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
|
||||
var localArticle UpdateArticleBody
|
||||
if err := json.NewDecoder(r.Body).Decode(&localArticle); err != nil {
|
||||
request, ok := readUpdateArticleBody(r)
|
||||
if !ok {
|
||||
http.Error(w, apperr.BodyErrorMessage, http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
if err := validator.Validate.Struct(localArticle); err != nil {
|
||||
http.Error(w, err.Error(), http.StatusBadRequest)
|
||||
if err := validator.Validate.Struct(request); err != nil {
|
||||
writeValidationError(w, err)
|
||||
return
|
||||
}
|
||||
|
||||
updatedArticle, err := h.UpdateUseCase.UpdateBody(r.Context(), id, localArticle.Body, format)
|
||||
updatedArticle, err := h.UpdateUseCase.Update(r.Context(), id, useCases.UpdateArticleCommand{
|
||||
Body: request.Body,
|
||||
SiteID: request.SiteID,
|
||||
AuthorIDs: request.AuthorIDs,
|
||||
Slug: request.Slug,
|
||||
Excerpt: request.Excerpt,
|
||||
SEOTitle: request.SEOTitle,
|
||||
SEODescription: request.SEODescription,
|
||||
CoverImageID: request.CoverImageID.toNullable(),
|
||||
CoverImageAlt: request.CoverImageAlt,
|
||||
SocialTitle: request.SocialTitle,
|
||||
SocialDescription: request.SocialDescription,
|
||||
SocialImageID: request.SocialImageID.toNullable(),
|
||||
CanonicalURL: request.CanonicalURL,
|
||||
Noindex: request.Noindex,
|
||||
SEODismissed: request.SEODismissed,
|
||||
Format: format,
|
||||
})
|
||||
if err != nil {
|
||||
writeArticleErrorResponse(w, err)
|
||||
return
|
||||
@@ -257,12 +492,16 @@ func (h *Handler) UnpublishArticle(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
|
||||
func (h *Handler) callerIsVerified(r *http.Request) bool {
|
||||
return isVerifiedCaller(r, h.GetUserUseCase)
|
||||
}
|
||||
|
||||
func isVerifiedCaller(r *http.Request, getUser *useCases.GetUserUseCase) bool {
|
||||
userId, ok := claims.UserId(r)
|
||||
if !ok {
|
||||
return false
|
||||
}
|
||||
|
||||
currentUser, err := h.GetUserUseCase.GetUser(userId)
|
||||
currentUser, err := getUser.GetUser(userId)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
@@ -276,11 +515,13 @@ const (
|
||||
)
|
||||
|
||||
type listQuery struct {
|
||||
Page int `validate:"gte=1"`
|
||||
Size int `validate:"oneof=5 25 50 100"`
|
||||
Q string `validate:"max=200"`
|
||||
Status string `validate:"omitempty,oneof=online draft"`
|
||||
Sort string `validate:"oneof=title:asc title:desc status:asc status:desc created_at:asc created_at:desc updated_at:asc updated_at:desc"`
|
||||
Page int `validate:"gte=1"`
|
||||
Size int `validate:"oneof=5 25 50 100"`
|
||||
Q string `validate:"max=200"`
|
||||
Status string `validate:"omitempty,oneof=online draft"`
|
||||
Site *string `validate:"omitempty,min=1"`
|
||||
SEO string `validate:"omitempty,oneof=ready suggestions hidden"`
|
||||
Sort string `validate:"oneof=title:asc title:desc status:asc status:desc created_at:asc created_at:desc updated_at:asc updated_at:desc"`
|
||||
}
|
||||
|
||||
const defaultListSort = "updated_at:desc"
|
||||
@@ -291,11 +532,11 @@ func parseSort(value string) domain.Sort {
|
||||
}
|
||||
|
||||
type listResponse struct {
|
||||
Items []articleResponse `json:"items"`
|
||||
Total int `json:"total"`
|
||||
Page int `json:"page"`
|
||||
Size int `json:"size"`
|
||||
Counts domain.Counts `json:"counts"`
|
||||
Items []listItemResponse `json:"items"`
|
||||
Total int `json:"total"`
|
||||
Page int `json:"page"`
|
||||
Size int `json:"size"`
|
||||
Counts domain.Counts `json:"counts"`
|
||||
}
|
||||
|
||||
func intQueryParam(values url.Values, name string, fallback int) (int, error) {
|
||||
@@ -322,7 +563,19 @@ func readListQuery(values url.Values) (listQuery, error) {
|
||||
if values.Has("sort") {
|
||||
sortValue = values.Get("sort")
|
||||
}
|
||||
return listQuery{Page: page, Size: size, Q: values.Get("q"), Status: status, Sort: sortValue}, nil
|
||||
var siteKey *string
|
||||
if values.Has("site") {
|
||||
key := values.Get("site")
|
||||
if key == "" {
|
||||
return listQuery{}, errors.New("empty site")
|
||||
}
|
||||
siteKey = &key
|
||||
}
|
||||
seoStatus := values.Get("seo")
|
||||
if values.Has("seo") && seoStatus == "" {
|
||||
return listQuery{}, errors.New("empty seo")
|
||||
}
|
||||
return listQuery{Page: page, Size: size, Q: values.Get("q"), Status: status, Sort: sortValue, Site: siteKey, SEO: seoStatus}, nil
|
||||
}
|
||||
|
||||
func (h *Handler) ListArticles(w http.ResponseWriter, r *http.Request) {
|
||||
@@ -345,15 +598,17 @@ func (h *Handler) ListArticles(w http.ResponseWriter, r *http.Request) {
|
||||
Q: query.Q,
|
||||
Status: query.Status,
|
||||
Sort: parseSort(query.Sort),
|
||||
SiteKey: query.Site,
|
||||
SEO: query.SEO,
|
||||
})
|
||||
if err != nil {
|
||||
http.Error(w, "Failed to retrieve articles", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
responses := make([]articleResponse, 0, len(page.Items))
|
||||
responses := make([]listItemResponse, 0, len(page.Items))
|
||||
for _, article := range page.Items {
|
||||
response, err := toArticleResponse(article, format)
|
||||
response, err := toListItemResponse(article, page.SEO[article.ID], format)
|
||||
if err != nil {
|
||||
http.Error(w, "Failed to encode response", http.StatusInternalServerError)
|
||||
return
|
||||
|
||||
@@ -0,0 +1,127 @@
|
||||
package article
|
||||
|
||||
import (
|
||||
"RenewCMS/api/pkg/apperr"
|
||||
validator "RenewCMS/api/pkg/validator"
|
||||
"RenewCMS/internal/infrastructure/useCases"
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"log"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
type SEOHandler struct {
|
||||
ResolveUseCase *useCases.ResolveArticleSEOUseCase
|
||||
CheckUseCase *useCases.CheckArticleSEOUseCase
|
||||
GetUserUseCase *useCases.GetUserUseCase
|
||||
}
|
||||
|
||||
func NewSEOHandler(resolve *useCases.ResolveArticleSEOUseCase, check *useCases.CheckArticleSEOUseCase, getUser *useCases.GetUserUseCase) *SEOHandler {
|
||||
return &SEOHandler{ResolveUseCase: resolve, CheckUseCase: check, GetUserUseCase: getUser}
|
||||
}
|
||||
|
||||
type CheckArticleSEOBody struct {
|
||||
Body *string `json:"body"`
|
||||
Slug *string `json:"slug" validate:"omitempty,articleslug"`
|
||||
Excerpt *string `json:"excerpt" validate:"omitempty,max=300"`
|
||||
SEOTitle *string `json:"seo_title" validate:"omitempty,max=120"`
|
||||
SEODescription *string `json:"seo_description" validate:"omitempty,max=320"`
|
||||
CoverImageID optionalImageID `json:"cover_image_id"`
|
||||
CoverImageAlt *string `json:"cover_image_alt" validate:"omitempty,max=200"`
|
||||
SocialTitle *string `json:"social_title" validate:"omitempty,max=120"`
|
||||
SocialDescription *string `json:"social_description" validate:"omitempty,max=320"`
|
||||
SocialImageID optionalImageID `json:"social_image_id"`
|
||||
CanonicalURL *string `json:"canonical_url" validate:"omitempty,max=2048"`
|
||||
Noindex *bool `json:"noindex"`
|
||||
SEODismissed *[]string `json:"seo_dismissed" validate:"omitempty,dive,oneof=title_long title_empty desc_short desc_long cover_alt cover_none slug_long no_au no_h body_alt short"`
|
||||
}
|
||||
|
||||
var checkNonNullableFields = []string{"body", "slug", "excerpt", "seo_title", "seo_description", "cover_image_alt", "social_title", "social_description", "canonical_url", "noindex", "seo_dismissed"}
|
||||
|
||||
func readCheckBody(r *http.Request) (CheckArticleSEOBody, bool) {
|
||||
raw, err := io.ReadAll(r.Body)
|
||||
if err != nil {
|
||||
return CheckArticleSEOBody{}, false
|
||||
}
|
||||
var fields map[string]json.RawMessage
|
||||
if err := json.Unmarshal(raw, &fields); err != nil || fields == nil {
|
||||
return CheckArticleSEOBody{}, false
|
||||
}
|
||||
known, ok := countKnownFields(fields, checkNonNullableFields)
|
||||
if !ok || known != len(fields) {
|
||||
return CheckArticleSEOBody{}, false
|
||||
}
|
||||
var request CheckArticleSEOBody
|
||||
decoder := json.NewDecoder(bytes.NewReader(raw))
|
||||
decoder.DisallowUnknownFields()
|
||||
if err := decoder.Decode(&request); err != nil {
|
||||
return CheckArticleSEOBody{}, false
|
||||
}
|
||||
return request, true
|
||||
}
|
||||
|
||||
func (h *SEOHandler) Resolve(w http.ResponseWriter, r *http.Request) {
|
||||
id, err := parseArticleId(r)
|
||||
if err != nil {
|
||||
http.Error(w, apperr.IdUint32ErrorMessage, http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
resolved, err := h.ResolveUseCase.Resolve(id, isVerifiedCaller(r, h.GetUserUseCase))
|
||||
if err != nil {
|
||||
writeArticleErrorResponse(w, err)
|
||||
return
|
||||
}
|
||||
writeSEOJson(w, resolved)
|
||||
}
|
||||
|
||||
func (h *SEOHandler) Check(w http.ResponseWriter, r *http.Request) {
|
||||
id, err := parseArticleId(r)
|
||||
if err != nil {
|
||||
http.Error(w, apperr.IdUint32ErrorMessage, http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
request, ok := readCheckBody(r)
|
||||
if !ok {
|
||||
http.Error(w, apperr.BodyErrorMessage, http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
if err := validator.Validate.Struct(request); err != nil {
|
||||
writeValidationError(w, err)
|
||||
return
|
||||
}
|
||||
|
||||
checked, err := h.CheckUseCase.Check(id, useCases.CheckArticleSEOCommand{
|
||||
Body: request.Body,
|
||||
Slug: request.Slug,
|
||||
Excerpt: request.Excerpt,
|
||||
SEOTitle: request.SEOTitle,
|
||||
SEODescription: request.SEODescription,
|
||||
CoverImageID: request.CoverImageID.toNullable(),
|
||||
CoverImageAlt: request.CoverImageAlt,
|
||||
SocialTitle: request.SocialTitle,
|
||||
SocialDescription: request.SocialDescription,
|
||||
SocialImageID: request.SocialImageID.toNullable(),
|
||||
CanonicalURL: request.CanonicalURL,
|
||||
Noindex: request.Noindex,
|
||||
SEODismissed: request.SEODismissed,
|
||||
})
|
||||
if err != nil {
|
||||
writeArticleErrorResponse(w, err)
|
||||
return
|
||||
}
|
||||
writeSEOJson(w, checked)
|
||||
}
|
||||
|
||||
func writeSEOJson(w http.ResponseWriter, payload any) {
|
||||
encoded, err := json.Marshal(payload)
|
||||
if err != nil {
|
||||
http.Error(w, "Failed to encode response", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
if _, err := w.Write(encoded); err != nil {
|
||||
log.Printf("Failed to write response: %v", err)
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"RenewCMS/api/pkg/apperr"
|
||||
"RenewCMS/api/pkg/claims"
|
||||
"RenewCMS/api/pkg/publicuser"
|
||||
"RenewCMS/internal/domain/author"
|
||||
"RenewCMS/internal/domain/user"
|
||||
"RenewCMS/internal/infrastructure/useCases"
|
||||
"encoding/json"
|
||||
@@ -12,15 +13,34 @@ import (
|
||||
)
|
||||
|
||||
type MeHandler struct {
|
||||
GetUseCase *useCases.GetUserUseCase
|
||||
GetUseCase *useCases.GetUserUseCase
|
||||
GetAuthorUseCase *useCases.GetMyAuthorUseCase
|
||||
}
|
||||
|
||||
func NewMeHandler(getUser *useCases.GetUserUseCase) *MeHandler {
|
||||
func NewMeHandler(getUser *useCases.GetUserUseCase, getAuthor *useCases.GetMyAuthorUseCase) *MeHandler {
|
||||
return &MeHandler{
|
||||
GetUseCase: getUser,
|
||||
GetUseCase: getUser,
|
||||
GetAuthorUseCase: getAuthor,
|
||||
}
|
||||
}
|
||||
|
||||
type meAuthor struct {
|
||||
author.Byline
|
||||
ArticleCount int `json:"article_count"`
|
||||
}
|
||||
|
||||
type meResponse struct {
|
||||
publicuser.PublicUser
|
||||
Author *meAuthor `json:"author"`
|
||||
}
|
||||
|
||||
func toMeAuthor(found *author.Author) *meAuthor {
|
||||
if found == nil {
|
||||
return nil
|
||||
}
|
||||
return &meAuthor{Byline: found.Byline(), ArticleCount: found.ArticleCount}
|
||||
}
|
||||
|
||||
func (h *MeHandler) Me(w http.ResponseWriter, r *http.Request) {
|
||||
userId, ok := claims.UserId(r)
|
||||
if !ok {
|
||||
@@ -38,7 +58,13 @@ func (h *MeHandler) Me(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
|
||||
body, err := json.Marshal(publicuser.New(loadedUser))
|
||||
linked, err := h.GetAuthorUseCase.Get(loadedUser.ID)
|
||||
if err != nil {
|
||||
http.Error(w, "Internal server error", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
body, err := json.Marshal(meResponse{PublicUser: publicuser.New(loadedUser), Author: toMeAuthor(linked)})
|
||||
if err != nil {
|
||||
http.Error(w, "Internal server error", http.StatusInternalServerError)
|
||||
return
|
||||
|
||||
@@ -0,0 +1,395 @@
|
||||
package author
|
||||
|
||||
import (
|
||||
"RenewCMS/api/pkg/apperr"
|
||||
"RenewCMS/api/pkg/claims"
|
||||
validator "RenewCMS/api/pkg/validator"
|
||||
domain "RenewCMS/internal/domain/author"
|
||||
"RenewCMS/internal/domain/image"
|
||||
"RenewCMS/internal/domain/user"
|
||||
"RenewCMS/internal/infrastructure/useCases"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"log"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strconv"
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
playground "github.com/go-playground/validator/v10"
|
||||
)
|
||||
|
||||
const (
|
||||
defaultListPage = 1
|
||||
defaultListSize = 25
|
||||
reassignParam = "reassign_to"
|
||||
reassignNone = "none"
|
||||
)
|
||||
|
||||
type Handler struct {
|
||||
ListUseCase *useCases.ListAuthorsUseCase
|
||||
CreateUseCase *useCases.CreateAuthorUseCase
|
||||
CreateMyUseCase *useCases.CreateMyAuthorUseCase
|
||||
UpdateUseCase *useCases.UpdateAuthorUseCase
|
||||
DeleteUseCase *useCases.DeleteAuthorUseCase
|
||||
GetUserUseCase *useCases.GetUserUseCase
|
||||
}
|
||||
|
||||
func NewHandler(list *useCases.ListAuthorsUseCase, create *useCases.CreateAuthorUseCase, createMy *useCases.CreateMyAuthorUseCase, update *useCases.UpdateAuthorUseCase, deleteUseCase *useCases.DeleteAuthorUseCase, getUser *useCases.GetUserUseCase) *Handler {
|
||||
return &Handler{ListUseCase: list, CreateUseCase: create, CreateMyUseCase: createMy, UpdateUseCase: update, DeleteUseCase: deleteUseCase, GetUserUseCase: getUser}
|
||||
}
|
||||
|
||||
type socialLinkRequest struct {
|
||||
Type string `json:"type" validate:"socialtype"`
|
||||
URL string `json:"url"`
|
||||
}
|
||||
|
||||
func toLinks(requests []socialLinkRequest) []domain.SocialLink {
|
||||
links := make([]domain.SocialLink, 0, len(requests))
|
||||
for _, request := range requests {
|
||||
links = append(links, domain.SocialLink{Type: request.Type, URL: request.URL})
|
||||
}
|
||||
return links
|
||||
}
|
||||
|
||||
type PostAuthor struct {
|
||||
Name string `json:"name" validate:"authorname"`
|
||||
Slug string `json:"slug" validate:"omitempty,authorslug"`
|
||||
Bio string `json:"bio"`
|
||||
AvatarID *uint32 `json:"avatar_id" validate:"omitempty,gte=1"`
|
||||
Website *string `json:"website"`
|
||||
SocialLinks []socialLinkRequest `json:"social_links" validate:"omitempty,dive"`
|
||||
UserID *uint32 `json:"user_id" validate:"omitempty,gte=1"`
|
||||
}
|
||||
|
||||
type optional[T any] struct {
|
||||
Set bool
|
||||
Value *T
|
||||
}
|
||||
|
||||
func (o *optional[T]) UnmarshalJSON(data []byte) error {
|
||||
o.Set = true
|
||||
if string(data) == "null" {
|
||||
o.Value = nil
|
||||
return nil
|
||||
}
|
||||
var value T
|
||||
if err := json.Unmarshal(data, &value); err != nil {
|
||||
return err
|
||||
}
|
||||
o.Value = &value
|
||||
return nil
|
||||
}
|
||||
|
||||
type PatchAuthor struct {
|
||||
Name *string `json:"name" validate:"authorname"`
|
||||
Slug *string `json:"slug" validate:"authorslug"`
|
||||
Bio *string `json:"bio"`
|
||||
AvatarID optional[uint32] `json:"avatar_id"`
|
||||
Website optional[string] `json:"website"`
|
||||
SocialLinks *[]socialLinkRequest `json:"social_links" validate:"omitempty,dive"`
|
||||
UserID optional[uint32] `json:"user_id"`
|
||||
}
|
||||
|
||||
func (p PatchAuthor) toPatch() domain.Patch {
|
||||
patch := domain.Patch{
|
||||
Name: p.Name,
|
||||
Slug: p.Slug,
|
||||
Bio: p.Bio,
|
||||
AvatarID: domain.Nullable[uint32]{Set: p.AvatarID.Set, Value: p.AvatarID.Value},
|
||||
Website: domain.Nullable[string]{Set: p.Website.Set, Value: p.Website.Value},
|
||||
UserID: domain.Nullable[uint32]{Set: p.UserID.Set, Value: p.UserID.Value},
|
||||
}
|
||||
if p.SocialLinks != nil {
|
||||
links := toLinks(*p.SocialLinks)
|
||||
patch.SocialLinks = &links
|
||||
}
|
||||
return patch
|
||||
}
|
||||
|
||||
var requiredNonNullFields = []string{"name", "slug", "bio", "social_links"}
|
||||
|
||||
var nullableFields = []string{"avatar_id", "website", "user_id"}
|
||||
|
||||
func readPatchAuthor(r *http.Request) (PatchAuthor, bool) {
|
||||
raw, err := io.ReadAll(r.Body)
|
||||
if err != nil {
|
||||
return PatchAuthor{}, false
|
||||
}
|
||||
var fields map[string]json.RawMessage
|
||||
if err := json.Unmarshal(raw, &fields); err != nil {
|
||||
return PatchAuthor{}, false
|
||||
}
|
||||
known := false
|
||||
for _, name := range requiredNonNullFields {
|
||||
value, present := fields[name]
|
||||
if !present {
|
||||
continue
|
||||
}
|
||||
if string(value) == "null" {
|
||||
return PatchAuthor{}, false
|
||||
}
|
||||
known = true
|
||||
}
|
||||
for _, name := range nullableFields {
|
||||
if _, present := fields[name]; present {
|
||||
known = true
|
||||
}
|
||||
}
|
||||
if !known {
|
||||
return PatchAuthor{}, false
|
||||
}
|
||||
var request PatchAuthor
|
||||
if err := json.Unmarshal(raw, &request); err != nil {
|
||||
return PatchAuthor{}, false
|
||||
}
|
||||
return request, true
|
||||
}
|
||||
|
||||
func parseAuthorId(r *http.Request) (uint32, error) {
|
||||
id, err := strconv.ParseUint(chi.URLParam(r, "id"), 10, 32)
|
||||
return uint32(id), err
|
||||
}
|
||||
|
||||
type ownAuthorResponse struct {
|
||||
domain.Author
|
||||
SlugAdjusted bool `json:"slug_adjusted"`
|
||||
}
|
||||
|
||||
func presentAuthor(a domain.Author) domain.Author {
|
||||
if a.SocialLinks == nil {
|
||||
a.SocialLinks = []domain.SocialLink{}
|
||||
}
|
||||
return a
|
||||
}
|
||||
|
||||
func writeJSON(w http.ResponseWriter, status int, payload any) {
|
||||
body, err := json.Marshal(payload)
|
||||
if err != nil {
|
||||
http.Error(w, "Failed to encode response", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
if status != http.StatusOK {
|
||||
w.WriteHeader(status)
|
||||
}
|
||||
if _, err := w.Write(body); err != nil {
|
||||
log.Printf("Failed to write response: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func writeAuthorError(w http.ResponseWriter, err error) {
|
||||
switch {
|
||||
case errors.Is(err, domain.ErrAuthorNotFound):
|
||||
http.Error(w, apperr.AuthorNotFoundErrorMessage, http.StatusNotFound)
|
||||
case errors.Is(err, domain.ErrSlugTaken):
|
||||
http.Error(w, apperr.AuthorSlugTakenErrorMessage, http.StatusConflict)
|
||||
case errors.Is(err, domain.ErrAuthorHasArticles):
|
||||
http.Error(w, apperr.AuthorHasArticlesErrorMessage, http.StatusConflict)
|
||||
case errors.Is(err, domain.ErrUserAlreadyLinked):
|
||||
http.Error(w, apperr.UserAlreadyLinkedErrorMessage, http.StatusConflict)
|
||||
case errors.Is(err, domain.ErrAuthorAlreadyLinked):
|
||||
http.Error(w, apperr.AuthorAlreadyLinkedErrorMessage, http.StatusConflict)
|
||||
case errors.Is(err, user.ErrUserNotFound):
|
||||
http.Error(w, apperr.UserNotFoundErrorMessage, http.StatusNotFound)
|
||||
case errors.Is(err, domain.ErrAuthorRights):
|
||||
http.Error(w, apperr.AuthorRightsErrorMessage, http.StatusForbidden)
|
||||
case errors.Is(err, domain.ErrBioTooLong):
|
||||
http.Error(w, apperr.BioTooLongErrorMessage, http.StatusUnprocessableEntity)
|
||||
case errors.Is(err, domain.ErrInvalidURL):
|
||||
http.Error(w, apperr.InvalidURLErrorMessage, http.StatusUnprocessableEntity)
|
||||
case errors.Is(err, domain.ErrTooManyLinks):
|
||||
http.Error(w, apperr.TooManyLinksErrorMessage, http.StatusUnprocessableEntity)
|
||||
case errors.Is(err, domain.ErrInvalidSocialType):
|
||||
http.Error(w, apperr.InvalidSocialTypeErrorMessage, http.StatusBadRequest)
|
||||
case errors.Is(err, domain.ErrInvalidSlug):
|
||||
http.Error(w, apperr.InvalidSlugErrorMessage, http.StatusBadRequest)
|
||||
case errors.Is(err, domain.ErrInvalidReassign):
|
||||
http.Error(w, apperr.InvalidReassignErrorMessage, http.StatusBadRequest)
|
||||
case errors.Is(err, image.ErrImageNotFound):
|
||||
http.Error(w, apperr.AuthorImageNotFoundErrorMessage, http.StatusBadRequest)
|
||||
default:
|
||||
http.Error(w, "Internal server error", http.StatusInternalServerError)
|
||||
}
|
||||
}
|
||||
|
||||
func writeValidationError(w http.ResponseWriter, err error) {
|
||||
var failures playground.ValidationErrors
|
||||
if errors.As(err, &failures) {
|
||||
for _, failure := range failures {
|
||||
if failure.Tag() == validator.AuthorSlugTag {
|
||||
http.Error(w, apperr.InvalidSlugErrorMessage, http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
http.Error(w, err.Error(), http.StatusBadRequest)
|
||||
}
|
||||
|
||||
func (h *Handler) currentUser(r *http.Request) (user.User, bool) {
|
||||
userId, ok := claims.UserId(r)
|
||||
if !ok {
|
||||
return user.User{}, false
|
||||
}
|
||||
current, err := h.GetUserUseCase.GetUser(userId)
|
||||
if err != nil {
|
||||
return user.User{}, false
|
||||
}
|
||||
return current, true
|
||||
}
|
||||
|
||||
type listQuery struct {
|
||||
Page int `validate:"gte=1"`
|
||||
Size int `validate:"oneof=5 25 50 100"`
|
||||
Q string `validate:"max=200"`
|
||||
}
|
||||
|
||||
type listResponse struct {
|
||||
Items []domain.Author `json:"items"`
|
||||
Total int `json:"total"`
|
||||
Page int `json:"page"`
|
||||
Size int `json:"size"`
|
||||
}
|
||||
|
||||
func intQueryParam(values url.Values, name string, fallback int) (int, error) {
|
||||
if !values.Has(name) {
|
||||
return fallback, nil
|
||||
}
|
||||
return strconv.Atoi(values.Get(name))
|
||||
}
|
||||
|
||||
func readListQuery(values url.Values) (listQuery, error) {
|
||||
page, err := intQueryParam(values, "page", defaultListPage)
|
||||
if err != nil {
|
||||
return listQuery{}, err
|
||||
}
|
||||
size, err := intQueryParam(values, "size", defaultListSize)
|
||||
if err != nil {
|
||||
return listQuery{}, err
|
||||
}
|
||||
return listQuery{Page: page, Size: size, Q: values.Get("q")}, nil
|
||||
}
|
||||
|
||||
func (h *Handler) List(w http.ResponseWriter, r *http.Request) {
|
||||
query, err := readListQuery(r.URL.Query())
|
||||
if err != nil || validator.Validate.Struct(query) != nil {
|
||||
http.Error(w, apperr.BodyErrorMessage, http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
current, _ := h.currentUser(r)
|
||||
page, err := h.ListUseCase.List(useCases.ListAuthorsCommand{Q: query.Q, Page: query.Page, Size: query.Size, CallerRole: current.Role})
|
||||
if err != nil {
|
||||
http.Error(w, "Internal server error", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
items := make([]domain.Author, 0, len(page.Items))
|
||||
for _, item := range page.Items {
|
||||
items = append(items, presentAuthor(item))
|
||||
}
|
||||
w.Header().Set("X-Total-Count", strconv.Itoa(page.Total))
|
||||
writeJSON(w, http.StatusOK, listResponse{Items: items, Total: page.Total, Page: page.Page, Size: page.Size})
|
||||
}
|
||||
|
||||
func (h *Handler) Create(w http.ResponseWriter, r *http.Request) {
|
||||
var request PostAuthor
|
||||
if err := json.NewDecoder(r.Body).Decode(&request); err != nil {
|
||||
http.Error(w, apperr.BodyErrorMessage, http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
if err := validator.Validate.Struct(request); err != nil {
|
||||
writeValidationError(w, err)
|
||||
return
|
||||
}
|
||||
|
||||
created, err := h.CreateUseCase.Create(r.Context(), useCases.CreateAuthorCommand{
|
||||
Name: request.Name,
|
||||
Slug: request.Slug,
|
||||
Bio: request.Bio,
|
||||
AvatarID: request.AvatarID,
|
||||
Website: request.Website,
|
||||
SocialLinks: toLinks(request.SocialLinks),
|
||||
UserID: request.UserID,
|
||||
})
|
||||
if err != nil {
|
||||
writeAuthorError(w, err)
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusCreated, presentAuthor(created))
|
||||
}
|
||||
|
||||
func (h *Handler) CreateMine(w http.ResponseWriter, r *http.Request) {
|
||||
userId, ok := claims.UserId(r)
|
||||
if !ok {
|
||||
http.Error(w, apperr.UnauthorizedErrorMessage, http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
|
||||
created, err := h.CreateMyUseCase.Create(r.Context(), userId)
|
||||
if err != nil {
|
||||
writeAuthorError(w, err)
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusCreated, ownAuthorResponse{Author: presentAuthor(created.Author), SlugAdjusted: created.SlugAdjusted})
|
||||
}
|
||||
|
||||
func (h *Handler) Update(w http.ResponseWriter, r *http.Request) {
|
||||
id, err := parseAuthorId(r)
|
||||
if err != nil {
|
||||
http.Error(w, apperr.IdUint32ErrorMessage, http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
request, ok := readPatchAuthor(r)
|
||||
if !ok {
|
||||
http.Error(w, apperr.BodyErrorMessage, http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
if err := validator.Validate.Struct(request); err != nil {
|
||||
writeValidationError(w, err)
|
||||
return
|
||||
}
|
||||
|
||||
current, ok := h.currentUser(r)
|
||||
if !ok {
|
||||
http.Error(w, apperr.UnauthorizedErrorMessage, http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
updated, err := h.UpdateUseCase.Update(r.Context(), id, useCases.AuthorCaller{UserID: current.ID, Role: current.Role}, request.toPatch())
|
||||
if err != nil {
|
||||
writeAuthorError(w, err)
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, presentAuthor(updated))
|
||||
}
|
||||
|
||||
func readReassignment(r *http.Request) useCases.Reassignment {
|
||||
query := r.URL.Query()
|
||||
if !query.Has(reassignParam) {
|
||||
return useCases.Reassignment{Mode: useCases.ReassignAbsent}
|
||||
}
|
||||
value := query.Get(reassignParam)
|
||||
if value == reassignNone {
|
||||
return useCases.Reassignment{Mode: useCases.ReassignNone}
|
||||
}
|
||||
parsed, err := strconv.ParseUint(value, 10, 32)
|
||||
if err != nil {
|
||||
return useCases.Reassignment{Mode: useCases.ReassignMalformed}
|
||||
}
|
||||
return useCases.Reassignment{Mode: useCases.ReassignToAuthor, Destination: uint32(parsed)}
|
||||
}
|
||||
|
||||
func (h *Handler) Delete(w http.ResponseWriter, r *http.Request) {
|
||||
id, err := parseAuthorId(r)
|
||||
if err != nil {
|
||||
http.Error(w, apperr.IdUint32ErrorMessage, http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
if err := h.DeleteUseCase.Delete(r.Context(), id, readReassignment(r)); err != nil {
|
||||
writeAuthorError(w, err)
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
@@ -90,13 +90,17 @@ func intQueryParam(values url.Values, name string, fallback int) (int, error) {
|
||||
}
|
||||
|
||||
type usageResponse struct {
|
||||
ID uint32 `json:"id"`
|
||||
Title string `json:"title"`
|
||||
Published bool `json:"published"`
|
||||
Type string `json:"type"`
|
||||
ID uint32 `json:"id"`
|
||||
Title string `json:"title"`
|
||||
Published *bool `json:"published,omitempty"`
|
||||
Fields []string `json:"fields"`
|
||||
}
|
||||
|
||||
type mergeResponse struct {
|
||||
ArticlesUpdated int `json:"articles_updated"`
|
||||
SitesUpdated int `json:"sites_updated"`
|
||||
AuthorsUpdated int `json:"authors_updated"`
|
||||
Merged int `json:"merged"`
|
||||
}
|
||||
|
||||
@@ -246,6 +250,19 @@ func (h *Handler) List(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSON(w, http.StatusOK, response)
|
||||
}
|
||||
|
||||
func (h *Handler) Get(w http.ResponseWriter, r *http.Request) {
|
||||
id, ok := parseImageId(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
item, err := h.ListUseCase.Get(id)
|
||||
if err != nil {
|
||||
writeImageError(w, err)
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, toResponse(item))
|
||||
}
|
||||
|
||||
func (h *Handler) Upload(w http.ResponseWriter, r *http.Request) {
|
||||
userId, _ := claims.UserId(r)
|
||||
input, closeFile, ok := upload.ReadImageInput(w, r, userId)
|
||||
@@ -322,15 +339,15 @@ func (h *Handler) Usage(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
|
||||
articles, err := h.UsageUseCase.Usage(id)
|
||||
usages, err := h.UsageUseCase.Usage(id)
|
||||
if err != nil {
|
||||
writeImageError(w, err)
|
||||
return
|
||||
}
|
||||
|
||||
response := make([]usageResponse, 0, len(articles))
|
||||
for _, a := range articles {
|
||||
response = append(response, usageResponse{ID: a.ID, Title: a.Title, Published: a.IsOnline})
|
||||
response := make([]usageResponse, 0, len(usages))
|
||||
for _, usage := range usages {
|
||||
response = append(response, usageResponse{Type: usage.Type, ID: usage.ID, Title: usage.Title, Published: usage.Published, Fields: usage.Fields})
|
||||
}
|
||||
writeJSON(w, http.StatusOK, response)
|
||||
}
|
||||
@@ -352,7 +369,7 @@ func (h *Handler) Merge(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
|
||||
writeJSON(w, http.StatusOK, mergeResponse{ArticlesUpdated: result.ArticlesUpdated, Merged: result.Merged})
|
||||
writeJSON(w, http.StatusOK, mergeResponse{ArticlesUpdated: result.ArticlesUpdated, SitesUpdated: result.SitesUpdated, AuthorsUpdated: result.AuthorsUpdated, Merged: result.Merged})
|
||||
}
|
||||
|
||||
func writeMergeError(w http.ResponseWriter, err error) {
|
||||
|
||||
@@ -53,6 +53,8 @@ type purgeRunResponse struct {
|
||||
GroupsPurged int `json:"groups_purged"`
|
||||
Merged int `json:"merged"`
|
||||
ArticlesUpdated int `json:"articles_updated"`
|
||||
SitesUpdated int `json:"sites_updated"`
|
||||
AuthorsUpdated int `json:"authors_updated"`
|
||||
FailedGroups int `json:"failed_groups"`
|
||||
}
|
||||
|
||||
@@ -164,6 +166,8 @@ func (h *Handler) RunPurge(w http.ResponseWriter, r *http.Request) {
|
||||
GroupsPurged: result.GroupsPurged,
|
||||
Merged: result.Merged,
|
||||
ArticlesUpdated: result.ArticlesUpdated,
|
||||
SitesUpdated: result.SitesUpdated,
|
||||
AuthorsUpdated: result.AuthorsUpdated,
|
||||
FailedGroups: result.FailedGroups,
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,296 @@
|
||||
package site
|
||||
|
||||
import (
|
||||
"RenewCMS/api/pkg/apperr"
|
||||
validator "RenewCMS/api/pkg/validator"
|
||||
"RenewCMS/internal/domain/image"
|
||||
domain "RenewCMS/internal/domain/site"
|
||||
"RenewCMS/internal/infrastructure/useCases"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"log"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strconv"
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
)
|
||||
|
||||
type Handler struct {
|
||||
ListUseCase *useCases.ListSitesUseCase
|
||||
CreateUseCase *useCases.CreateSiteUseCase
|
||||
UpdateUseCase *useCases.UpdateSiteUseCase
|
||||
SetDefaultUseCase *useCases.SetDefaultSiteUseCase
|
||||
DeleteUseCase *useCases.DeleteSiteUseCase
|
||||
}
|
||||
|
||||
func NewHandler(list *useCases.ListSitesUseCase, create *useCases.CreateSiteUseCase, update *useCases.UpdateSiteUseCase, setDefault *useCases.SetDefaultSiteUseCase, deleteUseCase *useCases.DeleteSiteUseCase) *Handler {
|
||||
return &Handler{ListUseCase: list, CreateUseCase: create, UpdateUseCase: update, SetDefaultUseCase: setDefault, DeleteUseCase: deleteUseCase}
|
||||
}
|
||||
|
||||
type PostSite struct {
|
||||
Name string `json:"name" validate:"required,sitename"`
|
||||
Key string `json:"key" validate:"required,sitekey"`
|
||||
BaseURL string `json:"base_url" validate:"required"`
|
||||
DefaultRobots string `json:"default_robots" validate:"omitempty,oneof=index noindex"`
|
||||
Locale *string `json:"locale"`
|
||||
DefaultSocialImageID *uint32 `json:"default_social_image_id"`
|
||||
IsDefault bool `json:"is_default"`
|
||||
SiteName string `json:"site_name" validate:"max=100"`
|
||||
TitleTemplate *string `json:"title_template" validate:"omitempty,max=200"`
|
||||
DefaultDescription string `json:"default_description" validate:"max=320"`
|
||||
}
|
||||
|
||||
type optional[T any] struct {
|
||||
Set bool
|
||||
Value *T
|
||||
}
|
||||
|
||||
func (o *optional[T]) UnmarshalJSON(data []byte) error {
|
||||
o.Set = true
|
||||
if string(data) == "null" {
|
||||
o.Value = nil
|
||||
return nil
|
||||
}
|
||||
var value T
|
||||
if err := json.Unmarshal(data, &value); err != nil {
|
||||
return err
|
||||
}
|
||||
o.Value = &value
|
||||
return nil
|
||||
}
|
||||
|
||||
type PatchSite struct {
|
||||
Name *string `json:"name" validate:"omitempty,sitename"`
|
||||
Key *string `json:"key" validate:"omitempty,sitekey"`
|
||||
BaseURL *string `json:"base_url"`
|
||||
DefaultRobots *string `json:"default_robots" validate:"omitempty,oneof=index noindex"`
|
||||
Locale optional[string] `json:"locale"`
|
||||
DefaultSocialImageID optional[uint32] `json:"default_social_image_id"`
|
||||
IsDefault *bool `json:"is_default"`
|
||||
SiteName *string `json:"site_name" validate:"omitempty,max=100"`
|
||||
TitleTemplate *string `json:"title_template" validate:"omitempty,max=200"`
|
||||
DefaultDescription *string `json:"default_description" validate:"omitempty,max=320"`
|
||||
}
|
||||
|
||||
func (p PatchSite) toPatch() domain.Patch {
|
||||
return domain.Patch{
|
||||
Name: p.Name,
|
||||
Key: p.Key,
|
||||
BaseURL: p.BaseURL,
|
||||
DefaultRobots: p.DefaultRobots,
|
||||
Locale: domain.Nullable[string]{Set: p.Locale.Set, Value: p.Locale.Value},
|
||||
DefaultSocialImageID: domain.Nullable[uint32]{Set: p.DefaultSocialImageID.Set, Value: p.DefaultSocialImageID.Value},
|
||||
IsDefault: p.IsDefault,
|
||||
SiteName: p.SiteName,
|
||||
TitleTemplate: p.TitleTemplate,
|
||||
DefaultDescription: p.DefaultDescription,
|
||||
}
|
||||
}
|
||||
|
||||
func parseSiteId(r *http.Request) (uint32, error) {
|
||||
id, err := strconv.ParseUint(chi.URLParam(r, "id"), 10, 32)
|
||||
return uint32(id), err
|
||||
}
|
||||
|
||||
func writeSite(w http.ResponseWriter, status int, s domain.Site) {
|
||||
body, err := json.Marshal(s)
|
||||
if err != nil {
|
||||
http.Error(w, "Failed to encode response", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
if status != http.StatusOK {
|
||||
w.WriteHeader(status)
|
||||
}
|
||||
if _, err := w.Write(body); err != nil {
|
||||
log.Printf("Failed to write response: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func writeSiteError(w http.ResponseWriter, err error) {
|
||||
switch {
|
||||
case errors.Is(err, domain.ErrSiteNotFound):
|
||||
http.Error(w, apperr.SiteNotFoundErrorMessage, http.StatusNotFound)
|
||||
case errors.Is(err, domain.ErrSiteKeyTaken):
|
||||
http.Error(w, apperr.SiteKeyTakenErrorMessage, http.StatusConflict)
|
||||
case errors.Is(err, domain.ErrSiteHasArticles):
|
||||
http.Error(w, apperr.SiteHasArticlesErrorMessage, http.StatusConflict)
|
||||
case errors.Is(err, domain.ErrDefaultSite):
|
||||
http.Error(w, apperr.DefaultSiteErrorMessage, http.StatusForbidden)
|
||||
case errors.Is(err, domain.ErrKeyImmutable):
|
||||
http.Error(w, apperr.SiteKeyImmutableErrorMessage, http.StatusBadRequest)
|
||||
case errors.Is(err, domain.ErrInvalidSiteURL):
|
||||
http.Error(w, apperr.InvalidSiteURLErrorMessage, http.StatusBadRequest)
|
||||
case errors.Is(err, domain.ErrInvalidTitleTemplate):
|
||||
http.Error(w, apperr.InvalidTitleTemplateErrorMessage, http.StatusBadRequest)
|
||||
case errors.Is(err, domain.ErrInvalidLocale):
|
||||
http.Error(w, apperr.InvalidLocaleErrorMessage, http.StatusBadRequest)
|
||||
case errors.Is(err, image.ErrImageNotFound):
|
||||
http.Error(w, apperr.SiteImageNotFoundErrorMessage, http.StatusBadRequest)
|
||||
case errors.Is(err, domain.ErrUseSetDefault):
|
||||
http.Error(w, apperr.UseSetDefaultErrorMessage, http.StatusBadRequest)
|
||||
case errors.Is(err, domain.ErrInvalidReassign):
|
||||
http.Error(w, apperr.InvalidReassignErrorMessage, http.StatusBadRequest)
|
||||
default:
|
||||
http.Error(w, "Internal server error", http.StatusInternalServerError)
|
||||
}
|
||||
}
|
||||
|
||||
const (
|
||||
defaultListPage = 1
|
||||
defaultListSize = 25
|
||||
)
|
||||
|
||||
type listQuery struct {
|
||||
Page int `validate:"gte=1"`
|
||||
Size int `validate:"omitempty,oneof=5 25 50 100"`
|
||||
Q string `validate:"max=200"`
|
||||
}
|
||||
|
||||
func intQueryParam(values url.Values, name string, fallback int) (int, error) {
|
||||
if !values.Has(name) {
|
||||
return fallback, nil
|
||||
}
|
||||
return strconv.Atoi(values.Get(name))
|
||||
}
|
||||
|
||||
func readListQuery(values url.Values) (listQuery, error) {
|
||||
paged := values.Has("page") || values.Has("size")
|
||||
page, err := intQueryParam(values, "page", defaultListPage)
|
||||
if err != nil {
|
||||
return listQuery{}, err
|
||||
}
|
||||
size := 0
|
||||
if paged {
|
||||
size, err = intQueryParam(values, "size", defaultListSize)
|
||||
if err != nil {
|
||||
return listQuery{}, err
|
||||
}
|
||||
if size == 0 {
|
||||
return listQuery{}, errors.New("invalid size")
|
||||
}
|
||||
}
|
||||
return listQuery{Page: page, Size: size, Q: values.Get("q")}, nil
|
||||
}
|
||||
|
||||
func (h *Handler) List(w http.ResponseWriter, r *http.Request) {
|
||||
query, err := readListQuery(r.URL.Query())
|
||||
if err != nil || validator.Validate.Struct(query) != nil {
|
||||
http.Error(w, apperr.BodyErrorMessage, http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
page, err := h.ListUseCase.ListPage(useCases.ListSitesCommand{Q: query.Q, Page: query.Page, Size: query.Size})
|
||||
if err != nil {
|
||||
http.Error(w, "Internal server error", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
body, err := json.Marshal(page.Items)
|
||||
if err != nil {
|
||||
http.Error(w, "Failed to encode response", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
w.Header().Set("X-Total-Count", strconv.Itoa(page.Total))
|
||||
if _, err := w.Write(body); err != nil {
|
||||
log.Printf("Failed to write response: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func (h *Handler) Create(w http.ResponseWriter, r *http.Request) {
|
||||
var request PostSite
|
||||
if err := json.NewDecoder(r.Body).Decode(&request); err != nil {
|
||||
http.Error(w, apperr.BodyErrorMessage, http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
if err := validator.Validate.Struct(request); err != nil {
|
||||
http.Error(w, err.Error(), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
created, err := h.CreateUseCase.Create(r.Context(), useCases.CreateSiteCommand{
|
||||
Name: request.Name,
|
||||
Key: request.Key,
|
||||
BaseURL: request.BaseURL,
|
||||
DefaultRobots: request.DefaultRobots,
|
||||
Locale: request.Locale,
|
||||
DefaultSocialImageID: request.DefaultSocialImageID,
|
||||
IsDefault: request.IsDefault,
|
||||
SiteName: request.SiteName,
|
||||
TitleTemplate: request.TitleTemplate,
|
||||
DefaultDescription: request.DefaultDescription,
|
||||
})
|
||||
if err != nil {
|
||||
writeSiteError(w, err)
|
||||
return
|
||||
}
|
||||
writeSite(w, http.StatusCreated, created)
|
||||
}
|
||||
|
||||
func (h *Handler) Update(w http.ResponseWriter, r *http.Request) {
|
||||
id, err := parseSiteId(r)
|
||||
if err != nil {
|
||||
http.Error(w, apperr.IdUint32ErrorMessage, http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
var request PatchSite
|
||||
if err := json.NewDecoder(r.Body).Decode(&request); err != nil {
|
||||
http.Error(w, apperr.BodyErrorMessage, http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
if err := validator.Validate.Struct(request); err != nil {
|
||||
http.Error(w, err.Error(), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
updated, err := h.UpdateUseCase.Update(r.Context(), id, request.toPatch())
|
||||
if err != nil {
|
||||
writeSiteError(w, err)
|
||||
return
|
||||
}
|
||||
writeSite(w, http.StatusOK, updated)
|
||||
}
|
||||
|
||||
func (h *Handler) SetDefault(w http.ResponseWriter, r *http.Request) {
|
||||
id, err := parseSiteId(r)
|
||||
if err != nil {
|
||||
http.Error(w, apperr.IdUint32ErrorMessage, http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
updated, err := h.SetDefaultUseCase.SetDefault(r.Context(), id)
|
||||
if err != nil {
|
||||
writeSiteError(w, err)
|
||||
return
|
||||
}
|
||||
writeSite(w, http.StatusOK, updated)
|
||||
}
|
||||
|
||||
const reassignQueryParam = "reassign_to"
|
||||
|
||||
func readReassign(r *http.Request) (*uint32, bool) {
|
||||
query := r.URL.Query()
|
||||
if !query.Has(reassignQueryParam) {
|
||||
return nil, false
|
||||
}
|
||||
parsed, err := strconv.ParseUint(query.Get(reassignQueryParam), 10, 32)
|
||||
if err != nil {
|
||||
return nil, true
|
||||
}
|
||||
destination := uint32(parsed)
|
||||
return &destination, false
|
||||
}
|
||||
|
||||
func (h *Handler) Delete(w http.ResponseWriter, r *http.Request) {
|
||||
id, err := parseSiteId(r)
|
||||
if err != nil {
|
||||
http.Error(w, apperr.IdUint32ErrorMessage, http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
reassignTo, invalid := readReassign(r)
|
||||
if err := h.DeleteUseCase.Delete(r.Context(), useCases.DeleteSiteCommand{ID: id, ReassignTo: reassignTo, ReassignInvalid: invalid}); err != nil {
|
||||
writeSiteError(w, err)
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
package site
|
||||
|
||||
import (
|
||||
"RenewCMS/api/pkg/apperr"
|
||||
validator "RenewCMS/api/pkg/validator"
|
||||
"RenewCMS/internal/infrastructure/useCases"
|
||||
"encoding/json"
|
||||
"log"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
)
|
||||
|
||||
const (
|
||||
defaultSitemapPage = 1
|
||||
defaultSitemapSize = 100
|
||||
totalCountHeader = "X-Total-Count"
|
||||
)
|
||||
|
||||
type SitemapHandler struct {
|
||||
ListUseCase *useCases.ListSitemapUseCase
|
||||
}
|
||||
|
||||
func NewSitemapHandler(list *useCases.ListSitemapUseCase) *SitemapHandler {
|
||||
return &SitemapHandler{ListUseCase: list}
|
||||
}
|
||||
|
||||
type sitemapQuery struct {
|
||||
Page int `validate:"gte=1"`
|
||||
Size int `validate:"oneof=25 50 100 500"`
|
||||
}
|
||||
|
||||
type sitemapItem struct {
|
||||
URL string `json:"url"`
|
||||
ModifiedAt string `json:"modified_at"`
|
||||
Noindex bool `json:"noindex"`
|
||||
}
|
||||
|
||||
func sitemapIntParam(values url.Values, name string, fallback int) (int, error) {
|
||||
if !values.Has(name) {
|
||||
return fallback, nil
|
||||
}
|
||||
return strconv.Atoi(values.Get(name))
|
||||
}
|
||||
|
||||
func readSitemapQuery(values url.Values) (sitemapQuery, error) {
|
||||
page, err := sitemapIntParam(values, "page", defaultSitemapPage)
|
||||
if err != nil {
|
||||
return sitemapQuery{}, err
|
||||
}
|
||||
size, err := sitemapIntParam(values, "size", defaultSitemapSize)
|
||||
if err != nil {
|
||||
return sitemapQuery{}, err
|
||||
}
|
||||
return sitemapQuery{Page: page, Size: size}, nil
|
||||
}
|
||||
|
||||
func (h *SitemapHandler) Sitemap(w http.ResponseWriter, r *http.Request) {
|
||||
query, err := readSitemapQuery(r.URL.Query())
|
||||
if err != nil || validator.Validate.Struct(query) != nil {
|
||||
http.Error(w, apperr.BodyErrorMessage, http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
page, err := h.ListUseCase.List(chi.URLParam(r, "key"), query.Page, query.Size)
|
||||
if err != nil {
|
||||
writeSiteError(w, err)
|
||||
return
|
||||
}
|
||||
|
||||
items := make([]sitemapItem, 0, len(page.Entries))
|
||||
for _, entry := range page.Entries {
|
||||
items = append(items, sitemapItem{URL: entry.URL, ModifiedAt: entry.ModifiedAt.UTC().Format(time.RFC3339), Noindex: entry.Noindex})
|
||||
}
|
||||
body, err := json.Marshal(items)
|
||||
if err != nil {
|
||||
http.Error(w, "Failed to encode response", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
w.Header().Set(totalCountHeader, strconv.Itoa(page.Total))
|
||||
if _, err := w.Write(body); err != nil {
|
||||
log.Printf("Failed to write response: %v", err)
|
||||
}
|
||||
}
|
||||
@@ -12,7 +12,7 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/go-chi/jwtauth/v5"
|
||||
"github.com/lestrrat-go/jwx/v2/jwt"
|
||||
"github.com/lestrrat-go/jwx/v3/jwt"
|
||||
)
|
||||
|
||||
const bearerScheme = "bearer "
|
||||
|
||||
@@ -5,7 +5,7 @@ import (
|
||||
"net/http"
|
||||
|
||||
"github.com/go-chi/jwtauth/v5"
|
||||
"github.com/lestrrat-go/jwx/v2/jwt"
|
||||
"github.com/lestrrat-go/jwx/v3/jwt"
|
||||
)
|
||||
|
||||
func RequireSignedIn(next http.Handler) http.Handler {
|
||||
|
||||
@@ -57,3 +57,32 @@ const CachePurgeScopeErrorMessage = "Scope must be all, unused, variant or image
|
||||
const CachePurgeTargetErrorMessage = "A variant name or an image id is required for this scope."
|
||||
const VariantUnknownMessage = "Unknown variant"
|
||||
const VariantUnsupportedParameterMessage = "Unsupported parameter"
|
||||
const SiteNotFoundErrorMessage = "site_not_found"
|
||||
const SiteKeyTakenErrorMessage = "site_key_taken"
|
||||
const SiteHasArticlesErrorMessage = "site_has_articles"
|
||||
const DefaultSiteErrorMessage = "default_site"
|
||||
const SiteKeyImmutableErrorMessage = "key_immutable"
|
||||
const InvalidSiteURLErrorMessage = "invalid_site_url"
|
||||
const InvalidLocaleErrorMessage = "invalid_locale"
|
||||
const SiteImageNotFoundErrorMessage = "image_not_found"
|
||||
const UseSetDefaultErrorMessage = "use_set_default"
|
||||
const InvalidReassignErrorMessage = "invalid_reassign"
|
||||
const InvalidSocialTypeErrorMessage = "invalid_social_type"
|
||||
|
||||
const AuthorNotFoundErrorMessage = "author_not_found"
|
||||
const AuthorSlugTakenErrorMessage = "author_slug_taken"
|
||||
const AuthorHasArticlesErrorMessage = "author_has_articles"
|
||||
const UserAlreadyLinkedErrorMessage = "user_already_linked"
|
||||
const AuthorAlreadyLinkedErrorMessage = "author_already_linked"
|
||||
const UserNotFoundErrorMessage = "user_not_found"
|
||||
const AuthorRightsErrorMessage = "author_rights"
|
||||
const BioTooLongErrorMessage = "bio_too_long"
|
||||
const InvalidURLErrorMessage = "invalid_url"
|
||||
const TooManyLinksErrorMessage = "too_many_links"
|
||||
const InvalidSlugErrorMessage = "invalid_slug"
|
||||
const AuthorImageNotFoundErrorMessage = "image_not_found"
|
||||
|
||||
const ArticleSlugTakenErrorMessage = "slug_taken"
|
||||
const ArticleImageNotFoundErrorMessage = "image_not_found"
|
||||
const InvalidTitleTemplateErrorMessage = "invalid_title_template"
|
||||
const SlugSuggestionHeader = "X-Slug-Suggestion"
|
||||
@@ -1,7 +1,11 @@
|
||||
package validator
|
||||
|
||||
import (
|
||||
"RenewCMS/internal/domain/article"
|
||||
"RenewCMS/internal/domain/author"
|
||||
"RenewCMS/internal/domain/image"
|
||||
"RenewCMS/internal/domain/site"
|
||||
"reflect"
|
||||
"regexp"
|
||||
|
||||
"github.com/go-playground/validator/v10"
|
||||
@@ -9,6 +13,12 @@ import (
|
||||
|
||||
const inviteEmailTag = "inviteemail"
|
||||
const variantNameTag = "variantname"
|
||||
const siteKeyTag = "sitekey"
|
||||
const siteNameTag = "sitename"
|
||||
const AuthorNameTag = "authorname"
|
||||
const AuthorSlugTag = "authorslug"
|
||||
const SocialTypeTag = "socialtype"
|
||||
const ArticleSlugTag = "articleslug"
|
||||
|
||||
var inviteEmailPattern = regexp.MustCompile(`^[^\s@]+@[^\s@.]+(\.[^\s@.]+)+$`)
|
||||
|
||||
@@ -18,6 +28,44 @@ func InitValidator() {
|
||||
Validate = validator.New()
|
||||
_ = Validate.RegisterValidation(inviteEmailTag, isInviteEmail)
|
||||
_ = Validate.RegisterValidation(variantNameTag, isVariantName)
|
||||
_ = Validate.RegisterValidation(siteKeyTag, isSiteKey)
|
||||
_ = Validate.RegisterValidation(siteNameTag, isSiteName)
|
||||
_ = Validate.RegisterValidation(AuthorNameTag, isAuthorName, true)
|
||||
_ = Validate.RegisterValidation(AuthorSlugTag, isAuthorSlug, true)
|
||||
_ = Validate.RegisterValidation(SocialTypeTag, isSocialType, true)
|
||||
_ = Validate.RegisterValidation(ArticleSlugTag, isArticleSlug, true)
|
||||
}
|
||||
|
||||
func isArticleSlug(field validator.FieldLevel) bool {
|
||||
if isAbsent(field) {
|
||||
return true
|
||||
}
|
||||
value := field.Field().String()
|
||||
return value == "" || article.IsValidSlug(value)
|
||||
}
|
||||
|
||||
func isAbsent(field validator.FieldLevel) bool {
|
||||
return field.Field().Kind() == reflect.Ptr && field.Field().IsNil()
|
||||
}
|
||||
|
||||
func isAuthorName(field validator.FieldLevel) bool {
|
||||
return isAbsent(field) || author.IsValidName(field.Field().String())
|
||||
}
|
||||
|
||||
func isSocialType(field validator.FieldLevel) bool {
|
||||
return author.IsValidSocialType(field.Field().String())
|
||||
}
|
||||
|
||||
func isAuthorSlug(field validator.FieldLevel) bool {
|
||||
return isAbsent(field) || author.IsValidSlug(field.Field().String())
|
||||
}
|
||||
|
||||
func isSiteKey(field validator.FieldLevel) bool {
|
||||
return site.IsValidKey(field.Field().String())
|
||||
}
|
||||
|
||||
func isSiteName(field validator.FieldLevel) bool {
|
||||
return site.IsValidName(field.Field().String())
|
||||
}
|
||||
|
||||
func isVariantName(field validator.FieldLevel) bool {
|
||||
|
||||
+76
-2
@@ -5,10 +5,12 @@ import (
|
||||
"RenewCMS/api/handlers/apikey"
|
||||
"RenewCMS/api/handlers/article"
|
||||
"RenewCMS/api/handlers/auth"
|
||||
"RenewCMS/api/handlers/author"
|
||||
"RenewCMS/api/handlers/frontend"
|
||||
"RenewCMS/api/handlers/imagevariant"
|
||||
"RenewCMS/api/handlers/media"
|
||||
"RenewCMS/api/handlers/settings"
|
||||
"RenewCMS/api/handlers/site"
|
||||
"RenewCMS/api/handlers/staticimages"
|
||||
"RenewCMS/api/handlers/update"
|
||||
"RenewCMS/api/handlers/user"
|
||||
@@ -55,9 +57,12 @@ func NewArticleRouter(container *UseCases, trustedProxies []string) http.Handler
|
||||
|
||||
articleHandler := article.NewHandler(container.CreateArticleUseCase, container.GetArticleUseCase, container.ListArticlesUseCase, container.DeleteArticleUseCase, container.UpdateArticleUseCase, container.GetUserUseCase)
|
||||
|
||||
seoHandler := article.NewSEOHandler(container.ResolveArticleSEOUseCase, container.CheckArticleSEOUseCase, container.GetUserUseCase)
|
||||
|
||||
r.Group(func(r chi.Router) {
|
||||
r.Get("/", articleHandler.ListArticles)
|
||||
r.Get("/{id}", articleHandler.GetArticle)
|
||||
r.Get("/{id}/seo", seoHandler.Resolve)
|
||||
})
|
||||
r.Group(func(r chi.Router) {
|
||||
r.Use(jwtauth.Authenticator(container.Token))
|
||||
@@ -68,6 +73,7 @@ func NewArticleRouter(container *UseCases, trustedProxies []string) http.Handler
|
||||
r.Patch("/{id}", articleHandler.UpdateArticleBody)
|
||||
r.Patch("/{id}/publish", articleHandler.PublishArticle)
|
||||
r.Patch("/{id}/unpublish", articleHandler.UnpublishArticle)
|
||||
r.Post("/{id}/seo/check", seoHandler.Check)
|
||||
})
|
||||
return r
|
||||
}
|
||||
@@ -79,7 +85,7 @@ func NewAuthRouter(container *UseCases, isProduction bool, rateLimit config.Auth
|
||||
|
||||
loginHandler := auth.NewLoginHandler(container.Token, container.CreateUserUseCase, container.AuthenticateUserUseCase, isProduction)
|
||||
verificationHandler := auth.NewVerificationHandler(container.VerifyUserUseCase, container.CancelRegistrationUseCase, isProduction)
|
||||
meHandler := auth.NewMeHandler(container.GetUserUseCase)
|
||||
meHandler := auth.NewMeHandler(container.GetUserUseCase, container.GetMyAuthorUseCase)
|
||||
passwordResetHandler := auth.NewPasswordResetHandler(container.RequestPasswordResetUseCase, container.ResetPasswordUseCase)
|
||||
acceptInviteHandler := auth.NewAcceptInviteHandler(container.GetInviteUseCase, container.AcceptInviteUseCase, container.Token, isProduction)
|
||||
|
||||
@@ -173,6 +179,71 @@ func NewSettingsRouter(container *UseCases, trustedProxies []string) http.Handle
|
||||
return r
|
||||
}
|
||||
|
||||
func NewSiteRouter(container *UseCases, trustedProxies []string) http.Handler {
|
||||
r := chi.NewRouter()
|
||||
|
||||
siteHandler := site.NewHandler(container.ListSitesUseCase, container.CreateSiteUseCase, container.UpdateSiteUseCase, container.SetDefaultSiteUseCase, container.DeleteSiteUseCase)
|
||||
|
||||
sitemapHandler := site.NewSitemapHandler(container.ListSitemapUseCase)
|
||||
|
||||
r.Get("/{key}/sitemap", sitemapHandler.Sitemap)
|
||||
r.Group(func(r chi.Router) {
|
||||
r.Use(jwtauth.Verifier(container.Token))
|
||||
r.Use(container.apiKeyAuth())
|
||||
r.Use(jwtauth.Authenticator(container.Token))
|
||||
r.Use(middleware.RequireCurrentToken(container.GetUserUseCase))
|
||||
r.Use(middleware.RequireVerifiedUser(container.GetUserUseCase))
|
||||
r.Get("/", siteHandler.List)
|
||||
})
|
||||
r.Group(func(r chi.Router) {
|
||||
r.Use(middleware.RequireSession)
|
||||
r.Use(jwtauth.Verifier(container.Token))
|
||||
r.Use(middleware.AuditContext(container.GetUserUseCase, trustedProxies))
|
||||
r.Use(middleware.RequireSignedIn)
|
||||
r.Use(jwtauth.Authenticator(container.Token))
|
||||
r.Use(middleware.RequireCurrentToken(container.GetUserUseCase))
|
||||
r.Use(middleware.RequireVerifiedUser(container.GetUserUseCase))
|
||||
r.Use(middleware.RequireOwner(container.GetUserUseCase))
|
||||
r.Post("/", siteHandler.Create)
|
||||
r.Patch("/{id}", siteHandler.Update)
|
||||
r.Patch("/{id}/default", siteHandler.SetDefault)
|
||||
r.Delete("/{id}", siteHandler.Delete)
|
||||
})
|
||||
return r
|
||||
}
|
||||
|
||||
func NewAuthorRouter(container *UseCases, trustedProxies []string) http.Handler {
|
||||
r := chi.NewRouter()
|
||||
|
||||
authorHandler := author.NewHandler(container.ListAuthorsUseCase, container.CreateAuthorUseCase, container.CreateMyAuthorUseCase, container.UpdateAuthorUseCase, container.DeleteAuthorUseCase, container.GetUserUseCase)
|
||||
|
||||
r.Group(func(r chi.Router) {
|
||||
r.Use(jwtauth.Verifier(container.Token))
|
||||
r.Use(container.apiKeyAuth())
|
||||
r.Use(jwtauth.Authenticator(container.Token))
|
||||
r.Use(middleware.RequireCurrentToken(container.GetUserUseCase))
|
||||
r.Use(middleware.RequireVerifiedUser(container.GetUserUseCase))
|
||||
r.Get("/", authorHandler.List)
|
||||
})
|
||||
r.Group(func(r chi.Router) {
|
||||
r.Use(middleware.RequireSession)
|
||||
r.Use(jwtauth.Verifier(container.Token))
|
||||
r.Use(middleware.AuditContext(container.GetUserUseCase, trustedProxies))
|
||||
r.Use(middleware.RequireSignedIn)
|
||||
r.Use(jwtauth.Authenticator(container.Token))
|
||||
r.Use(middleware.RequireCurrentToken(container.GetUserUseCase))
|
||||
r.Use(middleware.RequireVerifiedUser(container.GetUserUseCase))
|
||||
r.Post("/me", authorHandler.CreateMine)
|
||||
r.Patch("/{id}", authorHandler.Update)
|
||||
r.Group(func(r chi.Router) {
|
||||
r.Use(middleware.RequireOwnerOrAdmin(container.GetUserUseCase))
|
||||
r.Post("/", authorHandler.Create)
|
||||
r.Delete("/{id}", authorHandler.Delete)
|
||||
})
|
||||
})
|
||||
return r
|
||||
}
|
||||
|
||||
func NewActivityRouter(container *UseCases, trustedProxies []string) http.Handler {
|
||||
r := chi.NewRouter()
|
||||
|
||||
@@ -279,6 +350,7 @@ func NewMediaRouter(container *UseCases, trustedProxies []string) http.Handler {
|
||||
r.Post("/merge", mediaHandler.Merge)
|
||||
r.Patch("/{id}", mediaHandler.Rename)
|
||||
r.Delete("/{id}", mediaHandler.Delete)
|
||||
r.Get("/{id}", mediaHandler.Get)
|
||||
r.Get("/{id}/usage", mediaHandler.Usage)
|
||||
return r
|
||||
}
|
||||
@@ -320,6 +392,8 @@ func InitBackendRoutes(container *UseCases, settings config.Settings) *chi.Mux {
|
||||
})
|
||||
r.Mount("/user", NewUserRouter(container, settings.AuthRateLimit, settings.TrustedProxies))
|
||||
r.Mount("/settings", NewSettingsRouter(container, settings.TrustedProxies))
|
||||
r.Mount("/site", NewSiteRouter(container, settings.TrustedProxies))
|
||||
r.Mount("/author", NewAuthorRouter(container, settings.TrustedProxies))
|
||||
r.Mount("/activity", NewActivityRouter(container, settings.TrustedProxies))
|
||||
r.Mount("/media", NewMediaRouter(container, settings.TrustedProxies))
|
||||
r.Mount("/image-variants", NewImageVariantRouter(container, settings.TrustedProxies))
|
||||
@@ -353,7 +427,7 @@ func enableCorsIfConfigured(r *chi.Mux, origins []string) {
|
||||
AllowedOrigins: origins,
|
||||
AllowedMethods: []string{"GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"},
|
||||
AllowedHeaders: []string{"Accept", "Authorization", "Content-Type", "X-CSRF-Token"},
|
||||
ExposedHeaders: []string{"Link"},
|
||||
ExposedHeaders: []string{"Link", "X-Total-Count"},
|
||||
AllowCredentials: false,
|
||||
MaxAge: 300,
|
||||
}))
|
||||
|
||||
+175
-11
@@ -10,23 +10,27 @@ The origin that serves the app, for example `https://cms.example`. Every path st
|
||||
for example `https://cms.example/v1/article/`.
|
||||
|
||||
## Authentication
|
||||
- Public routes need nothing: `GET /v1/article/` and `GET /v1/article/{id}`. They return online
|
||||
articles only.
|
||||
- Public routes need nothing: `GET /v1/article/`, `GET /v1/article/{id}`, `GET /v1/article/{id}/seo`
|
||||
and `GET /v1/site/{key}/sitemap`. They return online articles only; the list and the resolved SEO
|
||||
object also answer drafts to a verified session or API key.
|
||||
- Everything else needs a signed-in browser session (the `jwt` cookie) or an API key:
|
||||
`Authorization: Bearer rcms_...`. Create keys at `/integration/api-keys`. A key acts as its
|
||||
creator, with that user's role, and shows in full once.
|
||||
- A key cannot call `POST /v1/auth/verify`, `DELETE /v1/auth/register`, `/v1/api-key/*` or
|
||||
`/v1/system/*`. Those answer 403 "This action needs a real session." An invalid, unknown, expired
|
||||
or revoked key answers 401, even on public routes.
|
||||
or revoked key answers 401, even on public routes. The site writes (`POST`, `PATCH` and `DELETE`
|
||||
under `/v1/site`) and the author writes (`POST`, `PATCH` and `DELETE` under `/v1/author`, `POST /v1/author/me` included) are session only too.
|
||||
- Each key can make 120 requests per minute. Beyond that: 429 with a `Retry-After` header.
|
||||
|
||||
## Routes a key can call (24)
|
||||
## Routes a key can call (30)
|
||||
| Group | Routes |
|
||||
| --- | --- |
|
||||
| Articles | GET /v1/article/, GET /v1/article/{id}, POST /v1/article/, PATCH /v1/article/{id}, PATCH /v1/article/{id}/publish, PATCH /v1/article/{id}/unpublish, DELETE /v1/article/{id} |
|
||||
| Media | GET /v1/media/, POST /v1/media/, PATCH /v1/media/{id}, DELETE /v1/media/{id}, POST /v1/media/merge, GET /v1/media/{id}/usage, GET /v1/media/purge-settings (owner or admin), PATCH /v1/media/purge-settings (owner or admin), GET /v1/media/purge-preview (owner or admin), POST /v1/media/purge (owner or admin), GET /v1/media/{id}/variants (owner or admin, session only), POST /v1/media/{id}/variants (owner or admin, session only), POST /v1/media/{id}/variants/{name} (owner or admin, session only), DELETE /v1/media/{id}/variants/{name} (owner or admin, session only) |
|
||||
| Users and invites | GET /v1/user/, PATCH /v1/user/me, POST /v1/user/invite (owner only), DELETE /v1/user/invite/{id} (owner only), POST /v1/user/invite/{id}/renew (owner only), GET /v1/auth/me |
|
||||
| Articles | GET /v1/article/, GET /v1/article/{id}, GET /v1/article/{id}/seo, POST /v1/article/{id}/seo/check, POST /v1/article/, PATCH /v1/article/{id}, PATCH /v1/article/{id}/publish, PATCH /v1/article/{id}/unpublish, DELETE /v1/article/{id} |
|
||||
| Media | GET /v1/media/, GET /v1/media/{id}, POST /v1/media/, PATCH /v1/media/{id}, DELETE /v1/media/{id}, POST /v1/media/merge, GET /v1/media/{id}/usage, GET /v1/media/purge-settings (owner or admin), PATCH /v1/media/purge-settings (owner or admin), GET /v1/media/purge-preview (owner or admin), POST /v1/media/purge (owner or admin), GET /v1/media/{id}/variants (owner or admin, session only), POST /v1/media/{id}/variants (owner or admin, session only), POST /v1/media/{id}/variants/{name} (owner or admin, session only), DELETE /v1/media/{id}/variants/{name} (owner or admin, session only) |
|
||||
| Users and invites | GET /v1/user/, PATCH /v1/user/me, POST /v1/user/invite (owner only), DELETE /v1/user/invite/{id} (owner only), POST /v1/user/invite/{id}/renew (owner only), GET /v1/auth/me (with the linked `author`) |
|
||||
| Settings | GET /v1/settings |
|
||||
| Sites | GET /v1/site/, GET /v1/site/{key}/sitemap |
|
||||
| Authors | GET /v1/author/ |
|
||||
|
||||
## Activity log
|
||||
The activity routes are session only: a key answers 403 "This action needs a real session." and a
|
||||
@@ -40,7 +44,7 @@ key never reads the audit trail. Events are append-only; there is no `POST`, `PU
|
||||
| `GET /v1/activity/export` | Owner, admin | The same filters as the list without `page` or `size`, as a `text/csv; charset=utf-8` attachment (`when,actor,action,target,outcome,source,ip`). Cells starting with `=`, `+`, `-` or `@` get a leading quote. |
|
||||
|
||||
Query: `q`, `actor` (`user:ID`, `key:ID`, `system`), `category` (`articles`, `media`, `users`,
|
||||
`api_keys`, `auth`, `system`), `outcome` (`all`, `success`, `failed`), `security` (`true`), `range`
|
||||
`api_keys`, `auth`, `system`, `sites`, `authors`), `outcome` (`all`, `success`, `failed`), `security` (`true`), `range`
|
||||
(`today`, `7d`, `30d`, `all`, `custom`; default `7d`), `from` and `to` (dates, with `custom`), `page` (from
|
||||
1) and `size` (25, 50 or 100). Any invalid value answers 400 with the body-mismatch message. Dates
|
||||
are UTC. The list answers `{ items, total, page, size }`, newest first (`created_at`, then `id`).
|
||||
@@ -65,12 +69,14 @@ never changes the response or the change itself.
|
||||
| `articles` | `article.create`, `article.edit`, `article.publish`, `article.unpublish`, `article.delete` |
|
||||
| `media` | `media.upload`, `media.rename`, `media.delete`, `media.merge`, `media.purge`, `media.variant_create`, `media.variant_update`, `media.variant_delete`, `media.variant_enable`, `media.variant_disable`, `media.variant_purge`, `media.variant_generate_all`, `media.variant_purge_image`, `media.variant_purge_all`, `media.variant_purge_unused` |
|
||||
| `users` | `user.register`, `user.verify`, `user.update_profile`, `invite.create`, `invite.cancel`, `invite.renew`, `invite.accept` |
|
||||
| `sites` | `site.create`, `site.edit`, `site.set_default`, `site.delete` |
|
||||
| `authors` | `author.create`, `author.edit`, `author.delete` |
|
||||
| `system` | `system.media_purge` (scheduled), `system.update_checked`, `system.update_downloaded`, `system.restart_requested`, `system.activity_cleanup`, `system.activity_retention_changed` |
|
||||
|
||||
Target types: `article`, `image`, `image_variant` (id and name are the variant name), `user`, `invite`,
|
||||
Target types: `article`, `site`, `author`, `image`, `image_variant` (id and name are the variant name), `user`, `invite`,
|
||||
`api_key` and `release` (id and name are the tag).
|
||||
Only the fields `title`, `online`, `body`, `filename`, `display_name`, `width`, `height`, `fit`, `format` and `quality` appear in `changes`, with the
|
||||
kinds `text` and `body`; a body edit carries a signed character count delta and never the text. A
|
||||
Only the fields `title`, `online`, `body`, `site`, `name`, `base_url`, `default_robots`, `locale`, `default_social_image`, `slug`, `canonical_url`, `noindex`, `cover_image`, `social_image`, `excerpt`, `seo_title`, `seo_description`, `social_title`, `social_description`, `cover_image_alt`, `site_name`, `title_template`, `default_description`, `bio`, `website`, `social_links`, `avatar`, `user`, `authors`, `filename`, `display_name`, `width`, `height`, `fit`, `format` and `quality` appear in `changes` (a site key is never a change; moving an article records `site` with the site names; changing the credited authors records `authors` with the names in order; the `user` change of an author holds usernames, never an email), with the
|
||||
kinds `text` and `body`; a body edit carries a signed character count delta and never the text; the free-text SEO fields (`excerpt`, `seo_title`, `seo_description`, `social_title`, `social_description`, `cover_image_alt`) do the same under their own field name, while `slug`, `canonical_url`, `noindex`, `cover_image`, `social_image` (image file names) and the site fields `site_name`, `title_template`, `default_description` carry `before` and `after`. `seo_dismissed` is not an edit and records nothing. A
|
||||
change that leaves a value as it was (same body, same publish state, same file name, same display
|
||||
name) records nothing. Params: `media.merge` and `media.purge` and `system.media_purge` carry
|
||||
`merged` and `articles_updated`, plus `failed_groups` when a group failed (still outcome `success`);
|
||||
@@ -109,9 +115,167 @@ with `items: []` and the real `total`. Any invalid `page`, `size`, `filter`, `so
|
||||
`hash` is 400 "The media query is invalid.". Every item carries `variant_count` and `variant_size`
|
||||
(the index rows of the image and their bytes, 0 when none).
|
||||
|
||||
`GET /v1/media/{id}` reads one image with the same auth as the list (a verified session or an API key; 403 for an
|
||||
unverified account, 401 without credentials) and writes nothing, so it records no activity event. It answers 200 with
|
||||
the object of one `items` element of the list, a missing image is 404 "Image not found" and a malformed id is 400 with
|
||||
the id-format message.
|
||||
|
||||
Breaking change: `next_cursor` is gone and no `X-Total-Count` header is sent. `cursor` and `limit`
|
||||
are no longer parameters; they are ignored, never an error, and have no effect on paging.
|
||||
|
||||
## Sites
|
||||
Every article belongs to exactly one site, and exactly one site is the default. A site is `{ id,
|
||||
name, key, base_url, default_social_image_id, default_robots, locale, is_default, article_count }`:
|
||||
`name` is 1 to 100 characters, `key` is 2 to 32 characters of lowercase letters, digits and single
|
||||
dashes (`^[a-z0-9]+(-[a-z0-9]+)*$`) and never changes, `base_url` is `https` (or `http` for
|
||||
`localhost`, `127.0.0.1` and `[::1]`) with no path, query or user info (a trailing slash is
|
||||
stripped, uniqueness is not enforced), `default_robots` is `index` (default) or `noindex`, `locale`
|
||||
is `null` or a tag such as `en` or `fr-CA` (an empty string means none) and `default_social_image_id`
|
||||
is `null` or the id of an image. Read access needs a verified session or an API key; every write is
|
||||
session only and owner only (403 "Only the owner can do this.", or "This action needs a real
|
||||
session." with a key). The role is checked before the body.
|
||||
|
||||
| Route | Purpose |
|
||||
| --- | --- |
|
||||
| `GET /v1/site/` | The sites, default first and then by name, each with `article_count`. Query `q` (up to 200 characters, matched in `name`, `key` or `base_url`, ignoring case and accents, `%` and `_` literal), `page` (a whole number from 1) and `size` (5, 25, 50 or 100). Without `page` and `size` every matching site is returned; with only `page`, `size` is 25; with only `size`, `page` is 1. The body stays a JSON array (`[]` when nothing matches, never `null`) and `X-Total-Count` holds the number of matching sites before paging. A page past the end is `200 []` with the total. An invalid `page`, `size` or `q` is 400 with the body-mismatch message and no `X-Total-Count`. |
|
||||
| `POST /v1/site/` | Create. 201 with the site. `is_default: true` makes it the default. `site_name`, `title_template` and `default_description` are optional and validated like on `PATCH`. |
|
||||
| `PATCH /v1/site/{id}` | Edit `name`, `base_url`, `default_robots`, `locale`, `default_social_image_id`, `site_name`, `title_template`, `default_description`. Absent fields are untouched. `key` may only be repeated unchanged; `is_default` is refused. |
|
||||
| `PATCH /v1/site/{id}/default` | Make the site the default, atomically. Setting the current default is a no-op. |
|
||||
| `DELETE /v1/site/{id}?reassign_to={id}` | 204. A site with articles needs `reassign_to`; the articles move and the site is deleted in one transaction. `reassign_to` is ignored when the site has no article. |
|
||||
|
||||
Errors are plain text whose body is exactly the token: 409 `site_key_taken`, 409 `site_has_articles`,
|
||||
403 `default_site` (checked before the articles), 400 `key_immutable`, 400 `invalid_site_url`, 400
|
||||
`invalid_locale`, 400 `invalid_title_template`, 400 `image_not_found`, 400 `use_set_default`, 400 `invalid_reassign` (missing
|
||||
number, the site itself or not a whole number) and 404 `site_not_found`. Refused writes except `site_not_found` and `image_not_found` are recorded as failed events. A body that cannot be
|
||||
decoded is 400 with the body-mismatch message, a malformed id is 400 with the uint32 message, and a
|
||||
field that fails validation (`name`, `key` format, `default_robots`, `site_name` over 100 characters, `title_template` over 200, `default_description` over 320) is 400 with the validator text.
|
||||
|
||||
A site also carries `site_name` (at most 100 characters, `""` by default), `title_template` (at most 200 characters, `%title% | %site%` by default; it must contain `%title%`, case sensitive, otherwise 400 `invalid_title_template`, an empty template included) and `default_description` (at most 320 characters, `""` by default). They appear on every site response, `POST` accepts them and `PATCH` edits them like the other site fields. Existing sites get the defaults when the server starts after the upgrade.
|
||||
|
||||
Articles carry `site_id`. A new article starts on the default site. `GET /v1/article/?site=<key>`
|
||||
keeps only the articles of that site and composes with `status`, `q`, `sort`, `size` and `page`;
|
||||
`counts` stay global, an unknown key answers 200 with no item and an empty `site=` is 400 with the
|
||||
body-mismatch message. `PATCH /v1/article/{id}` takes `body`, `site_id`, `author_ids` and the SEO
|
||||
fields below, and nothing else, such as `title`: absent fields are untouched, an empty object, an object without
|
||||
those fields, a `null` value (except on `cover_image_id` and `social_image_id`) or a malformed value is 400 with the body-mismatch message, `site_id: 0` is
|
||||
400 with the validator text and an unknown site is 404 `site_not_found`. Moving an article never
|
||||
changes `is_online`. `{"body": ""}` still sets an empty body, but `{}` and `{"body": null}` no longer do: they are 400.
|
||||
|
||||
### Resolved SEO, check, list status and sitemap
|
||||
|
||||
RenewCMS renders no page and injects no meta tag: it returns the data a frontend needs.
|
||||
|
||||
| Route | Who | Purpose |
|
||||
| --- | --- | --- |
|
||||
| `GET /v1/article/{id}/seo` | public for online articles; a verified session or API key also reads drafts | The resolved object `{ title, description, canonical_url, robots, og, twitter, image, authors, published_at, modified_at, fallbacks, json_ld }`. It never carries the body, the id or `seo_dismissed`, ignores `format`, and writes nothing. An offline article for any other caller, and a missing one, is 404 `Article not found`. |
|
||||
| `POST /v1/article/{id}/seo/check` | verified session or API key (401 without credentials, 403 unverified) | Evaluates the article without saving. The body is `{}` or any of the twelve SEO fields of `PATCH` plus `body`; each replaces the saved value for this check only. `site_id`, `author_ids`, unknown fields and `null` (except on `cover_image_id` and `social_image_id`) are 400 with the body-mismatch message. The other validation is the one of `PATCH` (`invalid_slug`, `invalid_url` as 422, `image_not_found`, validator text). Answers `{ status, suggestions, slug }` where `suggestions` is `[{ code, field, params }]` and `slug` is `{ available, suggestion }`. A taken slug is a 200 with `available: false` and the first free `<slug>-N` in `suggestion`, never a 409. |
|
||||
| `GET /v1/site/{key}/sitemap` | public | A JSON array `[{ url, modified_at, noindex }]` of the online articles of the site with that key, by id ascending. `url` is `base_url/slug` (never the canonical override). `page` (default 1) and `size` (25, 50, 100 or 500, default 100); an invalid value is 400 with the body-mismatch message. The total is in the `X-Total-Count` header. An unknown key, an id included, is 404 `site_not_found`. |
|
||||
|
||||
`GET /v1/article/` also takes `seo=ready|suggestions|hidden` (any other value, an empty one included, is 400 with the body-mismatch message, after the `format` check). It is applied before paging and composes with `q`, `status`, `site`, `sort`, `page` and `size`; `total` follows it and `counts` ignore it. Every item carries `seo_status` (`ready`, `suggestions` or `hidden`) and `seo_suggestions` (the number of suggestions that are not dismissed). The filter is evaluated in memory over every matching article, so its cost grows with the number of articles on the site; without it only the returned page is assessed.
|
||||
|
||||
`X-Total-Count` is added to `Access-Control-Expose-Headers` next to `Link`, so a browser on an allowed origin can read it.
|
||||
|
||||
### Article SEO fields
|
||||
|
||||
An article carries twelve search and sharing fields, all edited through `PATCH /v1/article/{id}` and returned by
|
||||
every single-article read (`GET /v1/article/{id}`, `POST`, `PATCH`, `publish`, `unpublish`):
|
||||
`slug`, `excerpt`, `seo_title`, `seo_description`, `cover_image_id`, `cover_image_alt`, `social_title`,
|
||||
`social_description`, `social_image_id`, `canonical_url`, `noindex` and `seo_dismissed`. Text fields are `""`
|
||||
when empty, the two image ids are `null` when unset, `noindex` is `false` and `seo_dismissed` is `[]` by
|
||||
default. Each item of `GET /v1/article/` carries `excerpt` and `slug` and none of the other ten.
|
||||
The limits are counted in characters: `excerpt` 300, `seo_title` 120, `seo_description` 320,
|
||||
`cover_image_alt` 200, `social_title` 120, `social_description` 320, `canonical_url` 2048; going over is
|
||||
400 with the validator text. `cover_image_id` and `social_image_id` accept `null` (and only those two do);
|
||||
`0` is 400 with the validator text and an unknown image is 400 `image_not_found`. `canonical_url` is `""` or an absolute
|
||||
`https` URL with a host, otherwise 422 `invalid_url`. `seo_dismissed` is a list of the codes `title_long`,
|
||||
`title_empty`, `desc_short`, `desc_long`, `cover_alt`, `cover_none`, `slug_long`, `no_au`, `no_h`, `body_alt`
|
||||
and `short`: an unknown code is 400 with the validator text and duplicates are collapsed with the order
|
||||
kept. `noindex` is only a flag, it does not take the article offline.
|
||||
|
||||
The `slug` matches `^[a-z0-9]+(-[a-z0-9]+)*$` with 1 to 100 characters (400 `invalid_slug`) and is unique per
|
||||
site, never globally. It is generated from the title when the article is created: lowercase, accents folded,
|
||||
every run of other characters becomes one dash, dashes trimmed, cut to 100 characters, and `article` when no
|
||||
letter or digit is left; a slug already used on the site gets `-2`, `-3`... silently. The same rule
|
||||
backfills the existing articles when the server starts after the upgrade (in id order within each site, so
|
||||
the oldest article keeps the plain slug). Sending `slug: ""` regenerates the slug from the title. A slug
|
||||
used by another article on the target site (the new site when `site_id` is sent too, and a move re-checks
|
||||
the current slug) is 409 with the plain-text body `slug_taken`; the response then carries the header
|
||||
`X-Slug-Suggestion` holding the first free `<slug>-N` from 2 on that site, fitting 100 characters. The header
|
||||
is set on this 409 only, never on another response. A regeneration that collides is refused the same way, never suffixed
|
||||
silently. Saving an article with its own slug is not a collision. Publishing never changes a slug, a deleted article
|
||||
frees its slug.
|
||||
|
||||
New error tokens are plain text from the handler: 409 `slug_taken`, 400 `invalid_slug`, 422 `invalid_url`, 400
|
||||
`image_not_found` and 400 `invalid_title_template` (sites). Edits that change a SEO field are recorded as
|
||||
`article.edit` events (`slug`, `canonical_url`, `noindex`, `cover_image`, `social_image` with before and after;
|
||||
the free-text fields as a size delta only); a refused slug is recorded as failed.
|
||||
|
||||
A site's `default_social_image_id` counts as a use of that image: it raises `used_in` and keeps the
|
||||
image out of the `unused` filter. Deleting the image sets the field to `null` and succeeds. `POST /v1/media/merge` and `POST
|
||||
/v1/media/purge` repoint the sites of the merged copies to the kept image and report it as
|
||||
`sites_updated` next to `articles_updated`.
|
||||
|
||||
An article's `cover_image_id` and `social_image_id` count the same way. `used_in` counts every article that uses the
|
||||
image in its body, as cover or as social image once, plus the authors using it as an avatar and the sites using it as default
|
||||
social image. Deleting an image never fails because of its uses: the covers and social images pointing at it are set to `null`
|
||||
(the `cover_image_alt` and the bodies are untouched), and a failed delete leaves every reference in place. A merge or a purge repoints
|
||||
the covers and social images of the copies to the kept image, and an article rewritten in its body and its cover counts once in
|
||||
`articles_updated`.
|
||||
|
||||
`GET /v1/media/{id}/usage` stays an array. Every item keeps the keys it had and gains `type` (`article`,
|
||||
`author` or `site`) and `fields`. An article item is `{ "type": "article", "id", "title", "published", "fields" }` with
|
||||
`fields` from `body`, `cover` and `social` (one item per article, in that order); an author item is
|
||||
`{ "type": "author", "id", "title": <name>, "fields": ["avatar"] }` and a site item is `{ "type": "site", "id", "title": <name>,
|
||||
"fields": ["default_social_image"] }`; author and site items have no `published` key. The array is `[]` for an unused image.
|
||||
|
||||
## Authors
|
||||
|
||||
An author is a public byline, with or without an account. It is `{ id, name, slug, bio, avatar_id,
|
||||
website, social_links, user_id, is_linked, article_count }`, plus `user_email` for owners and admins
|
||||
only (absent for every other caller). `name` is 1 to 100 characters after trimming, `slug` matches
|
||||
`^[a-z0-9]+(-[a-z0-9]+)*$` with 1 to 100 characters and is unique (generated from the name when
|
||||
omitted: accents folded, punctuation runs become one dash, `author` when nothing is left), `bio` has
|
||||
at most 280 characters (counted in runes), `avatar_id` is `null` or an image id, `website` is `null`
|
||||
or an `https` URL with a host (an empty string means none, at most 2048 characters),
|
||||
`social_links` holds at most 5 `{ "type", "url" }` with `type` one of `x`, `linkedin`, `github`,
|
||||
`mastodon`, `custom` and an `https` URL. `user_id` is the unique link to a user. Zero authors on an
|
||||
article is allowed and never blocks publishing.
|
||||
|
||||
| Route | Who | Purpose |
|
||||
| --- | --- | --- |
|
||||
| `GET /v1/author/` | verified session or API key | The authors newest first. Query `q` (name or slug, accent and case insensitive), `page` (default 1), `size` (5, 25, 50 or 100, default 25). Body `{ items, total, page, size }`, with `total` repeated in the `X-Total-Count` header on every 200; a bad query is 400 with the body-mismatch message and no header. |
|
||||
| `POST /v1/author/` | owner or admin, session only | Create. 201 with the author. `user_id` links an account that has no author. |
|
||||
| `POST /v1/author/me` | any verified session | Create the caller's own author from the display name (or the username). A taken slug gets `-2`, `-3`... silently. 201 with the author plus `slug_adjusted`: `true` when the stored slug differs from the plain slug of the name (a collision suffix was added), `false` otherwise. No other author response carries this field. |
|
||||
| `PATCH /v1/author/{id}` | owner or admin on any author; any verified session on the author linked to it; session only | Edit `name`, `slug`, `bio`, `avatar_id`, `website`, `social_links`, `user_id`. Absent fields are untouched, `avatar_id`, `website` and `user_id` accept `null`, `social_links` is replaced as a whole. `user_id` links or unlinks the account and is owner or admin only. |
|
||||
| `DELETE /v1/author/{id}?reassign_to={id\|none}` | owner or admin, session only | 204. An author credited on articles needs `reassign_to`: an author id (that author takes the deleted one's position and is never duplicated on an article) or `none` (the credit is removed). The move and the delete are one transaction. `reassign_to` is ignored when the author has no article. The linked account is untouched. |
|
||||
|
||||
The role checks use the existing bodies: 403 "Only owners and admins can do this." for `POST /` and
|
||||
`DELETE`, 403 `author_rights` for a `PATCH` by an account that is not owner or admin on an author
|
||||
that is not its own (or that sends `user_id`), and 403 "This action needs a real session." for a key.
|
||||
Errors are plain text whose body is exactly the token: 404 `author_not_found`, 404 `user_not_found`,
|
||||
409 `author_slug_taken`, 409 `author_has_articles`, 409 `user_already_linked`, 409
|
||||
`author_already_linked`, 400 `invalid_slug`, 400 `invalid_reassign` (own id, not a whole number,
|
||||
negative or empty), 400 `image_not_found`, 422 `bio_too_long`, 422 `invalid_url` and 422
|
||||
`too_many_links`. A body that cannot be decoded, an empty `PATCH` or one that nulls a required field
|
||||
is 400 with the body-mismatch message, a malformed id is 400 with the uint32 message and other
|
||||
validation failures (`name`, link `type`) are 400 with the validator text. Writes refused for a
|
||||
reason other than a missing target or an invalid value are recorded as failed events.
|
||||
|
||||
Articles carry `authors`, the ordered credits (the first is the primary byline), each with only `id`,
|
||||
`name`, `slug`, `bio`, `avatar_id`, `website` and `social_links`; it is `[]` when there is none and it
|
||||
is visible on online articles to anonymous readers. `PATCH /v1/article/{id}` also takes
|
||||
`author_ids`, the whole ordered list: it replaces the credits, `[]` empties them, an unknown id is 404
|
||||
`author_not_found`, a duplicate, `null` or a malformed list is 400 with the body-mismatch message and
|
||||
`0` is 400 with the validator text. Absent means unchanged. A new article is credited to the
|
||||
creator's linked author when there is one. `GET /v1/auth/me` returns the existing user fields plus
|
||||
`author`: the caller's linked author (`id`, `name`, `slug`, `bio`, `avatar_id`, `website`,
|
||||
`social_links`, `article_count`) or `null`.
|
||||
|
||||
An author's `avatar_id` counts as a use of that image like a site's social image: it raises `used_in`
|
||||
and keeps the image out of the `unused` filter, and `GET /v1/media/{id}/usage` lists the author with the field `avatar`.
|
||||
Deleting the image sets `avatar_id` to `null`. `POST /v1/media/merge` and `POST /v1/media/purge`
|
||||
repoint the avatars of the merged copies and report it as `authors_updated`.
|
||||
|
||||
## Image variants
|
||||
Owners and admins manage named variants of the stored images. These routes are session only (no API
|
||||
key) and sit behind the verified-user check; any other role gets 403 "Only owners and admins can do
|
||||
|
||||
+92
-2
@@ -2,6 +2,8 @@
|
||||
|
||||
Every route that returns an article accepts the optional `format` query parameter and returns the article body in that format. Articles are stored as HTML (Tiptap output). Storage and the request bodies of `POST /v1/article/` and `PATCH /v1/article/{id}` stay HTML.
|
||||
|
||||
`PATCH /v1/article/{id}` takes `body`, `site_id`, `author_ids` (the whole ordered list of author ids, see `docs/api.md`) and the SEO fields listed below, and nothing else. The request must contain at least one of them, and `null` answers `400` except for `cover_image_id` and `social_image_id`. Behaviour change: `{}` and `{"body": null}` used to set an empty body and now answer `400`; send `{"body": ""}` to empty a body.
|
||||
|
||||
## Routes that honour `format`
|
||||
|
||||
- `GET /v1/article/`
|
||||
@@ -23,7 +25,7 @@ Visibility is unchanged: anonymous and unverified callers only see online articl
|
||||
"total": 30,
|
||||
"page": 1,
|
||||
"size": 25,
|
||||
"counts": { "all": 30, "online": 30, "draft": 0 }
|
||||
"counts": { "all": 30, "online": 30, "draft": 0, "suggestions": 4 }
|
||||
}
|
||||
```
|
||||
|
||||
@@ -33,12 +35,15 @@ Visibility is unchanged: anonymous and unverified callers only see online articl
|
||||
| `size` | `5`, `25`, `50` or `100` | `25` |
|
||||
| `q` | up to 200 characters, matched anywhere in the title, ignoring case and accents | none |
|
||||
| `status` | `online` or `draft` | none |
|
||||
| `site` | the `key` of a site; an unknown key gives an empty page, an empty value is `400` | none |
|
||||
| `seo` | `ready`, `suggestions` or `hidden`; any other value, an empty one included, is `400` | none |
|
||||
| `sort` | `title`, `status`, `created_at` or `updated_at`, then `:asc` or `:desc` (lowercase, for example `title:asc`) | `updated_at:desc` |
|
||||
|
||||
- `items` is `[]` when empty, never `null`. Each item is the article object below.
|
||||
- Items follow `sort` (default `updated_at:desc`) across the whole list before paging. `title` ignores case, `status` orders on online state (`status:asc` puts drafts first), and every ordering ends with `id` descending so pages never overlap.
|
||||
- `total` is the number of visible articles matching `q` and `status`, before paging. `page` and `size` echo the values applied.
|
||||
- `counts` ignores `q` and `status`, so tab counts do not move while searching. For anonymous and unverified callers `all` equals `online` and `draft` is `0`, and `status=draft` answers `items: []` and `total: 0`.
|
||||
- `counts` ignores `q`, `status`, `site`, `seo`, `sort`, `page` and `size`, so tab counts do not move while searching. `suggestions` is the number of visible articles whose `seo_status` is `suggestions` (hidden and ready articles and dismissed codes are not counted); it equals the `total` of `?seo=suggestions` sent with no other filter by the same caller. For anonymous and unverified callers `all` equals `online` and `draft` is `0`, and `status=draft` answers `items: []` and `total: 0`.
|
||||
- Each item also carries `seo_status` and `seo_suggestions` (see [SEO status and suggestions](#seo-status-and-suggestions)). `seo` filters on the status before paging, so `total` follows it while `counts` do not.
|
||||
- A page beyond the last answers `200` with `items: []` and the real `total`.
|
||||
- An invalid `page`, `size`, `status`, `sort` or an over-long `q` answers `400` with the plain-text message `The request cannot be processed due to a mismatch in the format of the body.` An invalid `format` is reported first.
|
||||
|
||||
@@ -66,11 +71,93 @@ Breaking change: the default used to be HTML. Clients that need HTML must send `
|
||||
"body": "## Plan\n\nReplace the **old** deck.",
|
||||
"body_format": "markdown",
|
||||
"is_online": true,
|
||||
"site_id": 1,
|
||||
"authors": [],
|
||||
"slug": "backyard-renovation-update",
|
||||
"excerpt": "",
|
||||
"seo_title": "",
|
||||
"seo_description": "",
|
||||
"cover_image_id": null,
|
||||
"cover_image_alt": "",
|
||||
"social_title": "",
|
||||
"social_description": "",
|
||||
"social_image_id": null,
|
||||
"canonical_url": "",
|
||||
"noindex": false,
|
||||
"seo_dismissed": [],
|
||||
"created_at": "2026-03-12T09:14:00Z",
|
||||
"updated_at": "2026-09-10T07:00:00Z"
|
||||
}
|
||||
```
|
||||
|
||||
Every single-article read (`GET /v1/article/{id}`, `POST`, `PATCH`, `publish`, `unpublish`) carries the twelve SEO fields. Each item of `GET /v1/article/` carries `slug` and `excerpt` only, and none of the other ten.
|
||||
|
||||
## SEO fields
|
||||
|
||||
| Field | Type | Limit and rule |
|
||||
| --- | --- | --- |
|
||||
| `slug` | string | `^[a-z0-9]+(-[a-z0-9]+)*$`, 1 to 100 characters, unique per site. `""` regenerates it from the title. |
|
||||
| `excerpt` | string | 300 characters |
|
||||
| `seo_title` | string | 120 characters |
|
||||
| `seo_description` | string | 320 characters |
|
||||
| `cover_image_id` | number or `null` | an existing image id (`0` is refused) |
|
||||
| `cover_image_alt` | string | 200 characters, independent of the cover |
|
||||
| `social_title` | string | 120 characters |
|
||||
| `social_description` | string | 320 characters |
|
||||
| `social_image_id` | number or `null` | an existing image id (`0` is refused) |
|
||||
| `canonical_url` | string | `""` or an absolute `https` URL with a host, at most 2048 characters |
|
||||
| `noindex` | boolean | only a flag: the article stays online |
|
||||
| `seo_dismissed` | array of strings | any of `title_long`, `title_empty`, `desc_short`, `desc_long`, `cover_alt`, `cover_none`, `slug_long`, `no_au`, `no_h`, `body_alt`, `short`; duplicates are collapsed, order kept |
|
||||
|
||||
Limits are counted in characters (runes), not bytes. Absent fields are untouched; text fields and `noindex` are cleared with `""`, `false` and `[]`, the two image ids with `null`.
|
||||
|
||||
### The slug
|
||||
|
||||
A slug is unique per site (`site_id`, `slug`), never globally. At creation it is generated from the title: lowercase, accents folded, every run of other characters becomes one dash, dashes trimmed, cut to 100 characters without a trailing dash, and `article` when no letter or digit is left. A slug already used on the site gets `-2`, `-3`... silently, the base being truncated so the result fits 100 characters. The same rule backfills existing articles on the first start after the upgrade, in id order within each site.
|
||||
|
||||
Editing a slug that another article of the target site already uses (the new site when `site_id` is sent in the same request; moving an article also re-checks its current slug there) answers `409` with the plain-text body `slug_taken`, and the response header `X-Slug-Suggestion` holds the first free `<slug>-N` from 2 on that site, fitting 100 characters. `X-Slug-Suggestion` is set on this `409` only and on no other response. A request with `slug: ""` that regenerates onto another article's slug is refused the same way and never suffixed silently. Re-sending an article's own slug is not a conflict. A refused request changes nothing.
|
||||
|
||||
Publishing, unpublishing and `noindex` never change a slug. A deleted article frees its slug.
|
||||
|
||||
## Resolved SEO object
|
||||
|
||||
`GET /v1/article/{id}/seo` answers the data a frontend renders in its `<head>`. Online articles are public; a draft needs a verified session or API key and is otherwise `404 Article not found`. The query is ignored (no `format`). Keys:
|
||||
|
||||
`title`, `description`, `canonical_url`, `robots`, `og` (`type`, `title`, `description`, `image`, `image_alt`, `url`, `site_name`, `locale`), `twitter` (`card`, `title`, `description`, `image`, `image_alt`), `image` (`url`, `alt`, `source`), `authors` (`name`, `url`, `same_as`), `published_at`, `modified_at`, `fallbacks` and `json_ld` (a ready schema.org `Article`).
|
||||
|
||||
The fallback chain, first non-empty wins:
|
||||
|
||||
| Output | Chain | `fallbacks` value |
|
||||
| --- | --- | --- |
|
||||
| `title` | `seo_title`, then the article title, then the site `title_template` (`%title%`, `%site%` replaced by `site_name`, result trimmed) | `seo_title`, `title` |
|
||||
| `description` | `seo_description`, `excerpt`, the first sentence of the body (tags removed), the site `default_description` | `seo_description`, `excerpt`, `body`, `site`, `none` |
|
||||
| `image` | `social_image_id`, `cover_image_id` (with `cover_image_alt`), the site `default_social_image_id`; `url` is the site `base_url` plus the image path, `""` and `none` when there is none | `social`, `cover`, `site`, `none` |
|
||||
| `canonical_url` | `canonical_url`, then site `base_url` + `/` + `slug` | `canonical_url`, `site` |
|
||||
| `robots` | `noindex, nofollow` when `noindex` is true, otherwise from the site `default_robots` (`index, follow` or `noindex, nofollow`) | none |
|
||||
| `og` and `twitter` title and description | `social_title` and `social_description`, then the resolved values | none |
|
||||
|
||||
`og.type` is `article`, `og.locale` is the site locale (`""` when none), `twitter.card` is `summary_large_image` with an image and `summary` without. `published_at` is the creation time of an online article and `null` for a draft; `modified_at` is `updated_at`. `authors[].url` is the author website (`""` when none) and `same_as` lists the social link URLs only. `json_ld.headline` is the meta title without the site template, and `author`, `image` and `datePublished` are left out when empty.
|
||||
|
||||
## SEO status and suggestions
|
||||
|
||||
`POST /v1/article/{id}/seo/check` and the list use one rule set. Soft ranges never block saving or publishing; lengths are counted in characters.
|
||||
|
||||
| Code | Field | Fires when | `params` |
|
||||
| --- | --- | --- | --- |
|
||||
| `title_long` | `seo_title` | the meta title (`seo_title`, else the title) is over 60 characters | `length`, `max` |
|
||||
| `title_empty` | `seo_title` | the meta title is empty after trimming | none |
|
||||
| `desc_short` | `seo_description` | the resolved description is under 70 characters | `length`, `min` |
|
||||
| `desc_long` | `seo_description` | the resolved description is over 160 characters | `length`, `max` |
|
||||
| `cover_alt` | `cover_image_alt` | there is a cover and its alt text is empty | none |
|
||||
| `cover_none` | `cover_image_id` | there is no cover | none |
|
||||
| `slug_long` | `slug` | the slug is over 75 characters | `length`, `max` |
|
||||
| `no_au` | `author_ids` | no author is credited | none |
|
||||
| `no_h` | `body` | the text has at least 1000 characters and no `h2` to `h6` | none |
|
||||
| `body_alt` | `body` | an image of the body has no alt text | `count` |
|
||||
| `short` | `body` | the text has fewer than 300 characters | `length`, `min` |
|
||||
|
||||
Suggestions come in that order. Codes in `seo_dismissed` are never reported or counted. The status is `hidden` when `noindex` is true, else `suggestions` when at least one suggestion remains, else `ready`. The list items carry `seo_status` and `seo_suggestions` (the count, also for a hidden article).
|
||||
|
||||
## Markdown output
|
||||
|
||||
Headings, bold, italic, links, bullet and ordered lists, blockquotes, fenced code blocks, rules, images and inline code are converted. Anything else is reduced to its text. `script` and `style` content is removed, and the source HTML is never passed through; the only HTML in the output is the alignment wrapper described below. List indentation attributes are dropped. Links with a scheme other than http, https, mailto or tel are reduced to their text. Characters that markdown would read as formatting (`*`, `_`, `` ` ``, `[`, `]`, `<`, `\`) and line starts that would read as a heading, list, quote or rule (`#`, `-`, `+`, `>`, `1.`) are backslash-escaped, so plain text stays plain text. A line break becomes a backslash followed by a newline.
|
||||
@@ -124,5 +211,8 @@ Example for `<h2>Plan</h2><p>Replace the <strong>old</strong> deck.</p>`:
|
||||
| --- | --- |
|
||||
| `400` | `The server expects the ID to be in the format of an unsigned 32-bit integer (uint32).` for an invalid id |
|
||||
| `400` | `The format must be one of: markdown, html, json.` for an unsupported format |
|
||||
| `400` | `invalid_slug`, `image_not_found` or the validator text for an over-long SEO field, `cover_image_id: 0` or an unknown `seo_dismissed` code |
|
||||
| `404` | `Article not found` |
|
||||
| `409` | `slug_taken`, with the header `X-Slug-Suggestion: <first free slug>` (this response only) |
|
||||
| `422` | `invalid_url` for a `canonical_url` that is not an absolute `https` URL with a host |
|
||||
| `500` | `Internal server error` when the body cannot be converted |
|
||||
@@ -69,6 +69,28 @@ The use cases `ListActivity`, `GetActivitySummary` and `ExportActivity` turn the
|
||||
|
||||
Producers: `ArticleChanges`, `TextChange` and `BodyChange` in `internal/domain/audit` build the change lists (the body change holds only a signed rune count delta), and `NewTarget` and `ReleaseTarget` build the target snapshots (types `article`, `image`, `user`, `invite`, `api_key`, `release`). The use cases create, edit, publish, unpublish and delete article, upload, rename, delete, merge and purge media, register, verify, update profile, create, cancel, renew and accept invite, check, download and restart take the request context first and an `audit.Recorder` last, and record exactly one event after the change or the refusal (the action catalogue is in `docs/api.md`). Events are never written by handlers, middleware or GORM hooks, and nothing is recorded for reads or for a target that does not exist. `useCases/auditFailures.go` holds the fixed table of failure sentences keyed by domain `Err...` sentinels (matched with `errors.Is`, each at most 255 characters; the restart action overrides `ErrJobInProgress`) with the generic fallback "Something went wrong on our side. Please try again."; raw error text is never stored. The manual purge runs the groups through the non-recording `MergeMediaUseCase.merge`, so only one `media.purge` event is written; `RunPurgeUseCase.Execute` is the non-recording run that `PurgeSchedulerUseCase.Tick(now)` uses to record one `system.media_purge` event with the system actor and `context.Background()`. `StartUpdateDownloadUseCase` hands `context.WithoutCancel(ctx)` to its job goroutine so the `system.update_downloaded` event, written when the job becomes `ready` or `failed`, keeps the origin of the request. `middleware.AuditContext` is mounted on the article, user, media and system routers (after the API key middleware where keys are accepted), so API key calls are attributed to the key.
|
||||
|
||||
### Sites
|
||||
|
||||
`internal/domain/site` holds the `Site` entity (name, immutable key, normalised base URL, optional default social image, `index` or `noindex` robots, optional locale, the default flag and the computed `article_count`), `NormalizeBaseURL`, `SeedBaseURL`, `NormalizeLocale`, `IsValidKey`, the `Patch` type (with `Nullable` for the two nullable fields), the `Err...` sentinels (`ErrSiteNotFound`, `ErrSiteKeyTaken`, `ErrSiteHasArticles`, `ErrDefaultSite`, `ErrKeyImmutable`, `ErrInvalidSiteURL`, `ErrInvalidLocale`, `ErrUseSetDefault`, `ErrInvalidReassign`) and the `Repository` interface. `persistence.SiteRepository` implements it over `models.Site` (`sites`, unique `site_key`); the single default is kept by the transactional operations `Create` (when flagged) and `SetDefault`, not by an index, and `DeleteMovingArticles` moves the articles and deletes the site in one transaction. Articles carry a `site_id` (indexed, no foreign key, so the SQL stays portable).
|
||||
|
||||
The use cases `ListSites`, `CreateSite`, `UpdateSite`, `SetDefaultSite` and `DeleteSite` live in `internal/infrastructure/useCases`; the article, media and purge use cases take the site repository as a required constructor argument, wired by the composition root (new articles take the default site, `UpdateArticle` moves an article and records `site` with site names, the media use cases count, clear and repoint default social images). `api/handlers/site` serves `/v1/site`; reads accept a session or an API key, writes are session only behind `RequireOwner`. `database.Migrate(db, publicURL)` registers the model, seeds one default site from `PUBLIC_URL` when the table is empty and backfills `articles.site_id`.
|
||||
|
||||
### Authors
|
||||
|
||||
`internal/domain/author` holds the `Author` entity (name, unique slug, bio, optional avatar, optional website, social links, the unique optional `user_id`, `is_linked`, the computed `article_count` and a `user_email` that only owner and admin responses carry), the public `Byline` shape embedded in articles, the `Patch` type, the slug generation (a hand-written Latin diacritic folding table, no external dependency), the value rules (`ValidateBio`, `ValidateURL`, `ValidateLinks`, `IsValidSlug`, `IsValidName`), the `Err...` sentinels (`ErrAuthorNotFound`, `ErrSlugTaken`, `ErrAuthorHasArticles`, `ErrUserAlreadyLinked`, `ErrAuthorAlreadyLinked`, `ErrAuthorRights`, `ErrBioTooLong`, `ErrInvalidURL`, `ErrTooManyLinks`, `ErrInvalidSlug`, `ErrInvalidReassign`) and the `Repository` interface. `persistence.AuthorRepository` implements it over `models.Author` (`authors`, unique `slug` and unique nullable `user_id`) and the ordered join `models.ArticleAuthor` (`article_authors`, unique `(article_id, author_id)` and a `position`); uniqueness is checked inside the transaction and re-explained after a failed write, so a race still answers a domain sentinel, and `DeleteMovingCredits` moves the credits (keeping the position, never duplicating) and deletes the author in one transaction. `ArticleRepository` attaches the ordered `Byline`s to the articles it returns, writes `author_ids` in the article update transaction and removes the credits when an article is deleted.
|
||||
|
||||
The use cases `ListAuthors`, `CreateAuthor`, `CreateMyAuthor`, `UpdateAuthor`, `DeleteAuthor` and `GetMyAuthor` live in `internal/infrastructure/useCases`; `CreateArticle` credits the creator's author, `UpdateArticle` validates and records `author_ids`, and the media, purge and activity use cases take the author repository as a required constructor argument (avatars count as media usage, are cleared on delete and repointed on merge and purge). `api/handlers/author` serves `/v1/author`: the list accepts a session or an API key, every write is session only, `POST /` and `DELETE` sit behind `RequireOwnerOrAdmin`, and the edit rights (owner or admin, or the caller's own linked author) are decided by `UpdateAuthor` from the caller the handler passes in. `GET /v1/auth/me` adds the linked author through `GetMyAuthor`.
|
||||
|
||||
### Article SEO data
|
||||
|
||||
`internal/domain/slug` holds the one slug rule (`Generate`, `WithSuffix`, `IsValid`: lowercase, accents folded, runs of other characters become one dash, 100 characters, a caller-chosen fallback). `internal/domain/article` uses it with the fallback `article` and holds the twelve SEO fields of `Article`, the `Update` fields for them (`Nullable` for the two image ids), `ValidateCanonicalURL`, the eleven dismiss codes and `NormalizeDismissed`, and the sentinels `ErrInvalidSlug`, `ErrSlugTaken` and `ErrInvalidCanonicalURL`. `*SlugTakenError` wraps `ErrSlugTaken` and carries the suggested free slug; the handler turns it into the `X-Slug-Suggestion` header of the 409. `author.GenerateSlug` delegates to the same package.
|
||||
|
||||
Slugs are unique per site, enforced by the unique index `idx_articles_site_slug` on `(site_id, slug)`. The use cases decide first: `CreateArticle` generates the slug from the title and takes the first free `-N` on the default site (retrying when the repository reports a race), `UpdateArticle` re-checks the slug on the target site for an edited slug, an empty slug (regenerated from the title) and a move, and computes the suggestion as the first free `-N` from 2, fitting 100 characters. `ArticleRepository` locks the site row, checks the slug inside the transaction and re-explains a failed write as `ErrSlugTaken`. Deleting an article replaces its slug with the tombstone `#deleted-<id>` (it can never match a valid slug) before the soft delete, so the slug is free again while the unique index keeps covering soft-deleted rows.
|
||||
|
||||
`database.Migrate` adds the columns with `AutoMigrate`, then runs `BackfillSiteTitleTemplates` and `BackfillArticleSlugs` (only rows with an empty slug, in id order, per site, applying the same rule and the same suffixes, with the tombstone for soft-deleted rows) and only then creates the unique index, so it is idempotent and completes a partly backfilled table. The default `title_template` is written by the backfill and the seed, not by a column default, because the SQLite migrator rebuilds the table on every start when the default contains `%` and `|`.
|
||||
|
||||
Media usage has more sources than article bodies: `Article.CoverImageID` and `SocialImageID`, `Author.AvatarID` and `Site.DefaultSocialImageID`. `ListMedia`, the purge plan and `GetMediaUsage` count an article once however many places use the image. `DeleteMedia` clears the cover and social references (`article.Repository.ClearImage`, restored with `RestoreImage` when the delete fails), `MergeMedia` repoints them (`RepointImage`) and counts an article rewritten in its body and its cover once, and `GetMediaUsage` (now built with the site and author repositories) returns articles, authors and sites with `type` and `fields`.
|
||||
|
||||
### Image variants
|
||||
|
||||
`internal/domain/image` holds the `Variant` entity and its rules (`VariantSettings.Normalized`, the settings `Fingerprint`, `VariantETag`, `ETagMatches`, `IsAnimatedGIF`), the sentinels (`ErrVariantNotFound`, `ErrVariantExists`, `ErrVariantInvalid`, `ErrVariantFormatUnavailable`, `ErrUnknownVariant`, `ErrUnsupportedParameter`, `ErrSourceTooLarge`) and three ports: `VariantRepository` (definitions), `VariantFileRepository` (the index of generated files: variant name, source stored name, cached stored name, content type, size and the settings fingerprint, needed because `Storage.Put` chooses the stored name itself) and `VariantRenderer` (decode a source, encode a variant, report the formats it can encode). `internal/infrastructure/imaging` is the renderer adapter, free of GORM and HTTP; the persistence adapters are `VariantRepository` and `VariantFileRepository` over `models.ImageVariant` and `models.ImageVariantFile`.
|
||||
|
||||
@@ -10,7 +10,7 @@ Copy [`.env.example`](../.env.example) to `.env` to get started. When a required
|
||||
|
||||
| Name | Description | Example |
|
||||
|-----------------|---------------------------------------------------------------------------------------------------------------------|----------------------------|
|
||||
| `PUBLIC_URL` | Public base URL of the site, including scheme and no trailing slash. Used for links in emails and in the startup log. | `https://cms.example.com` |
|
||||
| `PUBLIC_URL` | Public base URL of the site, including scheme and no trailing slash. Used for links in emails and in the startup log. It is also the CMS's own address: at the first migration, when the sites table is empty, it seeds the default site (name "Default", key "default") with its scheme and host (path dropped, non-loopback `http` upgraded to `https`); an unparseable value stops the migration. It is never read for sites afterwards. | `https://cms.example.com` |
|
||||
| `JWT_SECRET` | Secret used to sign the auth JWT. Use a long random value; changing it logs everyone out. | `openssl rand -hex 32` |
|
||||
| `SMTP_LOGIN` | SMTP username used to authenticate with the server. Some providers (e.g. Brevo) issue a login distinct from the sender address. | `noreply@example.com` |
|
||||
| `SMTP_SENDER` | Sender address used in the `From` header. Must be an address/domain the SMTP provider allows that login to send as. | `noreply@example.com` |
|
||||
|
||||
+17
-4
@@ -3,13 +3,25 @@
|
||||
Nuxt UI v4 back-office. Tokens only, no raw hex (brand mark excepted). Light and dark. 1440×900 and 390×844. Radius 0.
|
||||
|
||||
## Boards
|
||||
- `RenewCMS Screens Back-office.dc.html`: every back-office screen, Settings → Media (variants, cache), and the group "States matrix: controls". Frames: `AppFrame` (shell), `ActivityFrame`, `MediaFrame`, `VariantsFrame`, `IntegrationPage`, `IntegrationImages`, `CodeSnippet`, `StatesMatrix`.
|
||||
- `RenewCMS Screens Back-office.dc.html`: every back-office screen, Settings → Media (variants, cache), and the group "States matrix: controls". Frames: `AppFrame` (shell), `DirectoryFrame` (Sites and Authors), `ActivityFrame`, `MediaFrame`, `VariantsFrame`, `IntegrationPage`, `IntegrationImages`, `CodeSnippet`, `StatesMatrix`.
|
||||
- `RenewCMS Screens Auth.dc.html` (7 groups, 50 states), `RenewCMS Screens API keys.dc.html` (12 states).
|
||||
- `RenewCMS Prototype.dc.html`: updated to match (title-only New article, no body limit or counter, neutral count, pagination, link button, AppFrame's mobile drawer).
|
||||
- Unchanged: Foundations, Components, Handoff, Directions and Emails boards.
|
||||
|
||||
## Pass 3: sites and authors (revised)
|
||||
Roles, decisions and the slice order are in `sites-authors-slices.md` (Sites and Authors) and `seo-slices.md` (SEO).
|
||||
|
||||
Back-office board groups: Sites, Sites: form, Sites: delete, Authors, Authors: form, Authors: delete, Editor: site and authors, Profile: author profile, Articles: sites and authors. Plus tables: decisions to confirm (13 rows, 5 marked Decided), deviations, API and errors (with the 403 rows), components, accessibility, copy per state.
|
||||
- Roles: only creating, editing, deleting and setting the default site are owner only (no sidebar entry or Publishing card for others, 403 page on a direct link). Anyone who can edit an article can set its site and read the site list. Authors: owner and admin manage; other roles read-only, and any role can create and edit their own author (user link locked, no delete).
|
||||
- The site key is immutable: read-only with a lock in the edit form; the warning state and dialog are gone.
|
||||
- The "Author profile" card is drawn in every existing Profile frame. The "Site and authors" section shows collapsed in every existing Editor frame that has the details sidebar (39 already did; the Loading frame now shows the header with a skeleton summary). The Not found frame has no editor, and on mobile the section is inside the Details sheet. The dedicated groups keep only the feature-specific states.
|
||||
- Shared pieces (list, slide-over, delete-with-reassign dialog, slug field, media field) are defined once in `DirectoryFrame`, used by Sites and Authors. The Profile card is defined once in `AppFrame`.
|
||||
- States trimmed from 87 to 68 (Sites 9, Sites: form 7, Sites: delete 3, Authors 8, Authors: form 11, Authors: delete 6, Editor: site and authors 16, Profile: author profile 5, Articles: sites and authors 3). Dropped: in-progress and done variants (covered by the button loading pattern and the confirm state's trigger), per-error URL variants, the site picker (same picker as the avatar), manual slug override, long names (merged into Many authors), per-field duplicates. The blocked-delete dialog is one frame, "Server fallback (409)".
|
||||
- Only individual states that render a relative time or a countdown carry the "Clock-sensitive" tag (13 states, listed in states.md). No Home or Articles frame is tagged as a whole.
|
||||
- Role-restricted variants drawn: read-only Authors list and detail, hidden Sites entry, Sites 403, own-author edit.
|
||||
|
||||
## Specs
|
||||
routes.md · components.md · states.md · foundations.md · change-list.md · activity-spec.js · screens/*.md (22 files)
|
||||
routes.md · components.md · states.md · foundations.md · change-list.md · activity-spec.js · screens/*.md (24 files)
|
||||
|
||||
## Status
|
||||
| Section | Status |
|
||||
@@ -30,7 +42,7 @@ routes.md · components.md · states.md · foundations.md · change-list.md · a
|
||||
| B9 Media and picker | Badge added; Media pagination drawn (9 states); filter, sort and size not folded in |
|
||||
| B10 "proposed" labels | Only article pagination and JSON export |
|
||||
|
||||
## State counts (Back-office board: 341)
|
||||
## State counts (Back-office board: 341 before pass 3, plus 68 for sites and authors = 409)
|
||||
| Group | States |
|
||||
|---|---|
|
||||
| Boot | 1 |
|
||||
@@ -65,7 +77,7 @@ routes.md · components.md · states.md · foundations.md · change-list.md · a
|
||||
| Cache panel | 10 |
|
||||
| Editor picker | 5 |
|
||||
|
||||
Back-office total 341. Auth board 50 (Log in 9, Register 6, Pending 6, Verify 6, Accept invite 10, Forgot password 6, Reset password 7). API keys board 12. Total 403 states; every one has a desktop and a mobile frame, and the theme switch gives light and dark. The matrix has 24 control rows, 5 states on desktop and 4 on mobile (no hover). screens/*.md list exactly these 403.
|
||||
Back-office total 341 (pass 2 groups, table above) + 68 (sites and authors) = 409. Auth board 50 (Log in 9, Register 6, Pending 6, Verify 6, Accept invite 10, Forgot password 6, Reset password 7). API keys board 12. Total 471 states; every one has a desktop and a mobile frame, and the theme switch gives light and dark. The matrix has 24 control rows, 5 states on desktop and 4 on mobile (no hover). screens/*.md list the states of the pass 2 groups and the 68 pass 3 states.
|
||||
|
||||
## Fixes applied (pass 2)
|
||||
1. Activity export dialog: removed the 42% progress bar, the "large export" state, the server-job copy and the "ready later" toast; added "Preparing download…" (indeterminate), "Download started", failed, nothing to export, 403; CSV only, with one proposed JSON state.
|
||||
@@ -118,4 +130,5 @@ Back-office total 341. Auth board 50 (Log in 9, Register 6, Pending 6, Verify 6,
|
||||
- Contrast was not computed for every hover and active background, only the pairs listed in foundations.md.
|
||||
- The glossary pass was a search for known patterns, not a line-by-line read of every string. Titles in Title Case were not searched.
|
||||
- The Components, Handoff and Foundations boards were not updated to mention the new tokens, CodeSnippet or the matrix.
|
||||
- Integration still lists "max 10000" for article bodies, as the backend does today (change-list item 11).
|
||||
- The sandbox cannot export; no files were bundled.
|
||||
@@ -1,4 +1,64 @@
|
||||
# Change list for implementation (status after pass 2)
|
||||
# Change list for implementation (status after pass 2; SEO round drawn; cleanup round drawn)
|
||||
|
||||
## Cleanup round
|
||||
|
||||
1. Editor: site and authors, "Create author" states (4 states, desktop and mobile): the mobile dialog sat under the Details sheet (z-index 50 against 55) and was hidden. It now stacks above the sheet (z-index 60), as the SEO panel does. Full-width bottom sheet with grabber, same fields, Cancel left and "Create author" right (Cancel below on mobile, as the other mobile dialogs). Frame: `DirectoryFrame.dc.html`. The four states share the fix: dialog, "for me", slug taken, failed.
|
||||
2. Integration, "6. Errors": the 403 row gets the muted note "Site SEO defaults are owner only. Article SEO fields need only the right to edit the article." The row below shifts down by the wrapped note height (two 18 px lines desktop, three mobile, plus the 2 px row gap). The old inline parenthetical with the same sentence in the 403 cause text was removed, so it isn't said twice. Frame: `IntegrationPage.dc.html`.
|
||||
3. Integration, sitemap errors: 404 now shows the body `site_not_found` in code style (was "Site not found"); 400 now shows the generic body-mismatch text used by the other routes (was "Invalid page or size.").
|
||||
4. New groups on the Back-office board: "Sites: pagination" and "Authors: pagination", 10 states each (20 states, every one desktop and mobile; light and dark by the theme switch). Back-office total 409 → 429. Same pager as Articles and Media, sizes 5, 25, 50, 100, default 25 (no difference to report). One deviation: on a single page the page-size select is hidden and only "N sites" or "N authors" remains.
|
||||
5. Specs: screens/sites.md, screens/authors.md (pager states, URL rules, out-of-range fallback), screens/integration.md, states.md (pagination states, three HTTP rows), components.md (single-page variant, no new component), routes.md (Sites pagination in the URL).
|
||||
|
||||
**Backend assumptions to confirm.** GET /v1/site/ takes `q`, `page`, `size` and returns `X-Total-Count` (it returns every site today). GET /v1/author/ gets `page`, `size` and `X-Total-Count` (it has `q`).
|
||||
|
||||
**Open points.**
|
||||
- Sites has no search field. The two states that need one (empty after search, search resets to page 1) draw the Authors field on Sites with "Search by name or key". Drop those states if you don't want search on Sites.
|
||||
- Stale copy found, not changed: GET /v1/article/ on Integration still shows the 400 caption "Invalid page or size." while every other route, and now the sitemap, uses the body-mismatch text. The 404 row of the Errors table still lists only the four resource messages and doesn't mention `site_not_found`. The existing Sites and Authors "Default" frames don't draw the count line. README.md state counts and the "Pagination" notes were not updated (outside this round).
|
||||
|
||||
## SEO round: decisions (frames drawn)
|
||||
|
||||
**Placement.** A "Search and sharing" section sits under "Site and authors" in the Editor sidebar and in the mobile Details sheet. It is collapsed by default, shows a one-line summary ("Ready", "2 suggestions" or "Hidden from search") and is remembered per browser like Site and authors. It holds only the slug, the full URL and three actions: "Edit search and sharing", "What the frontend gets" and the suggestion list. The fields and live previews open in a slide-over (desktop) or a 92% bottom sheet stacked over the Details sheet (mobile), because the 280 px sidebar is too narrow for previews and the slide-over rule already covers forms with a live preview. The API preview is a 720 px dialog (desktop) or a bottom sheet (mobile).
|
||||
|
||||
**Principles.** RenewCMS does not render pages or inject meta tags. Every field is optional and the UI shows its fallback. No scores. Suggestions never block saving or publishing; publishing is allowed regardless. Suggestions are dismissible per article.
|
||||
|
||||
**Fallback chain (resolved server-side, shown in the UI).**
|
||||
| Output | Order |
|
||||
|---|---|
|
||||
| title | seo_title, then article title; site title_template applied last |
|
||||
| description | seo_description, then excerpt, then first sentence of the body, then site default_description |
|
||||
| image | og_image_id, then cover_image_id, then site social image |
|
||||
| canonical | canonical_url, then site base_url + "/" + slug |
|
||||
| robots | noindex true gives "noindex, nofollow"; otherwise site default_robots |
|
||||
| og/twitter title and description | social_title, social_description, then the resolved values above |
|
||||
|
||||
**Soft ranges (counters, never blocks).** Meta title 30–60 characters; description 70–160; slug "very long" above 75 characters. Counter turns neutral-warning (`--ui-warning`) outside the range, never red.
|
||||
|
||||
**New article fields (PATCH /v1/article/{id}, all optional, snake_case).** `slug`, `excerpt` (max 300), `seo_title` (max 120), `seo_description` (max 320), `cover_image_id`, `cover_image_alt` (max 200; the cover is "ready" only with alt text), `social_title`, `social_description`, `social_image_id`, `canonical_url` (absolute https URL), `noindex` (boolean; only sets a flag in the API, it doesn't change visibility), `seo_dismissed` (string[] of suggestion codes). Slug: lowercase letters, numbers, hyphens; unique per site; 409 `slug_taken` with `suggestion` ("<slug>-2"); auto-generated from the title until edited.
|
||||
|
||||
**New site fields (PATCH /v1/site/{id}, owner only).** `site_name`, `title_template` (default "%title% | %site%", must contain %title%), `default_description` (max 320), `social_image_id` (existing), `default_robots` ("index" | "noindex"; existing as robots).
|
||||
|
||||
**New endpoints.**
|
||||
- `GET /v1/article/{id}/seo`: resolved object, public for online articles, 404 for drafts to anonymous callers. Shape: `{ title, description, canonical_url, robots, og: { type, title, description, image, image_alt, url, site_name, locale }, twitter: { card, title, description, image, image_alt }, image: { url, alt, source }, authors: [{ name, url, same_as: [] }], published_at, modified_at, fallbacks: { title, description, image, canonical }, json_ld }`. `json_ld` is a ready Article object (headline, description, image, author[] with name, url and sameAs from author profile URL and social links, datePublished, dateModified, mainEntityOfPage).
|
||||
- `GET /v1/site/{key}/sitemap?page=&size=`: published URLs only, total in `X-Total-Count`. Items: `{ url, modified_at, noindex }`. Decision: yes, shown on Integration under "Search and sharing" with a copy button; noindex articles are included with the flag so the frontend can skip them.
|
||||
- `GET /v1/article/?seo=ready|suggestions|hidden`: filter behind "Needs attention" (suggestions) with `seo_status` and `seo_suggestions` (count) added to list items.
|
||||
|
||||
**Articles list.** Quiet indicator inside the Status cell (and under the title on mobile cards): nothing when ready, a lightbulb chip "N" for suggestions, an eye-off chip "Hidden" for noindex. Toolbar gets a "Needs attention" toggle next to search; tabs and counts are unchanged. It behaves the same on a single-site install (independent of the Site filter, which stays hidden).
|
||||
|
||||
**Authors.** No change to the Authors screen. Profile URL (website) and social links feed `authors[].url` and `same_as`, and JSON-LD `author[].sameAs`; the API preview shows them.
|
||||
|
||||
**Permissions.** Anyone who can edit an article edits its SEO fields. Only the owner edits site SEO defaults. 401 and 403 rows join the existing HTTP table: 403 `owner_only` on Site SEO fields, 401 on a missing session.
|
||||
|
||||
**Left out on purpose.** Keyword scoring and focus keywords, readability scores, redirects management, schema types beyond Article, hreflang, robots.txt and sitemap rendering (RenewCMS only provides data), automatic image generation for social cards.
|
||||
|
||||
**Open questions.**
|
||||
1. Is `slug` immutable after first publish, or can it change (and break URLs with no redirects)?
|
||||
2. Does the API return the SEO object for drafts to authenticated callers (for frontend previews)?
|
||||
3. Should noindex articles be excluded from the sitemap endpoint instead of flagged?
|
||||
4. Is title_template applied by the API (resolved title) or only returned for the frontend to apply?
|
||||
5. Backfill: generate slugs for existing articles from their titles at migration, with `-2` suffixes on conflicts?
|
||||
6. Should excerpt be exposed in the list payload as the article teaser?
|
||||
|
||||
**Status.** Frames drawn on the Back-office board (groups: Articles: search status, Editor: search and sharing, Editor: what the frontend gets, Sites: SEO defaults), Integration page group added, specs updated. Placement rationale: the sidebar holds only the summary, address and suggestions because it is 280 px wide; previews and fields need a slide-over.
|
||||
|
||||
|
||||
Ordered by implementation dependency: tokens and shell first, then shared components, then screens. "Frontend only" means no backend work is needed.
|
||||
|
||||
@@ -25,3 +85,9 @@ Ordered by implementation dependency: tokens and shell first, then shared compon
|
||||
| 18 | All | States matrix for controls (hover, focus-visible, active, disabled) | Yes (board "States matrix: controls") | No | None | Yes |
|
||||
| 19 | All | Contrast fixes: paginator current page border, no muted text on sand | Yes | No | None | Yes |
|
||||
| 20 | All | Spacing, type and icon sizes made consistent (foundations.md, "One value per role") | Yes in the frames listed there | No | None | Yes |
|
||||
| 21 | Settings, sidebar | Sites screen under Settings → Sites ("Publishing" group); "Publishing" card on Settings. Owner only: hidden for other roles, 403 page on a direct link. Key immutable after creation | Yes | **Yes:** `site` table, GET/POST/PATCH/DELETE /v1/site/ (writes owner only; PATCH rejects a changed key), `reassign_to`, seed from PUBLIC_URL | SitesTable, SiteForm, SlugField (locked variant), ReassignDialog | No |
|
||||
| 22 | Sidebar | Authors entry between Media and Users, all roles. Owner and admin manage; other roles read-only list and detail | Yes | **Yes:** `author` table, GET /v1/author/ (any role), POST/PATCH/DELETE (owner and admin; a user may PATCH their own linked author), POST /v1/author/me (any role) | AuthorsTable, AuthorForm, SocialLinksRepeater, MediaField | No |
|
||||
| 23 | Editor | "Site and authors" section in every Editor frame (collapsed by default): Site select (any role that can edit the article), reorderable authors, inline create (owner and admin), hint | Yes | **Yes:** `site_id`, `author_ids[]` on PATCH /v1/article/{id} | MetaSection, AuthorList, AuthorSelect, SiteSelect, CreateAuthorHint | No |
|
||||
| 24 | Articles | Authors column; Site column and filter when more than one site | Yes | **Yes:** `site` filter, `site` and `authors` in the list payload | AuthorStack | No |
|
||||
| 25 | Profile | "Author profile" card in every Profile frame, one-click create, edit own author (user link locked) | Yes | **Yes:** POST /v1/author/me | AuthorProfileCard | No |
|
||||
| 26 | Backfill | Existing articles get the default site; authors start empty | n/a | **Yes:** migration | None | No |
|
||||
@@ -33,7 +33,9 @@ One component for every code or copyable value. Props: `tabs` (`{ k, label, code
|
||||
- **Toolbar at 390 px**: the full toolbar (22 buttons) does not fit. It scrolls sideways in one row, never wraps; a 24 px fade (`--ui-bg` to transparent) marks hidden content on each side. Buttons stay 40 px.
|
||||
|
||||
## Paginator
|
||||
First, previous, page numbers, next, last; "Showing 26–50 of 312"; page-size select "5 per page", "25 per page", "50 per page", "100 per page" (default 25). Mobile: previous, "Page 2 of 13", next. Hidden when there is one page. Buttons 32 px (44 px mobile), current page `--rc-sand` with `--ui-primary` border, disabled controls 40% opacity, focus ring 2 px `--ui-primary`. Page size and page live in the URL as `size` and `page`.
|
||||
First, previous, page numbers, next, last; "Showing 26–50 of 312"; page-size select "5 per page", "25 per page", "50 per page", "100 per page" (default 25). Mobile: previous, "Page 2 of 13", next. Hidden when there is one page. Desktop layout, one row: the summary on the left (it takes the free space), the page-size select next to it, the page controls right-aligned; Sites, Authors, Articles and Media draw it the same way. Buttons 32 px (44 px mobile), current page `--rc-sand` with `--ui-primary` border, disabled controls 40% opacity, focus ring 2 px `--ui-primary`. Page size and page live in the URL as `size` and `page`.
|
||||
|
||||
Variant for Sites and Authors (no new component): when everything fits on one page the page-size select is hidden together with the controls and the footer shows only the count line "N sites" or "N authors" in `--ui-text-muted`. Loading dims the whole pager to 40% and disables it; the summary reads "Loading page N…". Sizes are unchanged: 5, 25, 50, 100.
|
||||
|
||||
## Activity export
|
||||
Menu: "Export current view" (CSV, active filters, all pages) and "Export all activity…" (CSV, ignores filters; owner and admin only). Dialog: Format (read-only "CSV"; a CSV and JSON control appears when JSON ships, proposed), Date range (default "All time"). States: configure, "Preparing download…" (indeterminate bar, no percentage, Cancel left, "Preparing…" disabled right), "Download started" (Close), "Couldn't prepare the download" (Cancel, Retry), "Nothing to export" (Close), 403 "You can't export all activity" (Close). Synchronous: no job, no progress, no later notification.
|
||||
@@ -52,3 +54,38 @@ Row 32 px (44 px in the mobile drawer). Parent selected: `--rc-sand`, `--rc-on-s
|
||||
- **MediaCleanupCard**: square `USwitch`, `UInputNumber` with "days" suffix, saves on change.
|
||||
- **MediaLinksCard**: rows "Manage image variants" and "Cache usage", 44 px min height.
|
||||
- **StatesMatrix**: the board "States matrix: controls".
|
||||
|
||||
## Sites and authors (pass 3)
|
||||
|
||||
Frames: `DirectoryFrame.dc.html` (Sites, Authors, editor section content; the list, slide-over, delete-with-reassign dialog, slug field and media field are defined once there and used by both Sites and Authors); `AppFrame.dc.html` changed in place (sidebar items, Articles columns and filter, editor section and mobile details sheet, Settings card, Profile card, role-based sidebar). Existing components are reused unchanged: dialogs, toasts, empty states, skeletons, paginator, media picker.
|
||||
|
||||
| Component | Status | Nuxt UI | Notes |
|
||||
|---|---|---|---|
|
||||
| SitesTable, AuthorsTable | New | UTable; below 640 px a list of UCard | Same row heights as Users. Defined once as DirectoryList in DirectoryFrame and used by both. Read-only variant has no actions, chevron instead of the menu |
|
||||
| SiteForm, AuthorForm | New | USlideover + UForm, UFormField, UInput, UTextarea, URadioGroup, USwitch | Sheet on mobile. Close with changes opens the discard UModal |
|
||||
| SlugField | New | UInput + UButton (icon) + UBadge | Defined once in DirectoryFrame. Auto badge, pencil, "Reset to match the name". Locked read-only variant (lock icon, "Used in API paths, so it can't change.") for the site key after creation |
|
||||
| SocialLinksRepeater | New | USelect + UInput + UButton, in UFormField | Max 5 rows. Placeholder follows the type |
|
||||
| MediaField | New | UButton + UModal (existing picker) | Defined once in DirectoryFrame. Used for the social image and the avatar |
|
||||
| AuthorViewPanel | New | USlideover, read-only | Detail for roles without author rights. Close is the only action |
|
||||
| AuthorAvatar | New | UAvatar | Initials fallback, square, radius 0 |
|
||||
| AuthorStack | New | UAvatarGroup max=3 | Shows "+N" |
|
||||
| AuthorList | New | List of UButton, UAvatar, UBadge; sorting with useSortable | No Nuxt UI match for sortable rows. Keyboard reordering is custom |
|
||||
| AuthorSelect | New | USelectMenu multiple with create-item | Footer item "Create author…" opens the dialog |
|
||||
| SiteSelect | New | USelectMenu | Item slot shows name and host |
|
||||
| UserSelect | New | USelectMenu | Only users without an author |
|
||||
| ReassignDialog | New | UModal + USelectMenu + UAlert | Defined once in DirectoryFrame. Used for site and author deletion |
|
||||
| MetaSection | New | UCollapsible | Desktop sidebar and mobile sheet. Site select for anyone who can edit the article. No "Create author…" row without author rights |
|
||||
| AuthorProfileCard | New | UCard + UButton + UAlert | Profile screen. Defined once in AppFrame; every Profile frame shows it |
|
||||
| CreateAuthorHint | New | UAlert closable | Dismissal stored per user |
|
||||
| Default badge, Linked badge, Guest badge | New | UBadge | Sand fill, info soft fill, outline |
|
||||
| Row menu with a disabled item | Existing + change | UDropdownMenu + UTooltip | The item stays focusable |
|
||||
| SearchSharingSection | New | UCollapsible + UButton + USeparator | Editor sidebar and Details sheet, after Site and authors. Summary: Ready, N suggestions, Hidden from search, Checking… |
|
||||
| SeoPanel | New | USlideover (desktop 960 px) / bottom sheet (mobile) + UFormField, UInput, UTextarea, USwitch, UCollapsible | Defined once in DirectoryFrame. Reuses SlugField, MediaField and the picker. Fallback chip: dashed outline, "Using …" |
|
||||
| SoftCounter | New | text | Mono, "n / max". Amber (--ui-warning) outside the recommended range, never red, never blocks |
|
||||
| SearchPreview | New | UCard | Desktop and Mobile toggle (UTabs, 2 items). Title cut at 60 (desktop) or 70 (mobile) characters including the template, description at 160 or 120 |
|
||||
| SocialCardPreview | New | UCard | 1.91:1 image, host, title, 2-line description; fallback chips |
|
||||
| SuggestionList | New | UAlert-style rows + UButton (link, ghost icon) | Calm elevated block. States: list, all good, checking. Per-article dismiss; "Show dismissed" |
|
||||
| ApiPreviewDialog | New | UModal / bottom sheet + UTabs + UButton + UAlert | Formatted and Raw; Copy JSON; loading, error, draft note |
|
||||
| SeoStatusChip | New | UBadge | Lightbulb + count (warning soft) or eye-off "Hidden" (outline). Articles rows and cards |
|
||||
| NeedsAttentionToggle | New | UButton (pressed state) | Articles toolbar, sand when on |
|
||||
| TitleTemplateField | New | UInput + live example | Sites form |
|
||||
@@ -10,6 +10,11 @@
|
||||
| /articles | Articles list | page, size, tab, q | GET /v1/article/?page=&size=&q=&status= (page, size; total in the `X-Total-Count` header; array body unchanged) |
|
||||
| /activity | Activity | q, actor, category, outcome, security, range, from, to, page, size | GET /v1/activity (page, size), GET /v1/activity/export (shipped, CSV) |
|
||||
| /integration | Integration | none | none |
|
||||
| /settings/sites | Sites (owner only; other roles get a 403 page and no sidebar entry): list, add and edit slide-over, delete with reassignment. The key is read-only after creation | none | GET/POST /v1/site/, PATCH/DELETE /v1/site/{id} (DELETE takes `reassign_to`) |
|
||||
| /authors | Authors, all roles. Owner and admin: list, search, add and edit slide-over, delete with reassignment. Other roles: read-only list and detail | q, page, size | GET/POST /v1/author/, PATCH/DELETE /v1/author/{id}, POST /v1/author/me |
|
||||
| /articles | Articles list gains Authors column; Site column and filter when more than one site | site | GET /v1/article/?site={key} |
|
||||
| /article/:id/edit | Editor gains the "Site and authors" section (Site select and authors, any role that can edit the article) | none | PATCH /v1/article/{id} {site_id, author_ids[]} |
|
||||
| /profile | Profile gains the "Author profile" card, all roles | none | POST /v1/author/me |
|
||||
| /integration/api-keys | API keys | none | GET/POST /v1/api-key, DELETE /v1/api-key/{id} |
|
||||
|
||||
## Pagination in the URL (Articles, Media)
|
||||
@@ -30,3 +35,11 @@
|
||||
|
||||
## Public image request
|
||||
`/media/photo.png?v=<variant-name>`. Unknown or disabled variant: 400 `{ "status": 400, "error": "unknown_variant", "message": "Unknown variant", "detail": "<name>" }`. Any other query parameter: 400 `{ "status": 400, "error": "unsupported_parameter", "message": "Unsupported parameter", "detail": "<parameter>" }`. Missing source image: 404.
|
||||
|
||||
## Sites and authors in the URL
|
||||
`/articles?site=journal` filters by site key; it combines with `page`, `size`, `tab` and `q`, and resets `page` to 1 when it changes. An unknown key is dropped from the URL with no error. `/authors?q=camille&page=2&size=25` follows the same pagination rules as Articles. Deep links: `/authors?edit={slug}` and `/settings/sites?edit={key}` open the slide-over for owner and admin (authors) and the owner (sites); an unknown value shows the info toast "That author no longer exists" or "That site no longer exists". For other roles `/authors?edit={slug}` opens the read-only detail, and `/settings/sites` and its `?edit=` link show the 403 page "You don't have access to Sites".
|
||||
|
||||
Sites pagination: `/settings/sites?q=&page=&size=` with the same rules as Articles (sizes 5, 25, 50, 100; default 25; defaults omitted; search and size changes reset to page 1; a page past the end falls back to the last page). API: GET /v1/site/?q=&page=&size=, total in `X-Total-Count` (design assumption). Authors: `/authors?q=&page=&size=` as above.
|
||||
|
||||
## SEO
|
||||
No new page routes. The panel and dialog are overlays on `/article/:id/edit`: `?panel=seo` (optionally `&field=seo_title|seo_description|slug|cover|authors|body` for the suggestion jump) and `?dialog=seo-api`. `/articles?seo=suggestions` is the Needs attention filter. API: GET /v1/article/{id}/seo, GET /v1/site/{key}/sitemap?page=&size=, PATCH /v1/article/{id} (new fields), PATCH /v1/site/{id} {site_name, title_template, default_description, social_image_id, default_robots}, GET /v1/article/?seo=ready|suggestions|hidden. 401 without a session; 403 owner_only on site SEO fields; 409 slug_taken {suggestion} on PATCH slug; 400 on invalid canonical_url or title_template.
|
||||
@@ -42,7 +42,7 @@ Rows update when the server responds, not optimistically. Search, tab and sort a
|
||||
| 5 | No results | Search matched nothing. The tab counts still show the full list. | "No articles match "tiles"" / "Check the spelling, or search for a shorter part of the title." / "Clear search" |
|
||||
| 6 | No drafts | Drafts tab with nothing in it. The "Online" tab has an equivalent "Nothing is online yet" state. | "Everything you've written is online." / "New article" |
|
||||
| 7 | Action in progress | Publish chosen from the row menu. That row is disabled. | "Publishing…" |
|
||||
| 8 | Published | 200: the row updates in place and a toast confirms. | "Just now" / "Article published" / ""Winter checklist for timber windows" is now online." |
|
||||
| 8 | Published | 200: the row updates in place and a toast confirms. Clock-sensitive: shows a relative time or a countdown. | "Just now" / "Article published" / ""Winter checklist for timber windows" is now online." |
|
||||
| 9 | Action failed | A 500 or network error. The row stays as it was, and the toast stays until retried or dismissed. | "Couldn't unpublish" / "The server didn't respond. Nothing changed." / "Retry" |
|
||||
| 10 | Row vanished (404) | Any row action gets a 404. | "That article no longer exists" / "It was deleted somewhere else, so we removed it from the list." |
|
||||
| 11 | Delete: confirm | Delete… from the row menu. | |
|
||||
@@ -69,3 +69,33 @@ Page and page size live in the URL as page and size. Defaults (page 1, size 25)
|
||||
| 9 | Empty after search | Zero results. Paginator and summary are hidden. | "No articles match "tiles"" / "Check the spelling, or search for a shorter part of the title." / "Clear search" |
|
||||
| 10 | Page size menu | The select opens upward. 5, 25, 50 or 100; the chosen size is saved as size and the page resets to 1. | |
|
||||
| 11 | Focus-visible | Keyboard focus on Next: 2 px --ui-primary outline, 2 px offset. Same ring on every paginator control. | |
|
||||
|
||||
## Changed in pass 3: authors, site column and site filter
|
||||
|
||||
### Articles: sites and authors (group "Articles: sites and authors", 3 states)
|
||||
|
||||
Route: `/articles?site=journal`. API: GET /v1/article/?site={key}&page=&size=&q=&status=.
|
||||
|
||||
Every Articles frame has the Authors column (avatars, at most 3 plus "+N"; "—" when none; on mobile avatars with the first name). When more than one site exists, a Site column and a Site filter appear, read-only text for every role; with one site they are not rendered.
|
||||
|
||||
| # | State | Trigger | Copy |
|
||||
|---|---|---|---|
|
||||
| 1 | Several sites | More than one site exists. | Authors · Site · All sites · Renew · Journal · Projects |
|
||||
| 2 | Site filter open | The Site select in the toolbar. Choosing a site stores ?site=key and resets the page to 1. | All sites · Renew · Journal · Projects · Archive |
|
||||
| 3 | No articles on a site | The chosen site has no articles. | No articles on "Archive" · Move articles here from the editor, or choose another site. · Show all sites |
|
||||
|
||||
All existing Articles frames show the Authors column (avatars, at most 3 plus "+N", "—" when none).
|
||||
|
||||
## Articles: search status (SEO round)
|
||||
|
||||
Route: `/articles?seo=suggestions`. API: GET /v1/article/?seo=suggestions&page=&size= (items carry seo_status and seo_suggestions).
|
||||
|
||||
A quiet indicator in the Status cell on desktop and under the title on mobile cards: a lightbulb chip with a count when there are suggestions, an eye-off chip "Hidden" when noindex is on, nothing when the article is ready. The toolbar gets a "Needs attention" toggle with a count next to the search field. Tabs and their counts are unchanged. On a single-site install nothing changes: the Site filter and column stay hidden and the toggle works the same, over all articles.
|
||||
|
||||
| # | State | Trigger | Copy |
|
||||
|---|---|---|---|
|
||||
| 1 | Status chips | Row 2 has 2 suggestions, row 3 is hidden, row 4 has 3, row 5 has 1. | Needs attention · 3 · Hidden · 2 suggestions (tooltip) · Hidden from search engines (tooltip) |
|
||||
| 2 | Needs attention on | The toggle is pressed. The list shows only articles with suggestions. Hidden-only articles are not included. | Needs attention · 3 |
|
||||
| 3 | Needs attention: none | Nothing to show with the toggle on. | Nothing needs attention · Every article has a clean check. Suggestions are optional, so this is just a bonus. · Show all articles |
|
||||
|
||||
Filter: "Needs attention" sets `?seo=suggestions` and resets `page` to 1. Tab counts do not change. Single-site installs behave the same; the Site filter stays hidden.
|
||||
@@ -0,0 +1,82 @@
|
||||
|
||||
# Authors
|
||||
|
||||
Route: `/authors`. API: GET /v1/author/ · POST /v1/author/ · PATCH /v1/author/{id} · DELETE /v1/author/{id}?reassign_to={id|none} · POST /v1/author/me.
|
||||
|
||||
An author is a public byline, not an account. It may be linked to one CMS user; guest writers have no link. The slug is globally unique, generated from the name and editable. An article has zero or more authors in a set order; the first is the primary byline. Zero authors is allowed.
|
||||
|
||||
**Roles.** Owner and admin can create, edit and delete any author. Other roles see the Authors screen read-only: the list and a read-only detail, with no Add author button, no row menu, no slide-over form and no delete. They can pick authors in the article editor. Any role can use "Create my author profile" and edit their own linked author: the form opens with the linked user locked and has no delete action.
|
||||
|
||||
**Shared pieces.** The list, slide-over, delete-with-reassign dialog, slug field and media field are defined once in `DirectoryFrame.dc.html` and referenced by both Authors and Sites. The media picker is drawn once, in "Authors: form". The server-fallback 409 dialog is drawn once, in "Authors: delete".
|
||||
|
||||
Visual reference: `RenewCMS Screens Back-office.dc.html`, groups "Authors", "Authors: form", "Authors: delete". Every state is drawn in light and dark (theme switch) at 1440×900 and 390×844. Copy is exact. Strings in a Copy cell are separated by " · " and listed in reading order.
|
||||
|
||||
### Authors (group "Authors", 8 states)
|
||||
|
||||
Sidebar entry between Media and Users, visible to every role. Owner and admin create, edit and delete any author. Other roles see the list and the detail read-only. Columns: avatar and name, slug, account (Linked or Guest), article count. Search by name or slug. Long names truncate in the row and show in full on hover. Above 25 authors the list uses the same paginator as Articles; its states are drawn in "Authors: pagination". List, panel and dialogs come from DirectoryFrame and are shared with Sites.
|
||||
|
||||
| # | State | Trigger | Copy |
|
||||
|---|---|---|---|
|
||||
| 1 | Default | Owner or admin. The list loaded, newest first. | Authors · The names readers see on your articles. An author doesn't need an account. · Add author · Search by name or slug · Author · Slug · Account · Articles · Linked · Guest · 9 articles · 1 article · No articles |
|
||||
| 2 | Loading | The first load, or a retry. | |
|
||||
| 3 | Error | 500 or network failure. | Couldn't load authors · Check your connection and try again. · Try again |
|
||||
| 4 | Empty, first run | Zero authors. Toolbar hidden, one call to action. Other roles see the same text without the button. | No authors yet · Authors are the names readers see on articles. They don't need an account. · Add author |
|
||||
| 5 | No results | Search matched nothing. | No authors match "zoe" · Check the spelling, or search for a shorter part of the name. · Clear search |
|
||||
| 6 | Row menu | Owner or admin. The ellipsis button. Mobile: bottom sheet. | Edit · Delete… |
|
||||
| 7 | Read-only list (other roles) | Any role except owner and admin. No Add author button, no row menu and no bottom button on mobile. Search still works. A row opens the read-only detail. | Authors · The names readers see on your articles. Only an owner or admin can change authors. · Search by name or slug · Author · Slug · Account · Articles |
|
||||
| 8 | Read-only detail | A row was opened by a role without author rights. Same panel width as the form, no fields, Close as the only action. The account email is not shown. | Inès Duarte · Linked · 9 articles · Bio · Website · Only an owner or admin can change this author. · Close |
|
||||
|
||||
### Authors: add and edit (group "Authors: form", 11 states)
|
||||
|
||||
Owner and admin. A slide-over, because the form has a live preview (the byline). Fields: avatar (media picker), name, slug (auto, editable), bio with counter, website, social links (X, LinkedIn, GitHub, Mastodon, Custom; up to 5), linked user (only users without an author). Slug field, media field and picker are the shared ones from DirectoryFrame. Saving shows "Saving…" in the button, as in the other forms.
|
||||
|
||||
| # | State | Trigger | Copy |
|
||||
|---|---|---|---|
|
||||
| 1 | Add: empty | "Add author". Owner or admin. | Add author · Avatar (optional) · Choose image · Name · e.g. Camille Roche · Slug · Generated from the name · Bio (optional) · A sentence or two about the author. · 0 / 280 · Website (optional) · https://example.com · Social links (optional) · Add link · 0 of 5 · Linked user (optional) · No linked user · Link a CMS user if this author has an account. Guest writers need no link. · Byline preview · Author name · The bio appears here. · Cancel · Add author |
|
||||
| 2 | Slug from the name | Typing a name fills the slug. Auto badge and "Edit slug" pencil. | camille-roche · Auto · Generated from the name. Used in public author URLs and API paths. Unique across all authors. |
|
||||
| 3 | Slug collision | 409 on submit, or on blur after a check. | The slug "camille-roche" is already used by another author. · Use camille-roche-2 · Reset to match the name |
|
||||
| 4 | Validation | On submit or blur. Nothing is sent. | Enter a name. · Shorten the bio to 280 characters. · 291 / 280 · Enter a full URL starting with https://. |
|
||||
| 5 | Social links | Add link adds a row with a type select and a URL. One link is invalid. | X · LinkedIn · GitHub · Mastodon · Custom · https://x.com/username · https://www.linkedin.com/in/username · https://github.com/username · https://mastodon.social/@username · https://example.com · Enter a full URL starting with https://. · You can add up to 5 links. |
|
||||
| 6 | Linked user: choose | The select is open. Only users without an author. When none are left it reads "Every user already has an author." | Choose a user · Users without an author · Marta Alves · marta@renew.example · Rui Santos · rui@renew.example |
|
||||
| 7 | Edit: linked author | Edit on an author linked to a user. | Edit Inès Duarte · Linked user (optional) · ines.duarte@renew.example · Unlink · New articles by this user start with this author. · Save changes |
|
||||
| 8 | Avatar: picker | "Choose image". The existing media picker; shown as a square. The site social image uses this same picker. | Choose an image · The avatar for Camille Roche. · Shown as a square. Choose an image with the face or logo near the middle. · Use image |
|
||||
| 9 | Save failed | 500 or network failure. | Couldn't save the author. Your changes are still here. Try again in a moment. |
|
||||
| 10 | Unlink: confirm | "Unlink" next to the linked user, owner or admin. On 200 the field returns to "No linked user" and a toast reads "User unlinked" · "Inès Duarte is now a guest author." | Unlink Inès Duarte? · Inès Duarte will stay on their articles. New articles by ines.duarte@renew.example will no longer start with this author. · Cancel · Unlink user |
|
||||
| 11 | Re-link | "Link user" on a guest author in the row menu or the form. Same list as above. | Link Camille Roche to a user? · Only users without an author are listed. · Cancel · Link user |
|
||||
|
||||
### Authors: delete (group "Authors: delete", 6 states)
|
||||
|
||||
Owner and admin. Reassign: the dialog asks who gets the articles, with "Nobody" as the last option, and shows the count in the button. Zero authors are allowed, so Nobody is always valid. The 409 dialog is the server fallback and is drawn once.
|
||||
|
||||
| # | State | Trigger | Copy |
|
||||
|---|---|---|---|
|
||||
| 1 | Reassign (recommended) | "Delete…" on an author with articles, owner or admin. The button reads "Reassigning…" while the request runs. On 204 a toast reads "Author deleted" · "3 articles now credit Inès Duarte." A linked author also shows "Linked to ines.duarte@renew.example. The user account isn't affected." | Delete this author? · "Camille Roche" will be deleted and is credited on 3 articles. This can't be undone. · Credit these articles to · Inès Duarte · Where an article has several authors, Camille Roche is removed and the others stay. · Cancel · Delete and reassign 3 articles |
|
||||
| 2 | Choose who | The select is open. The deleted author is not listed. | Nobody · Remove the byline |
|
||||
| 3 | Nobody | "Nobody" chosen. | The articles keep any other authors. Articles with only this author will have no byline. |
|
||||
| 4 | Failed (shared by site and author delete) | 500 or network failure. Both delete dialogs use this notice. | Couldn't delete the author · Nothing was changed. Try again in a moment. |
|
||||
| 5 | Server fallback (409) | Fallback only. The dialog above always sends reassign_to, so this appears only when the server refuses a stale request because articles still credit the author. Drawn once, not as a flow. | Can't delete this author · "Camille Roche" is credited on 3 articles. Choose another author to credit instead, or remove Camille Roche from those articles first. · Close · Reassign articles |
|
||||
| 6 | No articles | An author with zero articles: plain confirm. | Delete this author? · "Léa Fontaine" will be deleted. No articles credit this author. This can't be undone. · Delete author |
|
||||
|
||||
### Authors: pagination (group "Authors: pagination", 10 states)
|
||||
|
||||
Route: `/authors?page=3&size=50`. API: GET /v1/author/?q=&page=&size= (total in `X-Total-Count`, array body unchanged; `q` already exists). Owner, admin and read-only roles see the same pager. Drawn with 128 authors (6 pages) and generated rows.
|
||||
|
||||
**URL.** `/authors?page=2&size=50`. `page` and `size` are the parameter names (as Articles and Activity). `size` is one of 5, 25, 50, 100; default 25. Defaults are omitted from the URL (`page=1`, `size=25`). Combined with search: `/authors?q=mar&page=2`. A search change or a size change resets `page` to 1 and drops it from the URL. An invalid `size` or `page` (not a positive integer) is replaced silently by the default with `history.replace`. A `page` past the last page falls back to the last page: the URL is replaced by `?page=<last>` and the info notice "That page doesn't exist. Showing the last page." is shown, as on Articles. Browser Back returns to the previous page of results.
|
||||
|
||||
**Pager.** The same component as Articles and Media, in the same footer position (below the list, summary on the left, page-size select next to it, right-aligned controls; mobile: summary and select on one row, then Previous, "Page X of Y", Next). Nothing new is drawn. Sizes are the sizes of the existing pattern: 5, 25, 50, 100 (default 25). API: total in `X-Total-Count`, array body unchanged. Keyboard and aria as Articles. The only difference from Articles: on a single page the page-size select is hidden too and the footer holds only the count line "N authors" (Articles keeps its summary and select). Existing frames of this screen that show a short list (the "Default" frames above) don't draw the count line yet; it appears whenever the list has loaded.
|
||||
|
||||
| # | State | Trigger | Copy |
|
||||
|---|---|---|---|
|
||||
| 1 | First page | /authors. Previous and First are disabled (40% opacity, aria-disabled). Mobile: Previous disabled. | Showing 1–25 of 128 · 25 per page · Page 1 of 6 |
|
||||
| 2 | Middle page | /authors?page=3. Current page uses --rc-sand and --rc-on-sand with a --ui-primary border; ellipses mark skipped ranges once there are more than 7 pages. | Showing 51–75 of 128 · Page 3 of 6 |
|
||||
| 3 | Last page | /authors?page=6. Next and Last are disabled. | Showing 126–128 of 128 · Page 6 of 6 |
|
||||
| 4 | Single page | Everything fits on one page (6 authors). The pager and the page-size select are hidden; the count line stays in the footer position. Zero results use state 8 instead. | 6 authors |
|
||||
| 5 | Page size menu | The select opens upward. Sizes are the Articles sizes: 5, 25, 50, 100; default 25. The chosen size is saved as size and the page resets to 1. | 5 per page · 25 per page · 50 per page · 100 per page |
|
||||
| 6 | Loading a page | Next, Previous, a page number or a size change was used. The rows are replaced by the existing skeleton rows (8 desktop, 6 mobile). The pager stays and is disabled (40% opacity, not focusable); the summary reads "Loading page 4…" and the page number shown is still 3. | Loading page 4… |
|
||||
| 7 | Error loading a page | 500 or network failure on a page change. The rows of page 3 stay, the pager keeps "Page 3", and the inline error with Retry sits above the pager. Retry repeats the request for page 4. | Couldn't load page 4. Showing page 3. · Check your connection and try again. · Retry |
|
||||
| 8 | Empty after search | A search matched nothing. The existing empty state replaces the list; no pager, no count. Clear search returns to /authors and page 1. | No authors match "zoe" · Check the spelling, or search for a shorter part of the name. · Clear search |
|
||||
| 9 | Search resets to page 1 | Searching "mar" from page 5 goes to /authors?q=mar (page omitted). Any search change, and any size change, resets the page to 1. | Showing 1–25 of 31 |
|
||||
| 10 | Long labels on mobile | A large total on a 390 px screen. The summary and the page-size select share one row and wrap onto two if needed; Previous, the "Page 12 of 52" label and Next stay on one row (the two buttons flex, the label never wraps). Totals over 999 use thousands separators in both labels. | Showing 276–300 of 1,284 · Page 12 of 52 |
|
||||
|
||||
## SEO round
|
||||
No change to the Authors screen. Name, profile URL (website) and social links feed `authors[].name`, `authors[].url`, `authors[].same_as` and the JSON-LD author (`sameAs`) in GET /v1/article/{id}/seo. They are visible in the editor's "What the frontend gets" dialog.
|
||||
@@ -96,3 +96,82 @@ On mobile, Save and Publish sit in a sticky bottom bar and the details panel ope
|
||||
| 39 | Leave with unsaved changes | Back, a nav link or closing the tab. | "Leave without saving?" / "Your changes to "How we price a bathroom renovation" haven't been saved." / "Discard changes" / "Keep editing" |
|
||||
| 40 | Offline | The connection dropped. Writing continues, and Save and Publish wait. | |
|
||||
| 41 | Not found (404) | Unknown id, or the article was deleted elsewhere. | |
|
||||
|
||||
## Changed in pass 3: site and authors
|
||||
|
||||
Every existing Editor frame that has the details sidebar shows the "Site and authors" section collapsed, as the SPA renders it: one summary line ("Inès Duarte") because the install has one site and the article has an author, so there is no Site select. In the Loading frame the header is shown with a skeleton summary. The Not found frame has no editor, so it has no section. On mobile the section lives in the Details sheet, closed by default, so the mobile editor frames do not show it until the sheet is opened. The group below holds only the states specific to the feature.
|
||||
|
||||
### Editor: site and authors (group "Editor: site and authors", 16 states)
|
||||
|
||||
Route: `/article/:id/edit`. API: PATCH /v1/article/{id} {site_id, author_ids[]} · GET /v1/site/ · GET /v1/author/ · POST /v1/author/.
|
||||
|
||||
States specific to this feature. The collapsed default (one site, the article has an author) and the Loading and Not found states are drawn in the existing Editor frames, which show the section in the same place; they are not repeated here. The section is open when the install has more than one site or the article has no authors, and collapsed to one summary line otherwise; the choice is remembered per browser. On mobile it is closed by default. With one site the Site select is not rendered. Anyone who can edit the article can set its site and pick authors; "Create author…", the Create author dialog and its "This is me" checkbox are for owner and admin only. For any other role, the "Create my author profile" hint (state 4) creates the profile directly with POST /v1/author/me, with no dialog, then shows the author in the list with a toast. Authors are a reorderable list; the first is the primary byline.
|
||||
|
||||
| # | State | Trigger | Copy |
|
||||
|---|---|---|---|
|
||||
| 1 | Open: one site, one author | The section was opened. No Site select. | Authors · Add an author |
|
||||
| 2 | Open: several sites | Site select above the authors, with the canonical host as helper text. | Site · Journal · journal.renew.example · Canonical host: journal.renew.example |
|
||||
| 3 | Site select open | The select is open. Options show name and host; the default site is first. | Renew · renew.example · Journal · journal.renew.example · Projects · Archive |
|
||||
| 4 | No authors, with hint | The article has no authors and the user has no author profile. The hint is dismissible and does not return once dismissed. "Create my author profile" creates the profile directly for every role (POST /v1/author/me, no dialog), then the author appears in the list and a toast confirms. | You don't have an author profile yet · Create one to be credited on your articles. · Create my author profile · No authors. This article will have no byline. |
|
||||
| 5 | Many authors | Four authors. The first shows "Primary". Each row has a drag handle and a remove button. Long names truncate with an ellipsis and carry the full name in title and aria-label. | Primary · Drag to reorder. The first author is the primary byline. · Dr. Alexandra Konstantinopoulou-Whitfield |
|
||||
| 6 | Add author: open | The Add an author combobox is open. Authors already on the article are checked and dimmed. "Create author…" is shown only to owner and admin. | Search authors · Create author… |
|
||||
| 7 | Add author: no match | Typing a name that matches nobody. "Create author…" is shown only to owner and admin. | No author matches "Zoe Lambert". · Create author "Zoe Lambert"… |
|
||||
| 8 | Add author: open (no create) | A role without author rights. The combobox lists the authors with no "Create author…" row, because that row is shown only to owner and admin. | Search authors |
|
||||
| 9 | Add author: no match (no create) | A role without author rights types a name that matches nobody. Only the message shows; there is no create link, because "Create author…" is shown only to owner and admin. | No author matches "Zoe Lambert". |
|
||||
| 10 | Add author: error | GET /v1/author/ failed. The article keeps its authors. | Couldn't load authors · Check your connection and try again. · Try again |
|
||||
| 11 | Reorder: keyboard | Space or Enter on the handle grabs the row. Arrow keys move it. | Jonas Pereira grabbed. Position 2 of 3. Use the up and down arrow keys to move, Space to drop, Escape to cancel. |
|
||||
| 12 | Reorder: pointer | Dragging a row. The row lifts and a line shows the drop position. | |
|
||||
| 13 | Create author: dialog | "Create author…" in the dropdown, owner and admin only. The writer stays in the editor. | Create author · Adds a byline for this article. You can add a bio and avatar later in Authors. · Name · Slug · Zoe Lambert · zoe-lambert · Cancel · Create author |
|
||||
| 14 | Create author: for me | Owner and admin only. When the user has no author profile, a checkbox links the new author to them. | This is me · Links the author to marta@renew.example. |
|
||||
| 15 | Create author: slug taken | The slug exists. The dialog suggests a free one. | The slug "zoe-lambert" is already used by another author. · Use zoe-lambert-2 |
|
||||
| 16 | Create author: failed | 500 or network failure. | Couldn't create the author · The article is unchanged. Try again in a moment. |
|
||||
|
||||
## Editor: search and sharing (SEO round)
|
||||
|
||||
Route: `/article/:id/edit`. API: PATCH /v1/article/{id} {slug, excerpt, seo_title, seo_description, cover_image_id, cover_image_alt, social_title, social_description, social_image_id, canonical_url, noindex, seo_dismissed[]}.
|
||||
|
||||
RenewCMS is headless: it never renders pages or adds meta tags. This section helps the writer fill in SEO data and shows what the frontend will receive. Everything is optional and each empty field shows its fallback. Placement: a "Search and sharing" section under "Site and authors" in the sidebar and in the mobile Details sheet. Collapsed by default with a one-line summary (Ready, N suggestions, Hidden from search), remembered per browser. The fields and live previews open in a slide-over (desktop, 960 px) or a 92% sheet over the Details sheet (mobile). Anyone who can edit the article can edit these fields. Suggestions never block saving or publishing: publishing is allowed regardless. Counters are soft guides and turn amber, never red, outside the recommended range. Light and dark follow the theme switch above.
|
||||
|
||||
| # | State | Trigger | Copy |
|
||||
|---|---|---|---|
|
||||
| 1 | Collapsed: ready | The default. Nothing to suggest. | Search and sharing · Ready |
|
||||
| 2 | Collapsed: suggestions | Summary in the warning colour. No count badge elsewhere. | Search and sharing · 2 suggestions |
|
||||
| 3 | Collapsed: hidden | noindex is on. | Search and sharing · Hidden from search |
|
||||
| 4 | Open: ready | Address, the all-good message and two actions. | Address · renew.example/how-we-price-a-bathroom-renovation · All good · Nothing to suggest for this article. · Edit search and sharing · What the frontend gets |
|
||||
| 5 | Open: suggestions | At most three suggestions here, then a count. Each links to its field. | The meta title is 74 characters. Search engines may cut it off after about 60. · Go to meta title · The cover image has no alt text. Add a short description of it. · Go to cover image · The body has no headings. H2 headings help readers scan the article. · Go to body · +1 more in Search and sharing |
|
||||
| 6 | Open: checking | While the checks run after the editor loads. The rest of the section stays usable. | Checking this article… |
|
||||
| 7 | Open: hidden | A line explains the flag. | Hidden from search engines. This only sets a flag in the API. |
|
||||
| 8 | Open: other site | The address uses the article's site. | journal.renew.example/how-we-price-a-bathroom-renovation |
|
||||
| 9 | Panel: defaults | A writer who changed nothing. Every value is a fallback and says so. | Search and sharing · URL slug · Generated from the title until you edit it. · Meta title · Using article title · Recommended 30 to 60 characters. This is a guide, not a limit. · Meta description · Using first sentence of the body · Recommended 70 to 160 characters. · Excerpt · A short summary. It is also sent as the article teaser. · Cover image · Using the site social image (north-wall.jpg). · Social sharing · Optional · Uses the meta values · Advanced · Canonical URL: automatic · Hide from search engines · Sets noindex in the API. It doesn't change who can read the article. · Search result · Social card · Suggestions · What the frontend gets · Cancel · Save changes |
|
||||
| 10 | Panel: filled in | Own values everywhere. The fallback chips are gone and the suggestion list shows All good. | All good · Nothing to suggest for this article. |
|
||||
| 11 | Panel: outside the soft ranges | Counters turn amber. The preview shows the cut-off. Nothing is blocked. | The meta title is 74 characters. Search engines may cut it off after about 60. · The description is 41 characters. About 70 to 160 reads best in results. · Cut off here, the way a search engine would. |
|
||||
| 12 | Panel: slug edited | The Auto badge is gone. "Reset to match the title" brings it back. | Reset to match the title |
|
||||
| 13 | Panel: slug taken | Checked on blur and on save. Nothing is saved until a free slug is chosen. | The slug "bathroom-costs" is already used on Renew. · Use bathroom-costs-2 |
|
||||
| 14 | Panel: cover without alt | Alt text is required before the cover counts as ready. It is a suggestion, not an error. | Alt text · Needed before the cover counts as ready. Sent as image alt in the API. · Describe the image for people who can't see it · The cover image has no alt text. Add a short description of it. |
|
||||
| 15 | Panel: choose cover | The shared Media picker. | Choose a cover image · The cover for this article. · Use image |
|
||||
| 16 | Panel: social sharing open | Optional overrides. Each falls back to the meta values. | Social sharing · Optional · Social title · Using meta title · Social description · Using meta description · Social image · Using the cover image. |
|
||||
| 17 | Panel: social customised | The card shows the overrides, so the Using chips disappear. | Customised |
|
||||
| 18 | Panel: advanced, invalid canonical | Collapsed by default. The address must be absolute. | Advanced · Canonical URL · Only change this if the same content lives at another address. · Enter a full address starting with https:// |
|
||||
| 19 | Panel: hidden from search | The switch only sets a flag in the API. | Hide from search engines · Sets noindex in the API. It doesn't change who can read the article. |
|
||||
| 20 | Panel: mobile search preview | The Desktop and Mobile toggle changes the width and where the title is cut. | Search result · Desktop · Mobile |
|
||||
| 21 | Panel: checking | Checks run on open and after each pause in typing. | Checking this article… |
|
||||
| 22 | Panel: saving | Fields are disabled while the request runs. | Saving… |
|
||||
| 23 | Panel: save failed | 500 or network failure. The values stay. | Couldn't save search and sharing. Your changes are still here. Try again in a moment. |
|
||||
| 24 | Saved | The panel closes. The summary updates. | Search and sharing saved · Your search and sharing settings are up to date. |
|
||||
|
||||
Mobile: the section sits under "Site and authors" in the Details sheet. "Edit search and sharing" opens a 92% sheet on top of the Details sheet, with suggestions first, then fields, then the two previews. Publishing is allowed regardless of suggestions; Save and Publish are never disabled by them.
|
||||
|
||||
## Editor: what the frontend gets (SEO round)
|
||||
|
||||
Route: `/article/:id/edit`. API: GET /v1/article/{id}/seo.
|
||||
|
||||
A read-only dialog (desktop, 720 px) or bottom sheet (mobile) with the resolved SEO object exactly as the API returns it. Opened from the sidebar section or the panel. Each value that came from a fallback carries a chip. Formatted shows a compact key and value list, Raw shows the JSON. Copy JSON copies the raw object. Author name, profile URL and social links come from the Authors screen and surface in authors[] and in the JSON-LD author, so Authors itself needs no change.
|
||||
|
||||
| # | State | Trigger | Copy |
|
||||
|---|---|---|---|
|
||||
| 1 | Formatted | Default view. | What the frontend gets · The SEO data returned by GET /v1/article/12/seo, read only. RenewCMS doesn't render pages or add meta tags: your frontend does. · Formatted · Raw JSON · Copy JSON · Close |
|
||||
| 2 | Raw JSON | The JSON as the API returns it. | Raw JSON |
|
||||
| 3 | Copied | The button reads Copied for 2 s and this is announced. | Copied |
|
||||
| 4 | Draft article | Drafts answer 404 to anonymous callers. | This article is a draft. The API returns this data only to signed-in callers until it is published. |
|
||||
| 5 | Loading | Copy is disabled. | – |
|
||||
| 6 | Error | GET failed. Nothing in the article changes. | Couldn't load the SEO data · GET /v1/article/12/seo failed. Your article is unchanged. Try again in a moment. · Try again |
|
||||
@@ -16,7 +16,7 @@ Sticky section index on the right (desktop), "Jump to" select (mobile). A refere
|
||||
- Note 1: "A key can't create, list or revoke API keys, log in, register, verify or reset a password, or call anything under `/v1/system`. Those routes answer 403 "This action needs a real session." An invalid, unknown, expired or revoked key answers 401, even on public routes, and so does a key whose user was deleted or unverified."
|
||||
- Note 2: "Each key can make 120 requests per minute. Beyond that the API answers 429 with a `Retry-After` header."
|
||||
- Groups: Articles (7), Media (6), Users and invites (6), Settings (1), Session only (12 routes, 3 sub-groups; every `/v1/system` route is in this group). Session-only banner: "These routes need a signed-in browser session. With an API key they answer 403 "This action needs a real session.""
|
||||
- Errors: "Every error is a plain-text body with a single sentence. The status code is in the HTTP status line, and the Content-Type is text/plain." Table 400, 401, 403, 404, 429, 500 with the real messages below. Sample: a status line plus the text body (`HTTP/1.1 403 Forbidden`, `Content-Type: text/plain`, blank line, `This action needs a real session.`).
|
||||
- Errors: "Every error is a plain-text body with a single sentence. The status code is in the HTTP status line, and the Content-Type is text/plain." Table 400, 401, 403, 404, 429, 500 with the real messages below. The 403 row has a note line under it: "Site SEO defaults are owner only. Article SEO fields need only the right to edit the article." (12/18, `--ui-text-muted`, in the cause column, 2 px under the cause text). It is the only row with a note; rows below it move down by the wrapped note height (two 18 px lines on desktop, three on mobile, plus 2 px). Sample: a status line plus the text body (`HTTP/1.1 403 Forbidden`, `Content-Type: text/plain`, blank line, `This action needs a real session.`).
|
||||
- Notes: image URL prefix, CORS (existing copy), and "Article routes accept `?format=markdown`, `?format=html` or `?format=json` to choose how `body` is returned. With `json`, `body` is the stored JSON structure. Articles have `body_format: markdown` by default."
|
||||
|
||||
## EndpointCard states
|
||||
@@ -34,8 +34,8 @@ Desktop 1440×900, mobile 390×844, light and dark.
|
||||
Plain text, one sentence. Used in the table and in the per-endpoint error captions.
|
||||
- 400: "The request cannot be processed due to a mismatch in the format of the body." / "The expiry must be a date in the future." Image requests (`/media/photo.png?v=`) answer 400 with a JSON body (`status`, `error`, `message`, `detail`) in two cases: `{ "status": 400, "error": "unknown_variant", "message": "Unknown variant", "detail": "unknown" }` for an unknown or disabled variant, and `{ "status": 400, "error": "unsupported_parameter", "message": "Unsupported parameter", "detail": "width" }` for any other query parameter (`width`, `height`, `format`, `quality`). Both are rows of the "Responses" table in "Images and variants".
|
||||
- 401: "You must be logged in to access this resource."
|
||||
- 403: "This action needs a real session." (session-only routes called with a key) / "Only the owner can do this." / "You must verify your account to access this resource."
|
||||
- 404: "Article not found" / "Image not found" / "Invite not found" / "API key not found"
|
||||
- 403: "This action needs a real session." (session-only routes called with a key) / "Only the owner can do this." / "You must verify your account to access this resource." Note under the 403 row: "Site SEO defaults are owner only. Article SEO fields need only the right to edit the article." The inline parenthetical that said the same thing in the row's cause text was removed to avoid saying it twice.
|
||||
- 404: "Article not found" / "Image not found" / "Invite not found" / "API key not found" / `site_not_found` (GET /v1/site/{key}/sitemap only; body is the code, not a sentence)
|
||||
- 429: "Too many requests. Please try again later." A per-key limit also sends `Retry-After`.
|
||||
- 500: "Internal server error"
|
||||
- 409, only as examples under their endpoints: `POST /v1/user/invite` "This address already has an account."; `POST /v1/media/merge` "Some of the images to merge changed. Refresh and try again." There is no 409 or 422 row in the table.
|
||||
@@ -108,3 +108,9 @@ New section "Images and variants" on the Integration page, after Media and befor
|
||||
## Pass 2 notes
|
||||
- The base URL field and the image URL builder output are CodeSnippets with a single tab.
|
||||
- Page padding 24 px (16 px on mobile), page title 20/28, section headings 18/26, card titles 15/24, sub headings 14/22 (foundations.md).
|
||||
|
||||
## Search and sharing (SEO round)
|
||||
New group "Search and sharing" after Articles, in the sidebar index and the mobile Jump to select. Two cards in the existing endpoint style (collapsed, method badge, auth badge "Public", example, 401 and 404 rows, copy buttons):
|
||||
- GET /v1/article/{id}/seo: the resolved SEO object. Fields: title, description, canonical_url, robots, og{type,title,description,url,site_name,image,image_alt,locale}, twitter{card,title,description,image,image_alt}, image{url,alt,source}, authors[{name,url,same_as}], published_at, modified_at, fallbacks, json_ld. Drafts answer 404 to anonymous callers.
|
||||
- GET /v1/site/{key}/sitemap?page=&size=: yes, shown per site by key. Items: { url, modified_at, noindex }. Total in X-Total-Count. Sizes 25, 50, 100, 500, default 100. Errors: 400 "The request cannot be processed due to a mismatch in the format of the body." (same text as the other routes; bad `page` or `size`), 401, 404 `site_not_found` (unknown site key; this is the body the API returns, shown as a code and not rewritten as prose).
|
||||
PATCH /v1/article/{id} lists the new optional fields (slug, excerpt, seo_title, seo_description, cover_image_id, cover_image_alt, social_title, social_description, social_image_id, canonical_url, noindex, seo_dismissed). The 403 row of the HTTP status table adds: site SEO defaults are owner only; article SEO fields need only the right to edit the article.
|
||||
@@ -49,7 +49,7 @@ New route for verified users, in the sidebar between Articles and Users with the
|
||||
| 29 | Upload: several files, mixed | Upload button or drop, several files. Each file has its own row and progress. Files upload two at a time. A row can end as added, "Already in your library", rejected in the browser, or failed. Rejected and failed rows stay until dismissed. | "2.2 MB" / "2.6 MB" / "1.1 of 2.6 MB" / "1.9 MB" |
|
||||
| 30 | Upload: summary | All rows settled. The summary counts each outcome. "Use existing" selects the existing image and drops the row; "Upload anyway" stores a second copy, which then appears under Duplicates. "Try again" retries one file. Announced when it finishes. | "2.2 MB" / "2.6 MB" / "Upload finished" / "5 images" / "2 uploaded · 1 already in your library · 2 need attention" |
|
||||
| 31 | Upload: rejected files (413, 400) | Type and size are checked in the browser first, so nothing is sent. A server 413 or 400 for a file that got through shows the same row with its own message. | "210 KB" / "notes.pdf isn't an image" / "Images can be up to 10 MB. Use a PNG, JPEG, WEBP or SVG image." / "3.0 MB" / "broken.png couldn't be read" / "The server couldn't read this image. Save it again as a PNG or JPEG, then try again." / "Nothing was uploaded" / "3 files were rejected" |
|
||||
| 32 | Upload: too many requests (429) | Rate limited. Retry-After is counted down in the button. It re-enables at zero. Already-added files are kept. | |
|
||||
| 32 | Upload: too many requests (429) | Rate limited. Retry-After is counted down in the button. It re-enables at zero. Already-added files are kept. Clock-sensitive: shows a relative time or a countdown. | |
|
||||
| 33 | Duplicates: groups | The Duplicates tab. Groups of identical images side by side, each with its uploader, upload date and "Used in N articles". The suggested copy to keep is the most used, then the oldest. | |
|
||||
| 34 | Purge duplicates: confirm | "Purge duplicates" in the toolbar, next to the sort menu (in the stacked toolbar on mobile). Opens the same dialog as Settings; every other state is on the Media cleanup board. | |
|
||||
| 35 | Duplicates: no purge button (member) | Verified users who are not owner or admin. The "Purge duplicates" button is hidden. "Merge into this one" is unchanged. | |
|
||||
|
||||
@@ -46,3 +46,21 @@ Opened from the account menu at the bottom of the sidebar. Username, email and p
|
||||
| 11 | Reset: too many requests (429) | Rate limited. The button is disabled for 5 minutes. | |
|
||||
| 12 | Reset: failed | 500 or network failure. The button can be pressed again. | |
|
||||
| 13 | Display names in the Users list | The Display name column shows the name when one is set and a dash when not. Your own row follows your saved name. | |
|
||||
|
||||
## Changed in pass 3: author profile
|
||||
|
||||
Every existing Profile frame has the "Author profile" card between Account and Password, in its default state ("Create my author profile"). The card is defined once, in `AppFrame.dc.html`.
|
||||
|
||||
### Profile: author profile (group "Profile: author profile", 5 states)
|
||||
|
||||
Route: `/profile`. API: POST /v1/author/me · GET /v1/auth/me (author field).
|
||||
|
||||
The "Author profile" card sits between Account and Password in every Profile frame, defined once in AppFrame. The existing Profile frames show its default state ("Create my author profile"). All roles can create their own profile and edit their own linked author. Only the states specific to the card are drawn here.
|
||||
|
||||
| # | State | Trigger | Copy |
|
||||
|---|---|---|---|
|
||||
| 1 | No author profile | The user has no linked author. | Author profile · Your public byline on articles. It's separate from your account. · You don't have an author profile yet. Create one to be credited on your own articles. · Create my author profile · Uses your display name, Marta Alves. You can change it afterwards. |
|
||||
| 2 | Error | 500 or network failure. | Couldn't create your author profile · Try again in a moment. |
|
||||
| 3 | Created | 201: the card shows the author. The author is named from the display name and linked to the user. | Author profile created · Marta Alves is now your byline. · Edit author · Linked to your account. New articles start with this author. |
|
||||
| 4 | Created, slug adjusted | The slug was taken, so the server added a number. No error is shown. | Your slug is marta-alves-2 · marta-alves was already used by another author. You can change it in Edit author. |
|
||||
| 5 | Edit own author | Edit author on the card, by a role without author rights. The form opens with the linked user locked and no Unlink. There is no delete action in the form or on this screen. | Edit Marta Alves · Linked user · marta@renew.example · This is your author profile. Only an owner or admin can change the link. · Save changes |
|
||||
@@ -106,11 +106,11 @@ The page is one column of cards, top to bottom: Version, Updates, Media cleanup,
|
||||
|
||||
| # | State | Trigger | Copy |
|
||||
|---|---|---|---|
|
||||
| 1 | Up to date | Opened with no newer version. Restart is available but not emphasised. | "You're up to date" / "You have the latest version of RenewCMS." / "Check for updates" / "Restart" |
|
||||
| 1 | Up to date | Opened with no newer version. Restart is available but not emphasised. Clock-sensitive: shows a relative time or a countdown. | "You're up to date" / "You have the latest version of RenewCMS." / "Check for updates" / "Restart" |
|
||||
| 2 | Checking | Check for updates pressed, or the first open after 24 hours. Announced as "Checking for updates". Buttons are disabled. | "Checking for updates…" / "This usually takes a few seconds." / "Checking…" |
|
||||
| 3 | Check failed | Offline, or the update server didn't answer (500, network). The last known result is kept. | "Couldn't check for updates" / "RenewCMS couldn't reach the update server. Check your connection and try again. Your site isn't affected." / "Last checked yesterday at 18:12" / "Try again" / "Restart" |
|
||||
| 4 | Update available | A newer version exists. Release notes are collapsed. Update is the one primary button. | "Version 2.3.0 is available" / "You have v2.2.0-beta. Update downloads the new version and checks it. Nothing changes until you restart." / "Update" / "Takes about 2 minutes. Your site stays online." |
|
||||
| 5 | Update available, notes open | "What's new in 2.3.0" expanded. It is a button with aria-expanded, and the list is plain text. | "Version 2.3.0 is available" / "You have v2.2.0-beta. Update downloads the new version and checks it. Nothing changes until you restart." / "Update" / "Takes about 2 minutes. Your site stays online." |
|
||||
| 3 | Check failed | Offline, or the update server didn't answer (500, network). The last known result is kept. Clock-sensitive: shows a relative time or a countdown. | "Couldn't check for updates" / "RenewCMS couldn't reach the update server. Check your connection and try again. Your site isn't affected." / "Last checked yesterday at 18:12" / "Try again" / "Restart" |
|
||||
| 4 | Update available | A newer version exists. Release notes are collapsed. Update is the one primary button. Clock-sensitive: shows a relative time or a countdown. | "Version 2.3.0 is available" / "You have v2.2.0-beta. Update downloads the new version and checks it. Nothing changes until you restart." / "Update" / "Takes about 2 minutes. Your site stays online." |
|
||||
| 5 | Update available, notes open | "What's new in 2.3.0" expanded. It is a button with aria-expanded, and the list is plain text. Clock-sensitive: shows a relative time or a countdown. | "Version 2.3.0 is available" / "You have v2.2.0-beta. Update downloads the new version and checks it. Nothing changes until you restart." / "Update" / "Takes about 2 minutes. Your site stays online." |
|
||||
| 6 | Downloading | Update pressed (202). Progress polls every second. Announced as "Downloading, 25 percent" and so on, never every tick. | "Downloading version 2.3.0…" / "You can leave this page. The download continues and your site stays online." / "Downloading version 2.3.0" / "42% · 11 of 26 MB" / "Updating…" |
|
||||
| 7 | Verifying | The download finished. No percentage, so the bar is indeterminate. Announced as "Checking the download". | "Checking the download…" / "Making sure the file is complete and safe to install. This takes a few seconds." / "Checking the download" / "Almost there" / "Updating…" |
|
||||
| 8 | Ready to install | The file passed its checks. Restart becomes the primary action. "Restart later" is closing the dialog or leaving the page. | "Version 2.3.0 is ready to install" / "The download is checked. Restart to install it. Your site will be unavailable for about 10 seconds." / "Nothing has changed yet." / "Restart" / "Not now? Leave this page. The update waits here, and the banner on Home reminds you." |
|
||||
@@ -118,19 +118,19 @@ The page is one column of cards, top to bottom: Version, Updates, Media cleanup,
|
||||
| 10 | Restart: request failed | 500 or network failure before the restart began. The site is still running. | "Version 2.3.0 is ready to install" / "The download is checked. Restart to install it. Your site will be unavailable for about 10 seconds." / "Nothing has changed yet." / "Restart" / "Couldn't start the restart. Nothing was changed and your site is still running. Try again in a moment." |
|
||||
| 11 | Restarting to install | Full-page overlay, so it survives the server going away. The page polls until the site answers, then reloads. It is a live region announced once as "Installing version 2.3.0. Your site is restarting." | "Version 2.3.0 is ready to install" / "Installing version 2.3.0" / "Your site is restarting with the new version. This takes about 10 seconds. This page reloads on its own when the site is back." / "Started at 09:51" |
|
||||
| 12 | Restarting, taking longer | No answer after 60 seconds. The copy changes and a manual reload appears. The overlay stays until the site is back. | "Still restarting" / "This is taking longer than usual. Keep this page open. It reloads on its own when the site is back, or you can reload it now." / "Started at 09:51 · 1 minute ago" / "Reload page" |
|
||||
| 13 | Update done | The page reloaded on the new version. Focus lands on the "Updates" heading (ring shown), the toast is announced, and the version updates. | "You're on version 2.3.0" / "The update is installed and your site is running again." / "Updated today at 09:52" / "Check for updates" / "Restart" / "Read the release notes" / "Update installed" / "RenewCMS is now on version 2.3.0." |
|
||||
| 13 | Update done | The page reloaded on the new version. Focus lands on the "Updates" heading (ring shown), the toast is announced, and the version updates. Clock-sensitive: shows a relative time or a countdown. | "You're on version 2.3.0" / "The update is installed and your site is running again." / "Updated today at 09:52" / "Check for updates" / "Restart" / "Read the release notes" / "Update installed" / "RenewCMS is now on version 2.3.0." |
|
||||
| 14 | Update failed, rolled back | The site came back on v2.2.0-beta. The error toast stays until dismissed and the card keeps the explanation. | "The update didn't install" / "RenewCMS put the previous version back, so your site is running as before. Nothing was lost." / "What to do next: try again in a few minutes. If it fails again, ask whoever manages your server to check the update." / "Try again" / "Your site is back on v2.2.0-beta." |
|
||||
| 15 | Download failed | A 500, or the connection dropped. Focus moves to the card heading. Try again restarts the download. | "The download didn't finish" / "The connection dropped before the file was complete. Nothing was changed and your site is running as before." / "Try again" |
|
||||
| 16 | Verification failed | The downloaded file isn't trusted. The tone is a warning, and the file is thrown away. Technical detail goes to the server log, not the screen. | "We didn't use this update" / "The file didn't pass our safety check, so it was not installed. Nothing was changed. Try downloading it again. If this keeps happening, contact RenewCMS support." / "Try again" |
|
||||
| 17 | Too many requests (429) | Retry-After counted down in the button. It re-enables at zero. | "Too many tries" / "Wait a moment before trying again." / "Try again in 0:42" |
|
||||
| 17 | Too many requests (429) | Retry-After counted down in the button. It re-enables at zero. Clock-sensitive: shows a relative time or a countdown. | "Too many tries" / "Wait a moment before trying again." / "Try again in 0:42" |
|
||||
| 18 | Not prepared | The server can't update from the browser. No buttons, not even Restart. The command is for the person who runs the server and is a single line. The placeholder command is subject to the real one. | |
|
||||
| 19 | Not prepared: command copied | Copy pressed. The button reads "Copied" for 2 s and it is announced. | |
|
||||
| 20 | Plain restart: confirm | Restart with no update waiting. Nothing is installed. | "You're up to date" / "You have the latest version of RenewCMS." / "Check for updates" / "Restart" |
|
||||
| 20 | Plain restart: confirm | Restart with no update waiting. Nothing is installed. Clock-sensitive: shows a relative time or a countdown. | "You're up to date" / "You have the latest version of RenewCMS." / "Check for updates" / "Restart" |
|
||||
| 21 | Plain restart: restarting | Same overlay as the update restart with shorter copy. | "Restarting your site" / "This takes about 10 seconds. This page reloads on its own when the site is back." / "Started at 09:51" |
|
||||
| 22 | Plain restart: done | The page reloaded. Focus lands on the "Updates" heading. | "Your site is back" / "Site restarted" / "Your site is running again." |
|
||||
| 23 | Admin view | Admins see the version and the note, with no buttons. Up to date: "You're up to date" and "Only the owner can update or restart the site." No Home banner or Settings pill. | "Version 2.3.0 is available" / "You have v2.2.0-beta. Only the owner can update RenewCMS. Ask the owner of this site." |
|
||||
| 24 | Role changed (403) | An owner was changed to admin while the page was open and pressed a button. The card reloads in the admin view. | "Version 2.3.0 is available" / "You have v2.2.0-beta. Only the owner can update RenewCMS. Ask the owner of this site." / "Only the owner can do this" / "Ask the owner of this site to update RenewCMS." |
|
||||
| 25 | Update already running (409) | Another owner started it. The card switches to that run's progress. | "Version 2.3.0 is available" / "You have v2.2.0-beta. Update downloads the new version and checks it. Nothing changes until you restart." / "Update" / "An update is already running" / "Another owner started it. Progress shows here." |
|
||||
| 23 | Admin view | Admins see the version and the note, with no buttons. Up to date: "You're up to date" and "Only the owner can update or restart the site." No Home banner or Settings pill. Clock-sensitive: shows a relative time or a countdown. | "Version 2.3.0 is available" / "You have v2.2.0-beta. Only the owner can update RenewCMS. Ask the owner of this site." |
|
||||
| 24 | Role changed (403) | An owner was changed to admin while the page was open and pressed a button. The card reloads in the admin view. Clock-sensitive: shows a relative time or a countdown. | "Version 2.3.0 is available" / "You have v2.2.0-beta. Only the owner can update RenewCMS. Ask the owner of this site." / "Only the owner can do this" / "Ask the owner of this site to update RenewCMS." |
|
||||
| 25 | Update already running (409) | Another owner started it. The card switches to that run's progress. Clock-sensitive: shows a relative time or a countdown. | "Version 2.3.0 is available" / "You have v2.2.0-beta. Update downloads the new version and checks it. Nothing changes until you restart." / "Update" / "An update is already running" / "Another owner started it. Progress shows here." |
|
||||
|
||||
### Settings: Media cleanup (group "Settings: Media cleanup", 9 states)
|
||||
|
||||
@@ -192,3 +192,7 @@ The last card on the page, same card styling as Version, Updates and Media clean
|
||||
| 4 | Shortening the period | Confirms before older events are removed. | |
|
||||
| 5 | Forever | No cleanup scheduled. | |
|
||||
| 6 | Save error | The previous setting is still in place. | |
|
||||
|
||||
## Changed in pass 3: Publishing card and Sites child
|
||||
|
||||
Owner only. A "Publishing" card sits between the Media card and Media cleanup: title "Publishing", text "Where your content is shown.", one row "Manage sites" / "Base URLs, default image and robots policy" that opens `/settings/sites`. The sidebar Settings group gains a second heading "Publishing" with one child, "Sites". Existing Settings frames (owner view) show both. Admins and other roles see neither the card nor the sidebar entry (frame "Hidden entry (admin)" in group "Sites"), and `/settings/sites` shows a 403 page (frame "Forbidden (403)").
|
||||
@@ -0,0 +1,109 @@
|
||||
|
||||
# Sites
|
||||
|
||||
Route: `/settings/sites`. API: GET /v1/site/ · POST /v1/site/ · PATCH /v1/site/{id} · DELETE /v1/site/{id}?reassign_to={id}.
|
||||
|
||||
A site is a frontend that displays content: name, key, base URL, default social image, default robots policy, optional locale and a default flag. Each article belongs to exactly one site. A default site always exists and cannot be deleted; the first is seeded once, at migration, from PUBLIC_URL (the CMS's own address, so only a starting value: the owner is expected to set the frontend's address). The base URL must use https, except for loopback hosts (localhost, 127.0.0.1, ::1), so a local frontend works. is_online stays the global publish switch.
|
||||
|
||||
**Roles.** Only the owner can create, edit, set the default or delete a site. Admins and other roles don't see the Sites entry under Settings, and the "Publishing" card is hidden for them. A direct link to `/settings/sites` shows a 403 page. Choosing a site for an article is not site management: anyone who can edit an article can set its site in the editor and read the site list (GET /v1/site/).
|
||||
|
||||
**Site key.** The key is set when the site is created and can't be edited afterwards. The edit form shows it read-only with a lock and the text "Used in API paths, so it can't change." There is no editable-key state and no key-change warning.
|
||||
|
||||
**Shared pieces.** The list, slide-over, delete-with-reassign dialog, slug field and media field are defined once in `DirectoryFrame.dc.html` and referenced by both Sites and Authors; nothing is drawn separately for either screen. `AppFrame.dc.html` holds the shell (sidebar, Settings card, editor section, Profile card).
|
||||
|
||||
Visual reference: `RenewCMS Screens Back-office.dc.html`, groups "Sites", "Sites: form", "Sites: delete". Every state is drawn in light and dark (theme switch) at 1440×900 and 390×844. Copy is exact. Strings in a Copy cell are separated by " · " and listed in reading order. Dialog and form submit states ("Saving…", "Moving articles…") use the button loading pattern from the controls matrix and are not drawn per screen.
|
||||
|
||||
### Sites (group "Sites", 9 states)
|
||||
|
||||
Only the owner can create, edit, set the default or delete a site. Other roles don't see the Sites entry under Settings; a direct link shows a 403 page. A site name can still appear read-only in the article editor and the Articles list. New child of Settings, under a "Publishing" heading in the sidebar (Settings also gets a "Publishing" card with a "Manage sites" row, owner only). Columns: name with key, base URL, article count. The default site carries a "Default" badge and has no delete action. A site with robots set to noindex shows a "Noindex" badge. List, row menu and dialogs come from DirectoryFrame and are shared with Authors.
|
||||
|
||||
| # | State | Trigger | Copy |
|
||||
|---|---|---|---|
|
||||
| 1 | Default | The list loaded. Four sites, Renew is the default. Owner only. | Sites · The frontends that display your content. · Add site · Site · Base URL · Articles · Default · Noindex · 268 articles · 38 articles · 6 articles · No articles |
|
||||
| 2 | Only the default site | First run: the seeded site only. A hint under the list, no empty-state wall. | Add another site if your content is shown on more than one frontend. Each article belongs to one site. |
|
||||
| 3 | Loading | The first load, or a retry. Skeleton rows appear after 150 ms. | |
|
||||
| 4 | Error | A 500 or network failure on the list request. | Couldn't load sites · Check your connection and try again. · Try again |
|
||||
| 5 | Row menu | The ellipsis button, or Enter on the focused menu button. Mobile: bottom sheet titled with the site name. | Edit · Set as default · Delete… |
|
||||
| 6 | Default site: delete unavailable | Menu on the default site. "Delete…" is aria-disabled, stays focusable and explains itself: tooltip on desktop, text in the sheet on touch. | The default site can't be deleted. Make another site the default first. |
|
||||
| 7 | Set as default: confirm | "Set as default" in the row menu. On 200 the badge moves and a toast confirms. The button reads "Saving…" while the request runs. | Make Journal the default site? · New articles start on this site. Articles that are already on other sites stay where they are. · Cancel · Make default · Default site changed · "Journal" is now the default site. |
|
||||
| 8 | Hidden entry (admin) | An admin opens Settings. The sidebar has no Publishing group and no Sites entry, and the page has no Publishing card. Roles without Settings have nothing to hide. | No Publishing group · No Sites entry · No "Manage sites" row |
|
||||
| 9 | Forbidden (403) | A role other than owner opens /settings/sites from a bookmark or a link. The sidebar has no Sites entry, so the page explains instead of redirecting. The API answers 403. | You don't have access to Sites · Only the owner can manage sites. Ask the owner of this site if you need a change. · Back to Settings |
|
||||
|
||||
### Sites: add and edit (group "Sites: form", 7 states)
|
||||
|
||||
Owner only. A slide-over, because the form has a live preview (the canonical URL). Fields: name, key, base URL, default social image (media picker), default robots policy, optional locale, default switch. The key is set when the site is added and can't be edited afterwards: the edit form shows it read-only with a lock and the text "Used in API paths, so it can't change." Closing with changes asks "Discard changes?" with the existing discard dialog. The slug field, media field and picker are the shared ones from DirectoryFrame (the picker is drawn once, in Authors: form). Locale error: "Use a language tag like en or fr-CH."
|
||||
|
||||
| # | State | Trigger | Copy |
|
||||
|---|---|---|---|
|
||||
| 1 | Add: empty | "Add site" in the page header, or the bottom button on mobile. | Add site · Name · e.g. Journal · Key · Generated from the name · Base URL · https://blog.example.com · The public address of the frontend. Use https and no path. · Default social image (optional) · Choose image · Used when an article has no image of its own. · Default robots policy · Index · Noindex · Search engines may list this site's pages. · Locale (optional) · e.g. en or fr-CH · A language tag. Leave empty if the site has no single language. · Make this the default site · New articles start here. The current default is Renew. · Canonical URL preview · Cancel · Add site |
|
||||
| 2 | Add: key from the name | Typing a name fills the key. The pencil unlocks it until the site is added. | journal · Auto · Lowercase letters, numbers and hyphens. Used in API paths. It can't be changed after the site is added. |
|
||||
| 3 | Add: URL not valid | On blur or submit. Nothing is sent. A URL with a path and text that is not a URL get their own messages, drawn the same way. | Use https. For example https://blog.example.com. · Remove the path. Use only the host, like https://blog.example.com. · Enter a full URL, like https://blog.example.com. |
|
||||
| 4 | Add: duplicate key | 409 on submit, or on blur after a check. | A site with the key "journal" already exists. Choose another key. · Use journal-2 |
|
||||
| 5 | Add: save failed | 500 or network failure. The values stay. | Couldn't save the site. Your changes are still here. Try again in a moment. |
|
||||
| 6 | Edit: default site | Edit on the default site. The key is read-only with a lock, because it is used in API paths. The switch is on and locked. | Edit Renew · Key · renew · Used in API paths, so it can't change. · Default site · New articles start on the default site. To change it, make another site the default. · Save changes |
|
||||
| 7 | Edit: other site, noindex | Edit on a non-default site. | Edit Projects · Key · projects · Used in API paths, so it can't change. · Noindex · Asks search engines not to list this site's pages. · Make this the default site |
|
||||
|
||||
### Sites: delete (group "Sites: delete", 3 states)
|
||||
|
||||
Owner only. A site with articles cannot be deleted without a destination: the dialog has a select and shows how many articles move. Destination defaults to the default site. Without reassign_to the server answers 409. This is the shared ReassignDialog from DirectoryFrame; its failed state is drawn once, in Authors: delete.
|
||||
|
||||
| # | State | Trigger | Copy |
|
||||
|---|---|---|---|
|
||||
| 1 | With articles | "Delete…" on a site that has articles. The button reads "Moving articles…" while the request runs. On 204 the row leaves the list and a toast reads "Site deleted" · "38 articles moved to Renew." | Delete this site? · "Journal" will be deleted. 38 articles belong to it, so choose a site to move them to. This can't be undone. · Move articles to · Renew · renew.example · 38 articles will move to Renew. Their canonical host changes to renew.example. · Cancel · Move 38 articles and delete |
|
||||
| 2 | Choose destination | The select is open. The site being deleted is not listed. | Journal is not offered. Options show name and host. |
|
||||
| 3 | No articles | A site with zero articles: plain confirm, no select. | Delete this site? · "Archive" will be deleted. No articles belong to it. This can't be undone. · Delete site |
|
||||
|
||||
### Sites: pagination (group "Sites: pagination", 10 states)
|
||||
|
||||
Route: `/settings/sites?page=2&size=50`. API: GET /v1/site/?q=&page=&size= (design assumption to confirm: `q`, `page`, `size` and `X-Total-Count` on the site list; today the list returns every site). Owner only, like the rest of Sites. Drawn with 61 sites (3 pages) and generated rows.
|
||||
|
||||
**URL.** `/settings/sites?page=2&size=50`. `page` and `size` are the parameter names (as Articles and Activity). `size` is one of 5, 25, 50, 100; default 25. Defaults are omitted from the URL (`page=1`, `size=25`). Combined with search: `/settings/sites?q=renew&page=2`. A search change or a size change resets `page` to 1 and drops it from the URL. An invalid `size` or `page` (not a positive integer) is replaced silently by the default with `history.replace`. A `page` past the last page falls back to the last page: the URL is replaced by `?page=<last>` and the info notice "That page doesn't exist. Showing the last page." is shown, as on Articles. Browser Back returns to the previous page of results.
|
||||
|
||||
**Pager.** The same component as Articles and Media, in the same footer position (below the list, summary on the left, page-size select next to it, right-aligned controls; mobile: summary and select on one row, then Previous, "Page X of Y", Next). Nothing new is drawn. Sizes are the sizes of the existing pattern: 5, 25, 50, 100 (default 25). API: total in `X-Total-Count`, array body unchanged. Keyboard and aria as Articles. The only difference from Articles: on a single page the page-size select is hidden too and the footer holds only the count line "N sites" (Articles keeps its summary and select). Existing frames of this screen that show a short list (the "Default" frames above) don't draw the count line yet; it appears whenever the list has loaded.
|
||||
|
||||
**Search on Sites.** The Sites screen has no search field today. States 8 and 9 need one, so the pagination frames add the Authors field with the placeholder "Search by name or key" (name, key and base URL are matched). Treat it as a proposal; if you prefer no search on Sites, drop states 8 and 9 and the `q` parameter.
|
||||
|
||||
| # | State | Trigger | Copy |
|
||||
|---|---|---|---|
|
||||
| 1 | First page | /settings/sites. Previous and First are disabled (40% opacity, aria-disabled). Mobile: Previous disabled. | Showing 1–25 of 61 · 25 per page · Page 1 of 3 |
|
||||
| 2 | Middle page | /settings/sites?page=2. Current page uses --rc-sand and --rc-on-sand with a --ui-primary border; ellipses mark skipped ranges once there are more than 7 pages. | Showing 26–50 of 61 · Page 2 of 3 |
|
||||
| 3 | Last page | /settings/sites?page=3. Next and Last are disabled. | Showing 51–61 of 61 · Page 3 of 3 |
|
||||
| 4 | Single page | Everything fits on one page (4 sites). The pager and the page-size select are hidden; the count line stays in the footer position. Zero results use state 8 instead. | 4 sites |
|
||||
| 5 | Page size menu | The select opens upward. Sizes are the Articles sizes: 5, 25, 50, 100; default 25. The chosen size is saved as size and the page resets to 1. | 5 per page · 25 per page · 50 per page · 100 per page |
|
||||
| 6 | Loading a page | Next, Previous, a page number or a size change was used. The rows are replaced by the existing skeleton rows (8 desktop, 6 mobile). The pager stays and is disabled (40% opacity, not focusable); the summary reads "Loading page 3…" and the page number shown is still 2. | Loading page 3… |
|
||||
| 7 | Error loading a page | 500 or network failure on a page change. The rows of page 2 stay, the pager keeps "Page 2", and the inline error with Retry sits above the pager. Retry repeats the request for page 3. | Couldn't load page 3. Showing page 2. · Check your connection and try again. · Retry |
|
||||
| 8 | Empty after search | A search matched nothing. The existing empty state replaces the list; no pager, no count. Clear search returns to /settings/sites and page 1. | No sites match "blog" · Check the spelling, or search for a shorter part of the name. · Clear search |
|
||||
| 9 | Search resets to page 1 | Searching "renew" from page 4 goes to /settings/sites?q=renew (page omitted). Any search change, and any size change, resets the page to 1. | Showing 1–25 of 27 |
|
||||
| 10 | Long labels on mobile | A large total on a 390 px screen. The summary and the page-size select share one row and wrap onto two if needed; Previous, the "Page 6 of 13" label and Next stay on one row (the two buttons flex, the label never wraps). Totals over 999 use thousands separators in both labels. | Showing 126–150 of 312 · Page 6 of 13 |
|
||||
|
||||
|
||||
|
||||
Route: `/settings/sites`. API: PATCH /v1/site/{id} {site_name, title_template, default_description, social_image_id, default_robots}.
|
||||
|
||||
Owner only, like the rest of Sites. The existing add and edit form gains three fields under the default social image (reused, not duplicated): Site name, Title template with a live example, and Default description. The default robots policy keeps its place. A box under the form explains how articles use these defaults. Sites has no separate read-only details view: the edit form is the details, and other roles get the existing 403 page (403 owner_only on PATCH, 401 without a session).
|
||||
|
||||
| # | State | Trigger | Copy |
|
||||
|---|---|---|---|
|
||||
| 1 | Edit: SEO defaults | Edit on the default site. | Default social image (optional) · Site name · Shown in titles through the template, and sent as the Open Graph site name. · Title template · Use %title% for the article title and %site% for the site name. · Example · How we price a bathroom renovation \| Renew · Default description (optional) · Used when an article has no description, excerpt or body text. · How articles use these defaults · Title · Article title, then the template. · Description · Used last, after the article's description, excerpt and body. · Image · Used when an article has no cover image. · Robots · Used unless an article is hidden from search engines. |
|
||||
| 2 | Add: defaults | New sites start with the default template and nothing else. | Site name · e.g. Renew · %title% \| %site% · One or two sentences about the site. |
|
||||
| 3 | Template: custom | The example updates as the owner types. | Example · How we price a bathroom renovation – Journal |
|
||||
| 4 | Template: not valid | The template needs %title%. Nothing is sent. | The template must contain %title%. |
|
||||
| 5 | Save failed | 500 or network failure. | Couldn't save the site. Your changes are still here. Try again in a moment. |
|
||||
|
||||
Owner only. Non-owners get the existing 403 page. Sites has no read-only details view; the edit form is the details.
|
||||
|
||||
## Sites: SEO defaults (SEO round)
|
||||
|
||||
Route: `/settings/sites`. API: PATCH /v1/site/{id} {site_name, title_template, default_description, social_image_id, default_robots}.
|
||||
|
||||
Owner only, like the rest of Sites. The existing add and edit form gains three fields under the default social image (reused, not duplicated): Site name, Title template with a live example, and Default description. The default robots policy keeps its place. A box under the form explains how articles use these defaults. Sites has no separate read-only details view: the edit form is the details, and other roles get the existing 403 page (403 owner_only on PATCH, 401 without a session).
|
||||
|
||||
| # | State | Trigger | Copy |
|
||||
|---|---|---|---|
|
||||
| 1 | Edit: SEO defaults | Edit on the default site. | Default social image (optional) · Site name · Shown in titles through the template, and sent as the Open Graph site name. · Title template · Use %title% for the article title and %site% for the site name. · Example · How we price a bathroom renovation \| Renew · Default description (optional) · Used when an article has no description, excerpt or body text. · How articles use these defaults · Title · Article title, then the template. · Description · Used last, after the article's description, excerpt and body. · Image · Used when an article has no cover image. · Robots · Used unless an article is hidden from search engines. |
|
||||
| 2 | Add: defaults | New sites start with the default template and nothing else. | Site name · e.g. Renew · %title% \| %site% · One or two sentences about the site. |
|
||||
| 3 | Template: custom | The example updates as the owner types. | Example · How we price a bathroom renovation – Journal |
|
||||
| 4 | Template: not valid | The template needs %title%. Nothing is sent. | The template must contain %title%. |
|
||||
| 5 | Save failed | 500 or network failure. | Couldn't save the site. Your changes are still here. Try again in a moment. |
|
||||
|
||||
Owner only. Non-owners get the existing 403 page. Sites has no read-only details view; the edit form is the details.
|
||||
@@ -47,6 +47,6 @@ One shared workspace: every user sees the same articles and this same list. Colu
|
||||
| 12 | Cancel invite: failed | 500 or network failure. The dialog stays open. | "Cancel this invite?" / "The link sent to sam.oliveira@renew.example will stop working. You can invite the address again later." / "Keep invite" / "Cancel invite" / "Couldn't cancel the invite. Try again in a moment." |
|
||||
| 13 | Cancel invite: done | 204: the row disappears and a toast confirms. | "Invite cancelled" / "sam.oliveira@renew.example can no longer use the link." |
|
||||
| 14 | Renew invite: sending | "Renew invite" on an Expired row. No confirmation, since it only sends an email. The button shows progress and is disabled. | "Renewing…" |
|
||||
| 15 | Renew invite: done | 200: the row becomes Pending with today's date, moves to the top, and the old link stops working. | "Today" / "Invite renewed" / "p.huber@gmail.com has 3 days to accept the new link." |
|
||||
| 15 | Renew invite: done | 200: the row becomes Pending with today's date, moves to the top, and the old link stops working. Clock-sensitive: shows a relative time or a countdown. | "Today" / "Invite renewed" / "p.huber@gmail.com has 3 days to accept the new link." |
|
||||
| 16 | Renew invite: failed | 500 or network failure. The row stays Expired and the button can be pressed again. | "Couldn't renew the invite" / "Try again in a moment." |
|
||||
| 17 | Invite sent | 201: the dialog closes, the new invite appears at the top as Pending, and a toast confirms. | "lea.martin@renew.example" / "Today" / "lea.martin@renew.example has 3 days to accept." |
|
||||
@@ -0,0 +1,32 @@
|
||||
# SEO: decisions and slice order
|
||||
|
||||
Spec of record for the design is `change-list.md` (section "SEO round"), `screens/editor.md`, `screens/sites.md`, `screens/articles.md`, `screens/integration.md` and `states.md`. This file records the product decisions that settle the design's open questions, and the order of the implementation slices.
|
||||
|
||||
## Decisions on the open questions
|
||||
|
||||
| # | Question | Decision |
|
||||
| --- | --- | --- |
|
||||
| 1 | Is `slug` immutable after publication? | No. It stays editable. RenewCMS does not manage redirects, so the frontend owns them. No extra warning copy is added to the design. |
|
||||
| 2 | SEO object for drafts | `GET /v1/article/{id}/seo` answers drafts to authenticated callers who can read the article, and 404 to anonymous callers. The editor preview needs it. |
|
||||
| 3 | Noindex in the sitemap | Included with `noindex: true`, as drawn. The frontend decides. |
|
||||
| 4 | Who applies `title_template` | The API. `title` in the SEO object is resolved. The raw `seo_title` and the site template stay readable on their own routes. |
|
||||
| 5 | Backfill | Migration generates a slug for every existing article from its title (same slug rule as authors), unique per site, with `-2`, `-3` suffixes. A title with no letter or digit becomes `article`, then `article-2`, `article-3`. It runs once and is idempotent. |
|
||||
| 6 | Excerpt in the list payload | Yes. Article items carry `excerpt`. |
|
||||
|
||||
## Decisions that the design leaves implicit
|
||||
|
||||
- Suggestions come from one server-side rule set. The same function feeds `seo_status` and `seo_suggestions` in the article list, the collapsed section summary, and the editor panel.
|
||||
- The editor panel's "checking" states and the "slug taken" state use one non-persisting endpoint: `POST /v1/article/{id}/seo/check`. Its body takes the same optional SEO fields as `PATCH /v1/article/{id}`, plus an optional `body` (never `site_id` or `author_ids`), and overrides the saved values for the check only. It answers `{ status, suggestions: [{ code, field, params }], slug: { available, suggestion } }`. Copy for each code lives in the SPA, with a French entry. `seo_dismissed` codes are filtered out of `suggestions` and are never counted in the list.
|
||||
- The suggestion codes are the ones the board uses: `title_long`, `title_empty`, `desc_short`, `desc_long`, `cover_alt`, `cover_none`, `slug_long`, `no_au`, `no_h`, `body_alt`, `short`.
|
||||
- Cover, social and site social images are media usages: `GET /media/{id}/usage`, `used_in`, the unused filter, merge, purge and delete protection must count them. This also closes the existing gap where author avatars and site social images are missing from `GET /media/{id}/usage`.
|
||||
- Roles: anyone who can edit an article edits its SEO fields and runs the check. Only the owner edits site SEO fields (403 "Only the owner can do this."). `GET /v1/site/{key}/sitemap` is public, like the other read routes that serve online articles. SEO edits are logged as an `articles` event; no field values or body text are stored.
|
||||
- `PATCH /v1/article/{id}` still requires at least one known field and still answers 400 on `null`. The SEO fields join `body`, `site_id` and `author_ids`.
|
||||
|
||||
## Slices
|
||||
|
||||
1. **SEO data (backend).** Article and site fields, slug rule and uniqueness per site (409 plain-text `slug_taken`; the first free alternative is in the `X-Slug-Suggestion` response header), backfill, `excerpt` in reads and lists, media usage widening. No resolver yet.
|
||||
2. **SEO output (backend).** `GET /v1/article/{id}/seo` (fallback chain, title template, JSON-LD), `POST /v1/article/{id}/seo/check`, `seo_status`, `seo_suggestions` and `?seo=` on the article list, `GET /v1/site/{key}/sitemap`.
|
||||
3. **Editor (SPA).** "Search and sharing" section, slide-over and sheet, live previews, suggestions with debounced check, slug field with Auto and Reset, "What the frontend gets" dialog, draft and Save behaviour.
|
||||
4. **Sites, Articles, Integration (SPA).** Site SEO defaults, status chip and "Needs attention" filter, Integration "Search and sharing" group, French strings, catalogue.
|
||||
|
||||
Run them in order and commit between them: 2 uses the fields of 1, 3 uses the endpoints of 2, and 3 and 4 share the article API types.
|
||||
@@ -0,0 +1,29 @@
|
||||
# Sites and authors: cross-slice context
|
||||
|
||||
The design for Sites and Authors is in `screens/sites.md`, `screens/authors.md`, the "Editor: site and authors", "Profile: author profile" and "Articles: sites and authors" sections of the editor, profile and articles docs, and the board groups listed in `README.md` (pass 3). Behaviour still comes from `features/`; where the two disagree, stop and ask.
|
||||
|
||||
## Roles
|
||||
| Action | Owner | Admin | Other roles |
|
||||
|---|---|---|---|
|
||||
| Create, edit, set default, delete a site | yes | no | no |
|
||||
| Read the site list, choose an article's site | yes | yes | yes, if they can edit the article |
|
||||
| Create, edit, delete any author | yes | yes | no |
|
||||
| Read authors, pick authors on an article | yes | yes | yes |
|
||||
| Create and edit their own linked author (`POST /v1/author/me`) | yes | yes | yes |
|
||||
| Create an author from the editor ("Create author…", "This is me") | yes | yes | no |
|
||||
|
||||
## Decisions already taken
|
||||
- One site per article (`site_id` on the article). No per-site publish state: `is_online` stays the global switch. API keys stay global.
|
||||
- The site key is immutable after creation. Exactly one default site exists and it cannot be deleted. Deleting a site with articles requires `reassign_to`.
|
||||
- Authors are separate from users. An optional, unique link to a user. The slug is globally unique and not tied to a site. Zero authors on an article is allowed and never blocks publishing. Deleting an author with articles requires `reassign_to` (an author id or `none`).
|
||||
- Media used as an author avatar or a site's default social image counts as media usage.
|
||||
- The default site is seeded once from `PUBLIC_URL`. That variable is the CMS's own address (email links), so the seed is only a starting value that the owner edits. The base URL must be https, except for loopback hosts.
|
||||
- Existing articles are backfilled to the default site and get no authors.
|
||||
|
||||
## Slices, in order
|
||||
1. Sites API. 2. Authors API (independent of 1; both touch the article update route and the article response, so merge 1 first and rebase 2).
|
||||
3. Sites and Authors screens plus the shared directory pieces (`DirectoryFrame.dc.html`). Existing Editor, Articles and Profile screens are not changed here.
|
||||
4. Editor, Articles and Profile integration, which also makes every existing frame of those screens pass the visual check.
|
||||
|
||||
## Open point for the first slice
|
||||
`PATCH /v1/article/{id}` is served by `UpdateArticleBody` and only updates the body. Extending it with `site_id` and `author_ids[]` or splitting a metadata endpoint is decided in the specifier step of slices 1 and 2.
|
||||
@@ -12,7 +12,7 @@
|
||||
<div style="width:224px;flex-shrink:0;background:var(--ui-bg);border-right:1px solid var(--ui-border);display:flex;flex-direction:column;padding:12px;gap:2px">
|
||||
<div style="display:flex;align-items:center;gap:10px;height:40px;padding:0 6px;margin-bottom:10px"><svg width="26" height="26" viewBox="0 0 16 16" shape-rendering="crispEdges"><rect width="16" height="16" fill="#111"></rect><path fill="#fff" fill-rule="evenodd" d="M4 3h6v1h1v1h1v3h-1v1h-1v1h1v1h1v2h-2v-2h-1v-1H6v3H4zm2 2v3h4V5z"></path></svg><span style="font-weight:600;font-size:14px;color:var(--ui-text-highlighted)">RenewCMS</span></div>
|
||||
<sc-for list="{{ nav }}" as="n" hint-placeholder-count="3">
|
||||
<div data-act="nav-{{ n.key }}" style="display:flex;align-items:center;gap:10px;height:32px;padding:0 10px;background:{{ n.bg }};color:{{ n.fg }};font-weight:{{ n.fw }}"><span aria-hidden="true" style="display:inline-block;width:16px;height:16px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/{{ n.icon }}.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/{{ n.icon }}.svg') center / contain no-repeat"></span>{{ n.t }}<sc-if value="{{ n.badge }}"><span style="margin-left:auto;height:18px;padding:0 6px;display:inline-flex;align-items:center;background:var(--ui-info);color:var(--ui-bg);font:500 11px 'IBM Plex Sans',sans-serif">Update</span></sc-if><sc-if value="{{ n.chev }}"><span aria-hidden="true" style="margin-left:{{ n.chevML }};display:inline-block;flex-shrink:0;width:14px;height:14px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/{{ n.chev }}.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/{{ n.chev }}.svg') center / contain no-repeat"></span></sc-if></div><sc-if value="{{ n.sub }}"><div style="display:flex;flex-direction:column;gap:2px;margin-left:19px;border-left:1px solid var(--ui-border)"><span style="padding:6px 10px 2px 12px;font-size:11px;line-height:16px;font-weight:600;letter-spacing:.04em;text-transform:uppercase;color:var(--ui-text-muted)">Media</span><sc-for list="{{ n.subs }}" as="x" hint-placeholder-count="2"><div data-act="nav-{{ x.t }}" style="display:flex;align-items:center;gap:10px;height:32px;padding:0 10px 0 12px;background:{{ x.bg }};color:{{ x.fg }};font-weight:{{ x.fw }}"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:14px;height:14px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/{{ x.ic }}.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/{{ x.ic }}.svg') center / contain no-repeat"></span>{{ x.t }}</div></sc-for></div></sc-if>
|
||||
<div data-act="nav-{{ n.key }}" style="display:flex;align-items:center;gap:10px;height:32px;padding:0 10px;background:{{ n.bg }};color:{{ n.fg }};font-weight:{{ n.fw }}"><span aria-hidden="true" style="display:inline-block;width:16px;height:16px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/{{ n.icon }}.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/{{ n.icon }}.svg') center / contain no-repeat"></span>{{ n.t }}<sc-if value="{{ n.badge }}"><span style="margin-left:auto;height:18px;padding:0 6px;display:inline-flex;align-items:center;background:var(--ui-info);color:var(--ui-bg);font:500 11px 'IBM Plex Sans',sans-serif">Update</span></sc-if><sc-if value="{{ n.chev }}"><span aria-hidden="true" style="margin-left:{{ n.chevML }};display:inline-block;flex-shrink:0;width:14px;height:14px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/{{ n.chev }}.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/{{ n.chev }}.svg') center / contain no-repeat"></span></sc-if></div><sc-if value="{{ n.sub }}"><div style="display:flex;flex-direction:column;gap:2px;margin-left:19px;border-left:1px solid var(--ui-border)"><span style="padding:6px 10px 2px 12px;font-size:11px;line-height:16px;font-weight:600;letter-spacing:.04em;text-transform:uppercase;color:var(--ui-text-muted)">Media</span><sc-for list="{{ n.subs }}" as="x" hint-placeholder-count="2"><div data-act="nav-{{ x.t }}" style="display:flex;align-items:center;gap:10px;height:32px;padding:0 10px 0 12px;background:{{ x.bg }};color:{{ x.fg }};font-weight:{{ x.fw }}"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:14px;height:14px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/{{ x.ic }}.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/{{ x.ic }}.svg') center / contain no-repeat"></span>{{ x.t }}</div></sc-for><sc-if value="{{ n.hasSites }}"><span style="padding:6px 10px 2px 12px;font-size:11px;line-height:16px;font-weight:600;letter-spacing:.04em;text-transform:uppercase;color:var(--ui-text-muted)">Publishing</span></sc-if><sc-for list="{{ n.subs2 }}" as="x2" hint-placeholder-count="1"><div data-act="nav-{{ x2.t }}" style="display:flex;align-items:center;gap:10px;height:32px;padding:0 10px 0 12px;background:{{ x2.bg }};color:{{ x2.fg }};font-weight:{{ x2.fw }}"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:14px;height:14px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/{{ x2.ic }}.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/{{ x2.ic }}.svg') center / contain no-repeat"></span>{{ x2.t }}</div></sc-for></div></sc-if>
|
||||
</sc-for>
|
||||
<div style="flex:1"></div>
|
||||
<sc-if value="{{ s.boot }}"><div style="display:flex;align-items:center;gap:10px;height:40px;padding:0 6px"><span style="width:26px;height:26px;background:var(--ui-bg-accented)"></span><span style="width:80px;height:12px;background:var(--ui-bg-accented)"></span></div></sc-if>
|
||||
@@ -83,8 +83,10 @@
|
||||
<div style="display:flex;align-items:flex-end;gap:16px;flex-wrap:wrap"><div style="flex:1;min-width:200px;display:flex;flex-direction:column;gap:2px"><span style="font:600 20px/28px 'IBM Plex Sans',sans-serif;color:var(--ui-text-highlighted)">Articles</span><span style="color:var(--ui-text-muted)">Everything you've written, online and in draft.</span></div><sc-if value="{{ desk }}"><span data-act="new" style="height:32px;padding:0 12px;display:flex;align-items:center;gap:6px;background:var(--ui-primary);color:var(--ui-bg);font-weight:500"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:16px;height:16px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/plus.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/plus.svg') center / contain no-repeat"></span>New article</span></sc-if></div>
|
||||
<div style="display:flex;flex-direction:{{ tbDir }};gap:{{ tbGap }};border-bottom:{{ tbBorder }}">
|
||||
<sc-if value="{{ mob }}"><span style="height:44px;padding:0 4px 0 12px;display:flex;align-items:center;gap:8px;border:1px solid var(--ui-border-accented);background:var(--ui-bg);color:{{ qFg }};font-size:16px"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:16px;height:16px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/search.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/search.svg') center / contain no-repeat"></span><span style="flex:1">{{ qText }}</span><sc-if value="{{ s.list.q }}"><span style="width:36px;height:36px;display:flex;align-items:center;justify-content:center;color:var(--ui-text-muted)"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:16px;height:16px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/x.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/x.svg') center / contain no-repeat"></span></span></sc-if></span></sc-if>
|
||||
<sc-if value="{{ mob }}"><span role="switch" aria-checked="{{ naOn }}" style="display:flex;flex-direction:column"><span style="height:44px;padding:0 10px;display:flex;align-items:center;gap:8px;border:1px solid {{ naBd }};background:{{ naBg }};color:{{ naFg }};font-size:15px;font-weight:{{ naFw }}"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:14px;height:14px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/lightbulb.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/lightbulb.svg') center / contain no-repeat"></span>Needs attention<span style="font:500 11px 'IBM Plex Mono',monospace">{{ naN }}</span></span></span></sc-if><sc-if value="{{ multiMob }}"><span style="position:relative;display:flex;flex-direction:column;"><span style="height:44px;padding:0 10px;display:flex;align-items:center;gap:8px;border:1px solid var(--ui-border-accented);background:var(--ui-bg);color:{{ sfFg }};font-size:16px;"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:14px;height:14px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/globe.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/globe.svg') center / contain no-repeat"></span><span style="flex:1">{{ sfText }}</span><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:14px;height:14px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/chevron-down.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/chevron-down.svg') center / contain no-repeat"></span></span><sc-if value="{{ sfMenu }}"><div role="listbox" aria-label="Site" style="position:absolute;left:0;right:0;top:48px;z-index:5;background:var(--ui-bg);border:1px solid var(--ui-border);box-shadow:var(--rc-shadow-pop);padding:4px"><sc-for list="{{ sfOpts }}" as="o" hint-placeholder-count="3"><div role="option" aria-selected="{{ o.on }}" style="height:44px;padding:0 8px;display:flex;align-items:center;justify-content:space-between;background:{{ o.bg }};color:var(--ui-text-highlighted)">{{ o.t }}<span style="opacity:{{ o.op }};display:flex"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:14px;height:14px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/check.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/check.svg') center / contain no-repeat"></span></span></div></sc-for></div></sc-if></span></sc-if>
|
||||
<div style="display:flex;gap:20px;flex:1;border-bottom:{{ tabBorder }}"><sc-for list="{{ tabs }}" as="t" hint-placeholder-count="3"><span style="height:{{ tabH }};display:flex;align-items:center;gap:6px;border-bottom:2px solid {{ t.line }};margin-bottom:-1px;font-weight:{{ t.fw }};color:{{ t.fg }};font-size:{{ tabF }}">{{ t.t }}<span style="font:500 11px 'IBM Plex Mono',monospace;color:var(--ui-text-muted)">{{ t.n }}</span></span></sc-for></div>
|
||||
<sc-if value="{{ desk }}"><span style="width:260px;height:32px;margin-bottom:6px;padding:0 4px 0 10px;display:flex;align-items:center;gap:8px;border:1px solid var(--ui-border-accented);background:var(--ui-bg);color:{{ qFg }}"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:14px;height:14px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/search.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/search.svg') center / contain no-repeat"></span><span style="flex:1">{{ qText }}</span><sc-if value="{{ s.list.q }}"><span style="width:24px;height:24px;display:flex;align-items:center;justify-content:center;color:var(--ui-text-muted)"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:14px;height:14px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/x.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/x.svg') center / contain no-repeat"></span></span></sc-if></span></sc-if>
|
||||
<sc-if value="{{ desk }}"><span role="switch" aria-checked="{{ naOn }}" style="margin-bottom:6px;display:flex"><span style="height:32px;padding:0 10px;display:flex;align-items:center;gap:8px;border:1px solid {{ naBd }};background:{{ naBg }};color:{{ naFg }};font-size:13px;font-weight:{{ naFw }}"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:14px;height:14px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/lightbulb.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/lightbulb.svg') center / contain no-repeat"></span>Needs attention<span style="font:500 11px 'IBM Plex Mono',monospace">{{ naN }}</span></span></span></sc-if><sc-if value="{{ desk }}"><span style="width:260px;height:32px;margin-bottom:6px;padding:0 4px 0 10px;display:flex;align-items:center;gap:8px;border:1px solid var(--ui-border-accented);background:var(--ui-bg);color:{{ qFg }}"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:14px;height:14px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/search.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/search.svg') center / contain no-repeat"></span><span style="flex:1">{{ qText }}</span><sc-if value="{{ s.list.q }}"><span style="width:24px;height:24px;display:flex;align-items:center;justify-content:center;color:var(--ui-text-muted)"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:14px;height:14px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/x.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/x.svg') center / contain no-repeat"></span></span></sc-if></span></sc-if>
|
||||
<sc-if value="{{ multiDesk }}"><span style="position:relative;display:flex;flex-direction:column;width:150px;margin-bottom:6px;"><span style="height:32px;padding:0 10px;display:flex;align-items:center;gap:8px;border:1px solid var(--ui-border-accented);background:var(--ui-bg);color:{{ sfFg }};"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:14px;height:14px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/globe.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/globe.svg') center / contain no-repeat"></span><span style="flex:1">{{ sfText }}</span><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:14px;height:14px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/chevron-down.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/chevron-down.svg') center / contain no-repeat"></span></span><sc-if value="{{ sfMenu }}"><div role="listbox" aria-label="Site" style="position:absolute;left:0;right:0;top:36px;z-index:5;background:var(--ui-bg);border:1px solid var(--ui-border);box-shadow:var(--rc-shadow-pop);padding:4px"><sc-for list="{{ sfOpts }}" as="o" hint-placeholder-count="3"><div role="option" aria-selected="{{ o.on }}" style="height:32px;padding:0 8px;display:flex;align-items:center;justify-content:space-between;background:{{ o.bg }};color:var(--ui-text-highlighted)">{{ o.t }}<span style="opacity:{{ o.op }};display:flex"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:14px;height:14px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/check.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/check.svg') center / contain no-repeat"></span></span></div></sc-for></div></sc-if></span></sc-if>
|
||||
</div>
|
||||
<sc-if value="{{ s.list.empty }}">
|
||||
<div style="background:var(--ui-bg);border:1px solid var(--ui-border);padding:56px 24px;display:flex;flex-direction:column;align-items:center;gap:12px;text-align:center"><span style="width:44px;height:44px;display:flex;align-items:center;justify-content:center;background:var(--ui-bg-elevated);color:var(--ui-text-toned)"><span aria-hidden="true" style="display:inline-block;width:20px;height:20px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/{{ s.list.empty.icon }}.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/{{ s.list.empty.icon }}.svg') center / contain no-repeat"></span></span><span style="font-weight:600;font-size:15px;color:var(--ui-text-highlighted)">{{ s.list.empty.title }}</span><span style="color:var(--ui-text-muted);max-width:280px">{{ s.list.empty.text }}</span><span data-act="empty" style="height:{{ btnH }};padding:0 12px;display:flex;align-items:center;font-weight:500;background:{{ emptyBg }};color:{{ emptyFg }};border:1px solid {{ emptyBd }}">{{ s.list.empty.action }}</span></div>
|
||||
@@ -93,13 +95,14 @@
|
||||
<sc-if value="{{ pgNote }}"><div role="status" style="display:flex;align-items:center;gap:10px;padding:10px 14px;background:var(--rc-info-soft);color:var(--ui-info)"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:16px;height:16px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/info.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/info.svg') center / contain no-repeat"></span><span style="flex:1;color:var(--ui-text-toned)">{{ pgNote }}</span></div></sc-if>
|
||||
<sc-if value="{{ showTable }}">
|
||||
<div style="background:var(--ui-bg);border:1px solid var(--ui-border)">
|
||||
<div style="display:grid;grid-template-columns:minmax(0,1fr) 110px 130px 140px 44px;height:36px;align-items:center;padding:0 12px;background:var(--ui-bg-elevated);color:var(--ui-text-muted);font-weight:500"><span>Title</span><span>Status</span><span>Created</span><span style="display:flex;align-items:center;gap:4px;color:var(--ui-text-highlighted)">Updated<span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:12px;height:12px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/arrow-down.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/arrow-down.svg') center / contain no-repeat"></span></span><span></span></div>
|
||||
<div style="display:grid;grid-template-columns:{{ gridCols }};height:36px;align-items:center;padding:0 12px;background:var(--ui-bg-elevated);color:var(--ui-text-muted);font-weight:500"><span>Title</span><sc-if value="{{ authorsCol }}"><span>Authors</span></sc-if><sc-if value="{{ multi }}"><span>Site</span></sc-if><span>Status</span><span>Created</span><span style="display:flex;align-items:center;gap:4px;color:var(--ui-text-highlighted)">Updated<span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:12px;height:12px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/arrow-down.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/arrow-down.svg') center / contain no-repeat"></span></span><span></span></div>
|
||||
<sc-for list="{{ rows }}" as="a" hint-placeholder-count="6">
|
||||
<div data-act="open-{{ a.id }}" style="display:grid;grid-template-columns:minmax(0,1fr) 110px 130px 140px 44px;height:44px;align-items:center;padding:0 12px;border-top:1px solid var(--ui-border);background:{{ a.bg }};opacity:{{ a.op }};position:relative">
|
||||
<sc-if value="{{ a.skel }}"><span style="height:12px;width:60%;background:var(--ui-bg-accented)"></span><span style="width:60px;height:20px;background:var(--ui-bg-accented)"></span><span style="width:80px;height:12px;background:var(--ui-bg-accented)"></span><span style="width:80px;height:12px;background:var(--ui-bg-accented)"></span><span></span></sc-if>
|
||||
<div data-act="open-{{ a.id }}" style="display:grid;grid-template-columns:{{ gridCols }};height:44px;align-items:center;padding:0 12px;border-top:1px solid var(--ui-border);background:{{ a.bg }};opacity:{{ a.op }};position:relative">
|
||||
<sc-if value="{{ a.skel }}"><span style="height:12px;width:60%;background:var(--ui-bg-accented)"></span><sc-if value="{{ authorsCol }}"><span style="width:60px;height:24px;background:var(--ui-bg-accented)"></span></sc-if><sc-if value="{{ multi }}"><span style="width:70px;height:12px;background:var(--ui-bg-accented)"></span></sc-if><span style="width:60px;height:20px;background:var(--ui-bg-accented)"></span><span style="width:80px;height:12px;background:var(--ui-bg-accented)"></span><span style="width:80px;height:12px;background:var(--ui-bg-accented)"></span><span></span></sc-if>
|
||||
<sc-if value="{{ a.t }}">
|
||||
<span style="font-weight:500;color:var(--ui-text-highlighted);overflow:hidden;text-overflow:ellipsis;white-space:nowrap;padding-right:12px">{{ a.t }}</span>
|
||||
<span><sc-if value="{{ a.busy }}"><span style="height:22px;padding:0 7px;display:inline-flex;align-items:center;gap:4px;border:1px solid var(--ui-border-accented);color:var(--ui-text-muted);font-size:12px;font-weight:500"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:12px;height:12px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/loader-circle.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/loader-circle.svg') center / contain no-repeat"></span>{{ a.busy }}</span></sc-if><sc-if value="{{ a.showOn }}"><span style="height:22px;padding:0 7px;display:inline-flex;align-items:center;gap:4px;background:var(--ui-bg-inverted);color:var(--ui-text-inverted);font-size:12px;font-weight:500"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:12px;height:12px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/globe.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/globe.svg') center / contain no-repeat"></span>Online</span></sc-if><sc-if value="{{ a.showDraft }}"><span style="height:22px;padding:0 7px;display:inline-flex;align-items:center;gap:4px;border:1px solid var(--ui-border-accented);color:var(--ui-text-toned);font-size:12px;font-weight:500"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:12px;height:12px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/pencil-line.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/pencil-line.svg') center / contain no-repeat"></span>Draft</span></sc-if></span>
|
||||
<sc-if value="{{ authorsCol }}"><span title="{{ a.auNames }}" style="display:flex;align-items:center;min-width:0"><sc-if value="{{ a.hasAu }}"><sc-for list="{{ a.avs }}" as="v" hint-placeholder-count="2"><span style="width:24px;height:24px;margin-left:{{ v.ml }};flex-shrink:0;display:flex;align-items:center;justify-content:center;background:{{ v.bg }};color:var(--ui-text-highlighted);border:2px solid var(--ui-bg);font:600 10px/1 'IBM Plex Sans',sans-serif">{{ v.i }}</span></sc-for><sc-if value="{{ a.auMore }}"><span style="margin-left:6px;font-size:12px;color:var(--ui-text-muted)">{{ a.auMore }}</span></sc-if></sc-if><sc-if value="{{ a.noAu }}"><span aria-label="No authors" style="color:var(--ui-text-dimmed)">—</span></sc-if></span></sc-if><sc-if value="{{ multi }}"><span style="color:var(--ui-text-toned);overflow:hidden;text-overflow:ellipsis;white-space:nowrap;padding-right:12px">{{ a.site }}</span></sc-if>
|
||||
<span><sc-if value="{{ a.busy }}"><span style="height:22px;padding:0 7px;display:inline-flex;align-items:center;gap:4px;border:1px solid var(--ui-border-accented);color:var(--ui-text-muted);font-size:12px;font-weight:500"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:12px;height:12px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/loader-circle.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/loader-circle.svg') center / contain no-repeat"></span>{{ a.busy }}</span></sc-if><sc-if value="{{ a.showOn }}"><span style="height:22px;padding:0 7px;display:inline-flex;align-items:center;gap:4px;background:var(--ui-bg-inverted);color:var(--ui-text-inverted);font-size:12px;font-weight:500"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:12px;height:12px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/globe.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/globe.svg') center / contain no-repeat"></span>Online</span></sc-if><sc-if value="{{ a.showDraft }}"><span style="height:22px;padding:0 7px;display:inline-flex;align-items:center;gap:4px;border:1px solid var(--ui-border-accented);color:var(--ui-text-toned);font-size:12px;font-weight:500"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:12px;height:12px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/pencil-line.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/pencil-line.svg') center / contain no-repeat"></span>Draft</span></sc-if><sc-if value="{{ a.seoSug }}"><span title="{{ a.seoTitle }}" style="margin-left:6px;height:22px;padding:0 6px;display:inline-flex;align-items:center;gap:4px;background:var(--rc-warning-soft);color:var(--ui-warning);font-size:12px;font-weight:500"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:12px;height:12px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/lightbulb.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/lightbulb.svg') center / contain no-repeat"></span>{{ a.seoN }}</span></sc-if><sc-if value="{{ a.seoHid }}"><span title="Hidden from search engines" style="margin-left:6px;height:22px;padding:0 6px;display:inline-flex;align-items:center;gap:4px;border:1px solid var(--ui-border-accented);color:var(--ui-text-toned);font-size:12px;font-weight:500"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:12px;height:12px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/eye-off.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/eye-off.svg') center / contain no-repeat"></span>Hidden</span></sc-if></span>
|
||||
<span style="color:var(--ui-text-muted)">{{ a.c }}</span><span style="color:var(--ui-text-muted)">{{ a.u }}</span>
|
||||
<span data-act="menu-{{ a.id }}" style="width:32px;height:32px;display:flex;align-items:center;justify-content:center;color:var(--ui-text-muted);background:{{ a.menuBg }}"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:16px;height:16px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/ellipsis.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/ellipsis.svg') center / contain no-repeat"></span></span>
|
||||
<sc-if value="{{ a.menu }}"><div role="menu" style="position:absolute;right:12px;top:40px;z-index:2;width:220px;background:var(--ui-bg);border:1px solid var(--ui-border);box-shadow:var(--rc-shadow-pop);padding:4px"><div data-act="open-{{ a.id }}" style="height:32px;padding:0 8px;display:flex;align-items:center;gap:8px;background:var(--ui-bg-elevated);color:var(--ui-text-highlighted)"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:16px;height:16px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/pencil.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/pencil.svg') center / contain no-repeat"></span>Edit</div><div data-act="pub-{{ a.id }}" style="height:32px;padding:0 8px;display:flex;align-items:center;gap:8px"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:16px;height:16px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/{{ a.menuIcon }}.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/{{ a.menuIcon }}.svg') center / contain no-repeat"></span>{{ a.menuPub }}</div><div data-act="copyurl" style="height:32px;padding:0 8px;display:flex;align-items:center;gap:8px"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:16px;height:16px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/link.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/link.svg') center / contain no-repeat"></span>Copy API URL</div><div style="height:1px;background:var(--ui-border);margin:4px 0"></div><div data-act="del-{{ a.id }}" style="height:32px;padding:0 8px;display:flex;align-items:center;gap:8px;color:var(--ui-error)"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:16px;height:16px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/trash-2.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/trash-2.svg') center / contain no-repeat"></span>Delete…</div></div></sc-if>
|
||||
@@ -121,7 +124,7 @@
|
||||
<sc-for list="{{ rows }}" as="a" hint-placeholder-count="6">
|
||||
<div data-act="open-{{ a.id }}" style="position:relative;display:flex;align-items:center;gap:8px;padding:12px 4px 12px 16px;border-bottom:1px solid var(--ui-border);min-height:68px;opacity:{{ a.op }}">
|
||||
<sc-if value="{{ a.skel }}"><div style="flex:1;display:flex;flex-direction:column;gap:8px"><span style="width:70%;height:14px;background:var(--ui-bg-accented)"></span><span style="width:40%;height:12px;background:var(--ui-bg-accented)"></span></div></sc-if>
|
||||
<sc-if value="{{ a.t }}"><div style="flex:1;min-width:0;display:flex;flex-direction:column;gap:6px"><span style="font-weight:500;font-size:15px;line-height:21px;color:var(--ui-text-highlighted)">{{ a.t }}</span><div style="display:flex;align-items:center;gap:10px;font-size:12px;color:var(--ui-text-muted)"><sc-if value="{{ a.busy }}"><span style="height:20px;padding:0 6px;display:inline-flex;align-items:center;gap:4px;border:1px solid var(--ui-border-accented);font-weight:500"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:12px;height:12px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/loader-circle.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/loader-circle.svg') center / contain no-repeat"></span>{{ a.busy }}</span></sc-if><sc-if value="{{ a.showOn }}"><span style="height:20px;padding:0 6px;display:inline-flex;align-items:center;gap:4px;background:var(--ui-bg-inverted);color:var(--ui-text-inverted);font-weight:500"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:12px;height:12px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/globe.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/globe.svg') center / contain no-repeat"></span>Online</span></sc-if><sc-if value="{{ a.showDraft }}"><span style="height:20px;padding:0 6px;display:inline-flex;align-items:center;gap:4px;border:1px solid var(--ui-border-accented);color:var(--ui-text-toned);font-weight:500"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:12px;height:12px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/pencil-line.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/pencil-line.svg') center / contain no-repeat"></span>Draft</span></sc-if><span>Updated {{ a.u }}</span></div></div><span data-act="menu-{{ a.id }}" style="width:44px;height:44px;display:flex;align-items:center;justify-content:center;color:var(--ui-text-muted)"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:18px;height:18px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/ellipsis-vertical.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/ellipsis-vertical.svg') center / contain no-repeat"></span></span></sc-if><sc-if value="{{ a.menu }}"><div role="menu" style="position:absolute;right:8px;top:56px;z-index:2;width:220px;background:var(--ui-bg);border:1px solid var(--ui-border);box-shadow:var(--rc-shadow-pop);padding:4px"><div data-act="open-{{ a.id }}" style="height:32px;padding:0 8px;display:flex;align-items:center;gap:8px;background:var(--ui-bg-elevated);color:var(--ui-text-highlighted)"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:16px;height:16px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/pencil.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/pencil.svg') center / contain no-repeat"></span>Edit</div><div data-act="pub-{{ a.id }}" style="height:32px;padding:0 8px;display:flex;align-items:center;gap:8px"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:16px;height:16px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/{{ a.menuIcon }}.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/{{ a.menuIcon }}.svg') center / contain no-repeat"></span>{{ a.menuPub }}</div><div data-act="copyurl" style="height:32px;padding:0 8px;display:flex;align-items:center;gap:8px"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:16px;height:16px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/link.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/link.svg') center / contain no-repeat"></span>Copy API URL</div><div style="height:1px;background:var(--ui-border);margin:4px 0"></div><div data-act="del-{{ a.id }}" style="height:32px;padding:0 8px;display:flex;align-items:center;gap:8px;color:var(--ui-error)"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:16px;height:16px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/trash-2.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/trash-2.svg') center / contain no-repeat"></span>Delete…</div></div></sc-if>
|
||||
<sc-if value="{{ a.t }}"><div style="flex:1;min-width:0;display:flex;flex-direction:column;gap:6px"><span style="font-weight:500;font-size:15px;line-height:21px;color:var(--ui-text-highlighted)">{{ a.t }}</span><div style="display:flex;align-items:center;gap:10px;font-size:12px;color:var(--ui-text-muted)"><sc-if value="{{ a.busy }}"><span style="height:20px;padding:0 6px;display:inline-flex;align-items:center;gap:4px;border:1px solid var(--ui-border-accented);font-weight:500"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:12px;height:12px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/loader-circle.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/loader-circle.svg') center / contain no-repeat"></span>{{ a.busy }}</span></sc-if><sc-if value="{{ a.showOn }}"><span style="height:20px;padding:0 6px;display:inline-flex;align-items:center;gap:4px;background:var(--ui-bg-inverted);color:var(--ui-text-inverted);font-weight:500"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:12px;height:12px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/globe.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/globe.svg') center / contain no-repeat"></span>Online</span></sc-if><sc-if value="{{ a.showDraft }}"><span style="height:20px;padding:0 6px;display:inline-flex;align-items:center;gap:4px;border:1px solid var(--ui-border-accented);color:var(--ui-text-toned);font-weight:500"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:12px;height:12px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/pencil-line.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/pencil-line.svg') center / contain no-repeat"></span>Draft</span></sc-if><sc-if value="{{ a.seoSug }}"><span title="{{ a.seoTitle }}" style="height:20px;padding:0 6px;display:inline-flex;align-items:center;gap:4px;background:var(--rc-warning-soft);color:var(--ui-warning);font-size:12px;font-weight:500"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:12px;height:12px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/lightbulb.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/lightbulb.svg') center / contain no-repeat"></span>{{ a.seoN }}</span></sc-if><sc-if value="{{ a.seoHid }}"><span title="Hidden from search engines" style="height:20px;padding:0 6px;display:inline-flex;align-items:center;gap:4px;border:1px solid var(--ui-border-accented);color:var(--ui-text-toned);font-size:12px;font-weight:500"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:12px;height:12px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/eye-off.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/eye-off.svg') center / contain no-repeat"></span>Hidden</span></sc-if><span>Updated {{ a.u }}</span></div><sc-if value="{{ authorsCol }}"><div style="display:flex;align-items:center;gap:8px;font-size:12px;color:var(--ui-text-muted);min-width:0"><sc-if value="{{ a.hasAu }}"><span style="display:flex;align-items:center"><sc-for list="{{ a.avs }}" as="v" hint-placeholder-count="2"><span style="width:22px;height:22px;margin-left:{{ v.ml }};flex-shrink:0;display:flex;align-items:center;justify-content:center;background:{{ v.bg }};color:var(--ui-text-highlighted);border:2px solid var(--ui-bg);font:600 9px/1 'IBM Plex Sans',sans-serif">{{ v.i }}</span></sc-for></span></sc-if><span style="overflow:hidden;text-overflow:ellipsis;white-space:nowrap">{{ a.auFirst }}</span><sc-if value="{{ multi }}"><span>· {{ a.site }}</span></sc-if></div></sc-if></div><span data-act="menu-{{ a.id }}" style="width:44px;height:44px;display:flex;align-items:center;justify-content:center;color:var(--ui-text-muted)"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:18px;height:18px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/ellipsis-vertical.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/ellipsis-vertical.svg') center / contain no-repeat"></span></span></sc-if><sc-if value="{{ a.menu }}"><div role="menu" style="position:absolute;right:8px;top:56px;z-index:2;width:220px;background:var(--ui-bg);border:1px solid var(--ui-border);box-shadow:var(--rc-shadow-pop);padding:4px"><div data-act="open-{{ a.id }}" style="height:32px;padding:0 8px;display:flex;align-items:center;gap:8px;background:var(--ui-bg-elevated);color:var(--ui-text-highlighted)"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:16px;height:16px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/pencil.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/pencil.svg') center / contain no-repeat"></span>Edit<Line truncated
|
||||
</div>
|
||||
</sc-for>
|
||||
</div>
|
||||
@@ -186,8 +189,9 @@
|
||||
<sc-if value="{{ desk }}">
|
||||
<div style="width:280px;flex-shrink:0;border-left:1px solid var(--ui-border);background:var(--ui-bg);padding:20px;display:flex;flex-direction:column;gap:16px">
|
||||
<span style="font-weight:600;font-size:14px;color:var(--ui-text-highlighted)">Details</span>
|
||||
<sc-if value="{{ s.ed.loading }}"><div style="display:flex;flex-direction:column;gap:10px"><span style="height:12px;background:var(--ui-bg-accented)"></span><span style="height:12px;background:var(--ui-bg-accented)"></span><span style="height:12px;width:60%;background:var(--ui-bg-accented)"></span></div></sc-if>
|
||||
<sc-if value="{{ s.ed.loading }}"><div style="display:flex;flex-direction:column;gap:12px;padding-bottom:16px;border-bottom:1px solid var(--ui-border)"><div style="display:flex;align-items:center;gap:8px;min-height:24px;color:var(--ui-text-highlighted)"><span style="display:flex;transform:rotate(-90deg)"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:14px;height:14px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/chevron-down.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/chevron-down.svg') center / contain no-repeat"></span></span><span style="font-weight:600;font-size:14px">Site and authors</span></div><span style="margin-left:22px;width:40%;height:12px;background:var(--ui-bg-accented)"></span></div><div style="display:flex;flex-direction:column;gap:10px"><span style="height:12px;background:var(--ui-bg-accented)"></span><span style="height:12px;background:var(--ui-bg-accented)"></span><span style="height:12px;width:60%;background:var(--ui-bg-accented)"></span></div></sc-if>
|
||||
<sc-if value="{{ edReady }}">
|
||||
<div style="display:flex;flex-direction:column;gap:12px;padding-bottom:16px;border-bottom:1px solid var(--ui-border)"><div data-act="meta-toggle" role="button" tabindex="0" aria-expanded="{{ metaOpen }}" aria-controls="meta-body" style="display:flex;align-items:center;gap:8px;min-height:24px;color:var(--ui-text-highlighted)"><span style="display:flex;transform:rotate({{ metaRot }})"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:14px;height:14px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/chevron-down.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/chevron-down.svg') center / contain no-repeat"></span></span><span style="font-weight:600;font-size:14px">Site and authors</span></div><sc-if value="{{ metaOpen }}"><div id="meta-body" style="display:flex;flex-direction:column;gap:16px">{{ edMeta }}</div></sc-if><sc-if value="{{ metaClosed }}"><span style="padding-left:22px;color:var(--ui-text-muted);overflow:hidden;text-overflow:ellipsis;white-space:nowrap">{{ metaSummary }}</span></sc-if></div><div style="display:flex;flex-direction:column;gap:12px;padding-bottom:16px;border-bottom:1px solid var(--ui-border)"><div data-act="seo-toggle" role="button" tabindex="0" aria-expanded="{{ seoOpen }}" aria-controls="seo-body" style="display:flex;align-items:center;gap:8px;min-height:24px;color:var(--ui-text-highlighted)"><span style="display:flex;transform:rotate({{ seoRot }})"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:14px;height:14px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/chevron-down.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/chevron-down.svg') center / contain no-repeat"></span></span><span style="font-weight:600;font-size:14px">Search and sharing</span></div><sc-if value="{{ seoOpen }}"><div id="seo-body" style="display:flex;flex-direction:column;gap:12px">{{ edSeo }}</div></sc-if><sc-if value="{{ seoClosed }}"><span style="padding-left:22px;color:{{ seoFg }};overflow:hidden;text-overflow:ellipsis;white-space:nowrap">{{ seoSummary }}</span></sc-if></div>
|
||||
<div style="display:grid;grid-template-columns:auto 1fr;gap:8px 12px"><span style="color:var(--ui-text-muted)">Created</span><span>12 Mar 2026, 09:14</span><span style="color:var(--ui-text-muted)">Updated</span><span>Today, 11:02</span><span style="color:var(--ui-text-muted)">ID</span><span style="font-family:'IBM Plex Mono',monospace">12</span><span style="color:var(--ui-text-muted)">Images</span><span>{{ imgCount }}</span></div>
|
||||
<div style="display:flex;flex-direction:column;gap:6px"><span style="color:var(--ui-text-muted)">Public API URL</span><span style="display:flex;align-items:center;gap:6px;padding:6px 8px;background:var(--ui-bg-elevated);font:400 12px 'IBM Plex Mono',monospace"><span style="flex:1">/v1/article/12</span><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:14px;height:14px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/copy.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/copy.svg') center / contain no-repeat"></span></span><span style="color:var(--ui-text-muted);font-size:12px;line-height:18px">{{ apiNote }}</span></div>
|
||||
<div style="display:flex;flex-direction:column;gap:4px;padding-top:12px;border-top:1px solid var(--ui-border)"><span style="color:var(--ui-text-muted)">Title</span><span style="font-size:12px;line-height:18px;color:var(--ui-text-toned)">Titles can't be changed after an article is created. To use a different title, create a new article and delete this one.</span></div>
|
||||
@@ -251,6 +255,7 @@
|
||||
<sc-if value="{{ s.upd.link }}"><span style="align-self:flex-start;display:flex;align-items:center;gap:6px;color:var(--ui-text-highlighted);text-decoration:underline;text-underline-offset:3px;font-weight:500">{{ s.upd.link }}<span aria-hidden="true" style="display:inline-block;width:14px;height:14px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/external-link.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/external-link.svg') center / contain no-repeat"></span></span></sc-if>
|
||||
</div>
|
||||
<div style="background:var(--ui-bg);border:1px solid var(--ui-border);padding:{{ cardPad }};display:flex;flex-direction:column;gap:12px"><div style="display:flex;flex-direction:column;gap:2px"><span style="font:600 15px/24px 'IBM Plex Sans',sans-serif;color:var(--ui-text-highlighted)">Media</span><span style="color:var(--ui-text-muted);text-wrap:pretty">Image sizes, cache and cleanup for your media library.</span></div><div style="display:flex;flex-direction:column"><div style="display:flex;align-items:center;gap:12px;min-height:44px;padding:8px 0;border-top:1px solid var(--ui-border);color:var(--ui-text-highlighted)"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:16px;height:16px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/layers.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/layers.svg') center / contain no-repeat"></span><div style="flex:1;min-width:0;display:flex;flex-direction:column"><span style="font-weight:500">Manage image variants</span><span style="color:var(--ui-text-muted)">Named sizes requested with ?v=</span></div><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:14px;height:14px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/chevron-right.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/chevron-right.svg') center / contain no-repeat"></span></div><div style="display:flex;align-items:center;gap:12px;min-height:44px;padding:8px 0;border-top:1px solid var(--ui-border);color:var(--ui-text-highlighted)"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:16px;height:16px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/database.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/database.svg') center / contain no-repeat"></span><div style="flex:1;min-width:0;display:flex;flex-direction:column"><span style="font-weight:500">Cache usage</span><span style="color:var(--ui-text-muted)">Generated images and disk space</span></div><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:14px;height:14px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/chevron-right.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/chevron-right.svg') center / contain no-repeat"></span></div></div></div>
|
||||
<sc-if value="{{ showSites }}"><div style="background:var(--ui-bg);border:1px solid var(--ui-border);padding:{{ cardPad }};display:flex;flex-direction:column;gap:12px"><div style="display:flex;flex-direction:column;gap:2px"><span style="font:600 15px/24px 'IBM Plex Sans',sans-serif;color:var(--ui-text-highlighted)">Publishing</span><span style="color:var(--ui-text-muted);text-wrap:pretty">Where your content is shown.</span></div><div style="display:flex;flex-direction:column"><div style="display:flex;align-items:center;gap:12px;min-height:44px;padding:8px 0;border-top:1px solid var(--ui-border);color:var(--ui-text-highlighted)"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:16px;height:16px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/globe.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/globe.svg') center / contain no-repeat"></span><div style="flex:1;min-width:0;display:flex;flex-direction:column"><span style="font-weight:500">Manage sites</span><span style="color:var(--ui-text-muted)">Base URLs, default image and robots policy</span></div><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:14px;height:14px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/chevron-right.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/chevron-right.svg') center / contain no-repeat"></span></div></div></div></sc-if>
|
||||
<div role="region" aria-labelledby="cleanup-h" style="background:var(--ui-bg);border:1px solid var(--ui-border);padding:{{ cardPad }};display:flex;flex-direction:column;gap:16px"><sc-if value="{{ cl.loading }}"><div aria-busy="true" style="display:flex;flex-direction:column;gap:16px"><span style="display:block;width:140px;height:16px;background:var(--ui-bg-accented)"></span><span style="display:block;width:90%;height:13px;background:var(--ui-bg-accented)"></span><span style="display:block;width:55%;height:13px;background:var(--ui-bg-accented)"></span><div style="display:flex;justify-content:space-between;align-items:center"><div style="display:flex;flex-direction:column;gap:6px"><span style="display:block;width:120px;height:13px;background:var(--ui-bg-accented)"></span><span style="display:block;width:180px;height:11px;background:var(--ui-bg-accented)"></span></div><span style="display:block;width:36px;height:20px;background:var(--ui-bg-accented)"></span></div><span style="display:block;width:60%;height:13px;background:var(--ui-bg-accented)"></span><div style="height:1px;background:var(--ui-border)"></div><div style="display:flex;justify-content:space-between;align-items:center"><div style="display:flex;flex-direction:column;gap:6px"><span style="display:block;width:100px;height:13px;background:var(--ui-bg-accented)"></span><span style="display:block;width:220px;height:11px;background:var(--ui-bg-accented)"></span></div><span style="display:block;width:140px;height:32px;background:var(--ui-bg-accented)"></span></div></div></sc-if><sc-if value="{{ cl.ready }}"><div style="display:flex;align-items:flex-start;gap:12px"><div style="flex:1;display:flex;flex-direction:column;gap:2px"><span id="cleanup-h" tabindex="-1" style="align-self:flex-start;font:600 15px/24px 'IBM Plex Sans',sans-serif;color:var(--ui-text-highlighted)">Media cleanup</span><span style="color:var(--ui-text-muted);text-wrap:pretty">Merge identical images so your library stays tidy. Articles that use a copy are switched to the most used one.</span></div><div style="height:24px;display:flex;align-items:center;flex-shrink:0"><sc-if value="{{ cl.saving }}"><span style="display:flex;align-items:center;gap:6px;font-size:12px;color:var(--ui-text-muted)"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:14px;height:14px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/loader-circle.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/loader-circle.svg') center / contain no-repeat;"></span>Saving…</span></sc-if><sc-if value="{{ cl.saved }}"><span role="status" style="display:flex;align-items:center;gap:6px;font-size:12px;color:var(--ui-success)"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:14px;height:14px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/check.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/check.svg') center / contain no-repeat;"></span>Saved</span></sc-if></div></div><sc-if value="{{ cl.ro }}"><div style="display:flex;gap:10px;padding:12px 14px;background:var(--rc-info-soft);color:var(--ui-info)"><span style="display:flex;padding-top:2px"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:16px;height:16px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/info.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/info.svg') center / contain no-repeat;"></span></span><span style="color:var(--ui-text-toned)">Only owners and admins can change this.</span></div></sc-if><div style="display:flex;flex-direction:{{ rowDir }};align-items:{{ rowAlign }};justify-content:{{ rowJust }};gap:{{ rowGap }}"><div style="display:flex;flex-direction:column;gap:2px;min-width:0"><span style="font-weight:500;color:var(--ui-text-highlighted)">Automatic purge</span><span style="font-size:12px;color:var(--ui-text-muted)">Runs in the background. Off by default.</span></div><div role="switch" aria-checked="{{ cl.on }}" style="display:flex;align-items:center;justify-content:center;width:{{ cl.swW }};height:{{ cl.swH }};flex-shrink:0;opacity:{{ cl.swOp }}"><div style="position:relative;width:36px;height:20px;border:1px solid {{ cl.swBd }};background:{{ cl.swBg }};outline:{{ cl.swRing }};outline-offset:2px"><div style="position:absolute;top:1px;left:{{ cl.knobL }};width:16px;height:16px;background:var(--ui-bg);border:1px solid {{ cl.knobBd }};box-sizing:border-box"></div></div></div></div><sc-if value="{{ cl.on }}"><div style="display:flex;flex-direction:{{ rowDir }};align-items:{{ rowAlign }};justify-content:{{ rowJust }};gap:{{ rowGap }}"><div style="display:flex;flex-direction:column;gap:2px;min-width:0"><span style="font-weight:500;color:var(--ui-text-highlighted)">Every</span><span style="font-size:12px;color:var(--ui-text-muted)">Between 1 and 365 days.</span></div><div style="display:flex;flex-direction:column;gaLine truncated
|
||||
<sc-if value="{{ rt.show }}"><div role="region" aria-labelledby="retention-h" style="background:var(--ui-bg);border:1px solid var(--ui-border);padding:{{ cardPad }};display:flex;flex-direction:column;gap:16px"><div style="display:flex;align-items:flex-start;gap:12px"><div style="flex:1;display:flex;flex-direction:column;gap:2px"><span id="retention-h" tabindex="-1" style="align-self:flex-start;font:600 15px/24px 'IBM Plex Sans',sans-serif;color:var(--ui-text-highlighted)">Retention</span><span style="color:var(--ui-text-muted);text-wrap:pretty">How long activity is kept, and how much log data to keep. Whichever limit is reached first removes the oldest events. Only owners can change it.</span></div><div style="height:24px;display:flex;align-items:center;flex-shrink:0"><sc-if value="{{ rt.saving }}"><span style="display:flex;align-items:center;gap:6px;font-size:12px;color:var(--ui-text-muted)"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:14px;height:14px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/loader-circle.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/loader-circle.svg') center / contain no-repeat;"></span>Saving…</span></sc-if><sc-if value="{{ rt.saved }}"><span role="status" style="display:flex;align-items:center;gap:6px;font-size:12px;color:var(--ui-success)"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:14px;height:14px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/check.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/check.svg') center / contain no-repeat;"></span>Saved</span></sc-if></div></div><sc-if value="{{ rt.err }}"><div style="display:flex;gap:10px;padding:12px 14px;background:var(--rc-error-soft);color:var(--ui-error)"><span style="display:flex;padding-top:2px"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:16px;height:16px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/circle-x.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/circle-x.svg') center / contain no-repeat;"></span></span><div style="flex:1;display:flex;flex-direction:column;gap:8px"><div style="display:flex;flex-direction:column;gap:2px"><span style="font-weight:600">Couldn't save the retention period</span><span style="color:var(--ui-text-toned)">Your previous setting is still in place.</span></div><span role="button" style="height:28px;padding:0 10px;display:flex;align-items:center;justify-content:center;gap:6px;border:1px solid var(--ui-border-accented);background:var(--ui-bg);color:var(--ui-text-highlighted);font-weight:500;font-size:12px;white-space:nowrap;opacity:1">Try again</span></div></div></sc-if><div style="display:flex;flex-direction:{{ rowDir }};align-items:{{ rowAlign }};justify-content:{{ rowJust }};gap:{{ rowGap }}"><div style="display:flex;flex-direction:column;gap:2px;min-width:0"><span style="font-weight:500;color:var(--ui-text-highlighted)">Keep activity for</span><span style="font-size:12px;color:var(--ui-text-muted)">{{ rt.help }}</span></div><div style="display:flex;align-items:center;width:{{ rt.selW }};min-height:{{ inH }};padding:0 12px;border:1px solid var(--ui-border-accented);background:var(--ui-bg);font-size:{{ inF }};color:var(--ui-text-highlighted)"><span style="flex:1">{{ rt.val }}</span><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:16px;height:16px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/chevron-down.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/chevron-down.svg') center / contain no-repeat;color:var(--ui-text-muted)"></span></div></div><div style="display:flex;align-items:center;gap:12px;color:var(--ui-text-muted);font-size:12px;font-weight:500"><span style="flex:1;height:1px;background:var(--ui-border)"></span><span>or</span><span style="flex:1;height:1px;background:var(--ui-border)"></span></div><div style="display:flex;flex-direction:{{ rowDir }};align-items:{{ rowAlign }};justify-content:{{ rowJust }};gap:{{ rowGap }}"><div style="display:flex;flex-direction:column;gap:2px;min-width:0"><span style="font-weight:500;color:var(--ui-text-highlighted)">Keep at most</span><span style="font-size:12px;color:var(--ui-text-muted)">{{ rt.sizeHelp }}</span></div><div style="display:flex;align-items:center;width:{{ rt.selW }};min-height:{{ inH }};padding:0 12px;border:1px solid var(--ui-border-accented);background:var(--ui-bg);font-size:{{ inF }};color:var(--ui-text-highlighted)"><span style="flex:1">{{ rt.sizeVal }}</span><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:16px;height:16px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/chevron-down.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/chevron-down.svg') center / contain no-repeat;cLine truncated
|
||||
</div>
|
||||
@@ -277,6 +282,12 @@
|
||||
<div style="display:flex;flex-direction:column;gap:2px"><span style="font-weight:600;font-size:14px;color:var(--ui-text-highlighted)">Account</span><span style="color:var(--ui-text-muted);text-wrap:pretty">Set when your account was created. You log in with your username, even after adding a display name.</span></div>
|
||||
<div style="display:grid;grid-template-columns:{{ pfCols }};gap:14px"><div style="display:flex;flex-direction:column;gap:6px;min-width:0"><span style="font-weight:500;color:var(--ui-text-highlighted)">Username</span><div aria-disabled="true" style="height:{{ inH }};padding:0 10px;display:flex;align-items:center;gap:8px;border:1px solid var(--ui-border);background:var(--ui-bg-elevated);color:var(--ui-text-toned);font-size:{{ inF }};cursor:not-allowed"><span style="flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap">marta</span><span style="display:flex;color:var(--ui-text-muted)"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:14px;height:14px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/lock.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/lock.svg') center / contain no-repeat"></span></span></div></div><div style="display:flex;flex-direction:column;gap:6px;min-width:0"><span style="font-weight:500;color:var(--ui-text-highlighted)">Email</span><div aria-disabled="true" style="height:{{ inH }};padding:0 10px;display:flex;align-items:center;gap:8px;border:1px solid var(--ui-border);background:var(--ui-bg-elevated);color:var(--ui-text-toned);font-size:{{ inF }};cursor:not-allowed"><span style="flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap">marta@renew.example</span><span style="display:flex;color:var(--ui-text-muted)"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:14px;height:14px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/lock.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/lock.svg') center / contain no-repeat"></span></span></div></div></div>
|
||||
</div>
|
||||
<div style="background:var(--ui-bg);border:1px solid var(--ui-border);padding:{{ cardPad }};display:flex;flex-direction:column;gap:14px"><div style="display:flex;flex-direction:column;gap:2px"><span style="font-weight:600;font-size:14px;color:var(--ui-text-highlighted)">Author profile</span><span style="color:var(--ui-text-muted);text-wrap:pretty">Your public byline on articles. It's separate from your account.</span></div>
|
||||
<sc-if value="{{ pAu.err }}"><div role="alert" style="display:flex;gap:10px;padding:12px 14px;background:var(--rc-error-soft);color:var(--ui-error)"><span style="display:flex;padding-top:2px"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:16px;height:16px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/circle-x.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/circle-x.svg') center / contain no-repeat"></span></span><div style="display:flex;flex-direction:column;gap:2px"><span style="font-weight:600">Couldn't create your author profile</span><span style="color:var(--ui-text-toned)">Try again in a moment.</span></div></div></sc-if>
|
||||
<sc-if value="{{ pAu.none }}"><span style="color:var(--ui-text-toned);text-wrap:pretty">You don't have an author profile yet. Create one to be credited on your own articles.</span><div style="display:flex;flex-direction:{{ pwDir }};align-items:{{ pwAlign }};gap:12px"><span style="height:{{ btnH }};padding:0 12px;display:flex;align-items:center;justify-content:center;gap:6px;background:var(--ui-primary);color:var(--ui-bg);font-weight:500;opacity:{{ pAu.op }}"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:16px;height:16px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/{{ pAu.icon }}.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/{{ pAu.icon }}.svg') center / contain no-repeat"></span>{{ pAu.btn }}</span><span style="color:var(--ui-text-muted);font-size:12px">Uses your display name, Marta Alves. You can change it afterwards.</span></div></sc-if>
|
||||
<sc-if value="{{ pAu.has }}"><div style="display:flex;align-items:center;gap:12px;flex-wrap:wrap"><span style="width:40px;height:40px;flex-shrink:0;display:flex;align-items:center;justify-content:center;background:var(--rc-sand);color:var(--rc-on-sand);border:1px solid var(--ui-border);font:600 14px/1 'IBM Plex Sans',sans-serif">MA</span><div style="flex:1;min-width:140px;display:flex;flex-direction:column"><span style="font-weight:500;color:var(--ui-text-highlighted)">Marta Alves</span><span style="font:400 12px/18px 'IBM Plex Mono',monospace;color:var(--ui-text-muted)">{{ pAu.slug }}</span></div><span style="height:{{ btnH }};padding:0 12px;display:flex;align-items:center;justify-content:center;gap:6px;border:1px solid var(--ui-border-accented);background:var(--ui-bg);color:var(--ui-text-highlighted);font-weight:500"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:16px;height:16px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/pencil.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/pencil.svg') center / contain no-repeat"></span>Edit author</span></div>
|
||||
<sc-if value="{{ pAu.slugNote }}"><div role="status" style="display:flex;gap:10px;padding:12px 14px;background:var(--rc-info-soft);color:var(--ui-info)"><span style="display:flex;padding-top:2px"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:16px;height:16px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/info.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/info.svg') center / contain no-repeat"></span></span><div style="display:flex;flex-direction:column;gap:2px"><span style="font-weight:600">Your slug is {{ pAu.slug }}</span><span style="color:var(--ui-text-toned)">marta-alves was already used by another author. You can change it in Edit author.</span></div></div></sc-if>
|
||||
<div style="display:flex;align-items:center;gap:6px;color:var(--ui-text-muted);font-size:12px"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:12px;height:12px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/link.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/link.svg') center / contain no-repeat"></span>Linked to your account. New articles start with this author.</div></sc-if></div>
|
||||
<div style="background:var(--ui-bg);border:1px solid var(--ui-border);padding:{{ cardPad }};display:flex;flex-direction:column;gap:14px">
|
||||
<div style="display:flex;flex-direction:column;gap:2px"><span style="font-weight:600;font-size:14px;color:var(--ui-text-highlighted)">Password</span><span style="color:var(--ui-text-muted);text-wrap:pretty">To change it, we'll email a reset link to marta@renew.example. The link works once, within 1 hour.</span></div>
|
||||
<div style="display:flex;flex-direction:{{ pwDir }};align-items:{{ pwAlign }};gap:12px"><div style="flex:1;min-width:0"><div style="display:flex;flex-direction:column;gap:6px;min-width:0"><span style="font-weight:500;color:var(--ui-text-highlighted)">Password</span><div aria-disabled="true" style="height:{{ inH }};padding:0 10px;display:flex;align-items:center;gap:8px;border:1px solid var(--ui-border);background:var(--ui-bg-elevated);color:var(--ui-text-toned);font-size:{{ inF }};cursor:not-allowed"><span style="flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;letter-spacing:0.12em">••••••••••••</span><span style="display:flex;color:var(--ui-text-muted)"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:14px;height:14px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/lock.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/lock.svg') center / contain no-repeat"></span></span></div></div></div><span data-act="pf-reset" style="height:{{ inH }};padding:0 14px;display:flex;align-items:center;justify-content:center;gap:6px;flex-shrink:0;border:1px solid var(--ui-border-accented);background:var(--ui-bg);color:var(--ui-text-highlighted);font-weight:500;white-space:nowrap;opacity:{{ rsBtn.op }}"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:16px;height:16px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/{{ rsBtn.icon }}.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/{{ rsBtn.icon }}.svg') center / contain no-repeat"></span>{{ rsBtn.t }}</span></div>
|
||||
@@ -357,8 +368,9 @@
|
||||
</sc-if>
|
||||
|
||||
{{ purgeDlg }}
|
||||
<sc-if value="{{ navDrawer }}"><div data-act="mnav-close" style="position:absolute;inset:0;z-index:60;display:flex;background:var(--rc-overlay)"><div role="navigation" aria-label="Main" style="width:300px;max-width:85%;height:100%;background:var(--ui-bg);box-shadow:var(--rc-shadow-modal);display:flex;flex-direction:column;padding:12px;gap:2px"><div style="display:flex;align-items:center;gap:10px;height:40px;padding:0 6px;margin-bottom:10px"><svg width="26" height="26" viewBox="0 0 16 16" shape-rendering="crispEdges"><rect width="16" height="16" fill="#111"></rect><path fill="#fff" fill-rule="evenodd" d="M4 3h6v1h1v1h1v3h-1v1h-1v1h1v1h1v2h-2v-2h-1v-1H6v3H4zm2 2v3h4V5z"></path></svg><span style="flex:1;font-weight:600;font-size:14px;color:var(--ui-text-highlighted)">RenewCMS</span></div><sc-for list="{{ nav }}" as="n" hint-placeholder-count="3"><div data-act="nav-{{ n.key }}" style="display:flex;align-items:center;gap:10px;height:44px;padding:0 10px;background:{{ n.bg }};color:{{ n.fg }};font-weight:{{ n.fw }}"><span aria-hidden="true" style="display:inline-block;width:16px;height:16px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/{{ n.icon }}.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/{{ n.icon }}.svg') center / contain no-repeat"></span><span style="flex:1">{{ n.t }}</span><sc-if value="{{ n.chev }}"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:14px;height:14px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/{{ n.chev }}.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/{{ n.chev }}.svg') center / contain no-repeat"></span></sc-if></div><sc-if value="{{ n.sub }}"><div style="display:flex;flex-direction:column;gap:2px;margin-left:19px;border-left:1px solid var(--ui-border)"><span style="padding:6px 10px 2px 12px;font-size:11px;line-height:16px;font-weight:600;letter-spacing:.04em;text-transform:uppercase;color:var(--ui-text-muted)">Media</span><sc-for list="{{ n.subs }}" as="x" hint-placeholder-count="2"><div data-act="nav-{{ x.t }}" style="display:flex;align-items:center;gap:10px;height:44px;padding:0 10px 0 12px;background:{{ x.bg }};color:{{ x.fg }};font-weight:{{ x.fw }}"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:14px;height:14px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/{{ x.ic }}.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/{{ x.ic }}.svg') center / contain no-repeat"></span>{{ x.t }}</div></sc-for></div></sc-if></sc-for><div style="flex:1"></div><div style="display:flex;align-items:center;gap:10px;height:44px;padding:0 6px;color:var(--ui-text-highlighted)"><span style="width:26px;height:26px;flex-shrink:0;background:var(--rc-sand);color:var(--rc-on-sand);display:flex;align-items:center;justify-content:center;font:600 11px 'IBM Plex Sans',sans-serif">{{ ini }}</span><span style="flex:1;font-weight:500">{{ who }}</span></div></div></div></sc-if>
|
||||
<sc-if value="{{ navDrawer }}"><div data-act="mnav-close" style="position:absolute;inset:0;z-index:60;display:flex;background:var(--rc-overlay)"><div role="navigation" aria-label="Main" style="width:300px;max-width:85%;height:100%;background:var(--ui-bg);box-shadow:var(--rc-shadow-modal);display:flex;flex-direction:column;padding:12px;gap:2px"><div style="display:flex;align-items:center;gap:10px;height:40px;padding:0 6px;margin-bottom:10px"><svg width="26" height="26" viewBox="0 0 16 16" shape-rendering="crispEdges"><rect width="16" height="16" fill="#111"></rect><path fill="#fff" fill-rule="evenodd" d="M4 3h6v1h1v1h1v3h-1v1h-1v1h1v1h1v2h-2v-2h-1v-1H6v3H4zm2 2v3h4V5z"></path></svg><span style="flex:1;font-weight:600;font-size:14px;color:var(--ui-text-highlighted)">RenewCMS</span></div><sc-for list="{{ nav }}" as="n" hint-placeholder-count="3"><div data-act="nav-{{ n.key }}" style="display:flex;align-items:center;gap:10px;height:44px;padding:0 10px;background:{{ n.bg }};color:{{ n.fg }};font-weight:{{ n.fw }}"><span aria-hidden="true" style="display:inline-block;width:16px;height:16px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/{{ n.icon }}.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/{{ n.icon }}.svg') center / contain no-repeat"></span><span style="flex:1">{{ n.t }}</span><sc-if value="{{ n.chev }}"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:14px;height:14px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/{{ n.chev }}.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/{{ n.chev }}.svg') center / contain no-repeat"></span></sc-if></div><sc-if value="{{ n.sub }}"><div style="display:flex;flex-direction:column;gap:2px;margin-left:19px;border-left:1px solid var(--ui-border)"><span style="padding:6px 10px 2px 12px;font-size:11px;line-height:16px;font-weight:600;letter-spacing:.04em;text-transform:uppercase;color:var(--ui-text-muted)">Media</span><sc-for list="{{ n.subs }}" as="x" hint-placeholder-count="2"><div data-act="nav-{{ x.t }}" style="display:flex;align-items:center;gap:10px;height:44px;padding:0 10px 0 12px;background:{{ x.bg }};color:{{ x.fg }};font-weight:{{ x.fw }}"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:14px;height:14px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/{{ x.ic }}.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/{{ x.ic }}.svg') center / contain no-repeat"></span>{{ x.t }}</div></sc-for><sc-if value="{{ n.hasSites }}"><span style="padding:6px 10px 2px 12px;font-size:11px;line-height:16px;font-weight:600;letter-spacing:.04em;text-transform:uppercase;color:var(--ui-text-muted)">Publishing</span></sc-if><sc-for list="{{ n.subs2 }}" as="x2" hint-placeholder-count="1"><div data-act="nav-{{ x2.t }}" style="display:flex;align-items:center;gap:10px;height:44px;padding:0 10px 0 12px;background:{{ x2.bg }};color:{{ x2.fg }};font-weight:{{ x2.fw }}"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:14px;height:14px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/{{ x2.ic }}.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/{{ x2.ic }}.svg') center / contain no-repeat"></span>{{ x2.t }}</div></sc-for></div></sc-if></sc-for><div style="flex:1"></div><div style="display:flex;align-items:center;gap:10px;height:44px;padding:0 6px;color:var(--ui-text-highlighted)"><span style="width:26px;height:26px;flex-shrink:0;background:var(--rc-sand);color:var(--rc-on-sand);display:flex;align-items:center;justify-content:center;font:600 11px 'IBM Plex Sans',sans-serif">{{ ini }}</span><span style="flex:1;font-weight:500">{{ who }}</span></div></div></div></sc-if>
|
||||
<sc-if value="{{ lk.sheet }}"><div style="position:absolute;inset:0;z-index:55;background:var(--rc-overlay);display:flex;align-items:flex-end"><div role="dialog" aria-label="Link" style="width:100%;background:var(--ui-bg);box-shadow:var(--rc-shadow-modal);display:flex;flex-direction:column"><div style="display:flex;justify-content:center;padding-top:8px"><span style="display:block;width:36px;height:4px;background:var(--ui-border-accented)"></span></div><div style="display:flex;flex-direction:column;gap:2px;padding:12px 16px 12px;border-bottom:1px solid var(--ui-border)"><span style="font-weight:600;font-size:16px;line-height:24px;color:var(--ui-text-highlighted)">timber windows</span><span style="font:400 12px/18px 'IBM Plex Mono',monospace;color:var(--ui-text-toned);overflow:hidden;text-overflow:ellipsis;white-space:nowrap">/articles/winter-checklist</span></div><div style="display:flex;flex-direction:column;padding:8px 0 16px"><span style="height:48px;padding:0 16px;display:flex;align-items:center;gap:12px;color:var(--ui-text-highlighted)"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:18px;height:18px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/pencil.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/pencil.svg') center / contain no-repeat"></span>Edit link</span><span style="height:48px;padding:0 16px;display:flex;align-items:center;gap:12px;color:var(--ui-text-highlighted)"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:18px;height:18px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/external-link.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/external-link.svg') center / contain no-repeat"></span>Open link</span><span style="height:48px;padding:0 16px;display:flex;align-items:center;gap:12px;color:var(--ui-error)"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:18px;height:18px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/unlink.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/unlink.svg') center / contain no-repeat"></span>Remove link</span></div></div></div></sc-if>
|
||||
<sc-if value="{{ edSheet }}"><div style="position:absolute;inset:0;z-index:55;background:var(--rc-overlay);display:flex;align-items:flex-end"><div role="dialog" aria-modal="true" aria-label="Details" style="width:100%;height:92%;background:var(--ui-bg);box-shadow:var(--rc-shadow-modal);display:flex;flex-direction:column"><div style="display:flex;justify-content:center;padding-top:8px;flex-shrink:0"><span style="display:block;width:36px;height:4px;background:var(--ui-border-accented)"></span></div><div style="padding:8px 16px 0 16px;display:flex;align-items:center;gap:12px;flex-shrink:0"><span style="flex:1;font:600 16px/24px 'IBM Plex Sans',sans-serif;color:var(--ui-text-highlighted)">Details</span><span data-act="modal-close" style="width:44px;height:44px;display:flex;align-items:center;justify-content:center;color:var(--ui-text-muted)"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:16px;height:16px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/x.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/x.svg') center / contain no-repeat"></span></span></div><div style="flex:1;min-height:0;overflow:hidden;padding:12px 16px 16px;display:flex;flex-direction:column;gap:16px"><div style="display:flex;flex-direction:column;gap:12px;padding-bottom:16px;border-bottom:1px solid var(--ui-border)"><div data-act="meta-toggle" role="button" tabindex="0" aria-expanded="{{ metaOpen }}" aria-controls="meta-body" style="display:flex;align-items:center;gap:8px;min-height:24px;color:var(--ui-text-highlighted)"><span style="display:flex;transform:rotate({{ metaRot }})"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:14px;height:14px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/chevron-down.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/chevron-down.svg') center / contain no-repeat"></span></span><span style="font-weight:600;font-size:14px">Site and authors</span></div><sc-if value="{{ metaOpen }}"><div id="meta-body" style="display:flex;flex-direction:column;gap:16px">{{ edMeta }}</div></sc-if><sc-if value="{{ metaClosed }}"><span style="padding-left:22px;color:var(--ui-text-muted);overflow:hidden;text-overflow:ellipsis;white-space:nowrap">{{ metaSummary }}</span></sc-if></div><div style="display:flex;flex-direction:column;gap:12px;padding-bottom:16px;border-bottom:1px solid var(--ui-border)"><div data-act="seo-toggle" role="button" tabindex="0" aria-expanded="{{ seoOpen }}" aria-controls="seo-body" style="display:flex;align-items:center;gap:8px;min-height:24px;color:var(--ui-text-highlighted)"><span style="display:flex;transform:rotate({{ seoRot }})"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:14px;height:14px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/chevron-down.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/chevron-down.svg') center / contain no-repeat"></span></span><span style="font-weight:600;font-size:14px">Search and sharing</span></div><sc-if value="{{ seoOpen }}"><div id="seo-body" style="display:flex;flex-direction:column;gap:12px">{{ edSeo }}</div></sc-if><sc-if value="{{ seoClosed }}"><span style="padding-left:22px;color:{{ seoFg }};overflow:hidden;text-overflow:ellipsis;white-space:nowrap">{{ seoSummary }}</span></sc-if></div><div style="display:grid;grid-template-columns:auto 1fr;gap:8px 12px"><span style="color:var(--ui-text-muted)">Created</span><span>12 Mar 2026, 09:14</span><span style="color:var(--ui-text-muted)">Updated</span><span>Today, 11:02</span><span style="color:var(--ui-text-muted)">ID</span><span style="font-family:'IBM Plex Mono',monospace">12</span></div><div style="display:flex;flex-direction:column;gap:6px"><span style="color:var(--ui-text-muted)">Public API URL</span><span style="padding:6px 8px;background:var(--ui-bg-elevated);font:400 12px 'IBM Plex Mono',monospace">/v1/article/12</span></div></div></div></div></sc-if>
|
||||
{{ slotOverlays }}
|
||||
<sc-if value="{{ hasToasts }}">
|
||||
<div style="position:absolute;z-index:60;display:flex;flex-direction:column;gap:8px;left:{{ tL }};right:{{ tR }};bottom:{{ tB }};width:{{ tW }}">
|
||||
@@ -375,14 +387,16 @@ class Component extends DCLogic {
|
||||
const s = this.props.s || {}
|
||||
const m = !!this.props.mobile
|
||||
const k = s.kind || 'home'
|
||||
const navItems = s.role === 'user' ? [['home', 'house', 'Home'], ['articles', 'file-text', 'Articles'], ['media', 'images', 'Media'], ['activity', 'history', 'Activity']] : [['home', 'house', 'Home'], ['articles', 'file-text', 'Articles'], ['media', 'images', 'Media'], ['users', 'users', 'Users'], ['activity', 'history', 'Activity'], ['integration', 'plug', 'Integration'], ['settings', 'settings', 'Settings']]
|
||||
const navItems = s.role === 'user' ? [['home', 'house', 'Home'], ['articles', 'file-text', 'Articles'], ['media', 'images', 'Media'], ['authors', 'feather', 'Authors'], ['activity', 'history', 'Activity']] : [['home', 'house', 'Home'], ['articles', 'file-text', 'Articles'], ['media', 'images', 'Media'], ['authors', 'feather', 'Authors'], ['users', 'users', 'Users'], ['activity', 'history', 'Activity'], ['integration', 'plug', 'Integration'], ['settings', 'settings', 'Settings']]
|
||||
const cr0 = s.crumbs || [], setOpen = s.nav === 'settings' || !!s.sideOpen, parentOn = (key) => s.nav === key && (key !== 'settings' || cr0.length <= 1)
|
||||
const nav = navItems.map(([key, icon, t]) => { const on = parentOn(key), open = key === 'settings' && setOpen; return { key, icon, t, bg: on ? 'var(--rc-sand)' : 'transparent', badge: key === 'settings' && !!s.navBadge, fg: on ? 'var(--rc-on-sand)' : open ? 'var(--ui-text-highlighted)' : 'var(--ui-text-toned)', fw: on || open ? 500 : 400, chev: key === 'settings' ? (open ? 'chevron-down' : 'chevron-right') : '', chevML: key === 'settings' && s.navBadge ? '8px' : 'auto', sub: open, subs: ['Variants', 'Cache'].map(x => { const o = cr0[cr0.length - 1] === x; return { t: x, ic: x === 'Variants' ? 'layers' : 'database', bg: o ? 'var(--rc-sand)' : 'transparent', fg: o ? 'var(--rc-on-sand)' : 'var(--ui-text-toned)', fw: o ? 500 : 400 } }) } })
|
||||
const nav = navItems.map(([key, icon, t]) => { const on = parentOn(key), open = key === 'settings' && setOpen; return { key, icon, t, bg: on ? 'var(--rc-sand)' : 'transparent', badge: key === 'settings' && !!s.navBadge, fg: on ? 'var(--rc-on-sand)' : open ? 'var(--ui-text-highlighted)' : 'var(--ui-text-toned)', fw: on || open ? 500 : 400, chev: key === 'settings' ? (open ? 'chevron-down' : 'chevron-right') : '', chevML: key === 'settings' && s.navBadge ? '8px' : 'auto', sub: open, hasSites: !s.role || s.role === 'owner', subs2: (!s.role || s.role === 'owner') ? (() => { const o = cr0[cr0.length - 1] === 'Sites'; return [{ t: 'Sites', ic: 'globe', bg: o ? 'var(--rc-sand)' : 'transparent', fg: o ? 'var(--rc-on-sand)' : 'var(--ui-text-toned)', fw: o ? 500 : 400 }] })() : [], subs: ['Variants', 'Cache'].map(x => { const o = cr0[cr0.length - 1] === x; return { t: x, ic: x === 'Variants' ? 'layers' : 'database', bg: o ? 'var(--rc-sand)' : 'transparent', fg: o ? 'var(--rc-on-sand)' : 'var(--ui-text-toned)', fw: o ? 500 : 400 } }) } })
|
||||
const crumbs = (s.crumbs || []).map((t, i, a) => ({ t, sep: i > 0, fg: i === a.length - 1 ? 'var(--ui-text-highlighted)' : 'var(--ui-text-muted)', fw: i === a.length - 1 ? 500 : 400 }))
|
||||
const L = s.list || {}
|
||||
const counts = L.counts || [6, 4, 2]
|
||||
const tabs = ['All', 'Online', 'Drafts'].map((t, i) => { const on = (L.tab || 0) === i; return { t, n: counts[i], line: on ? 'var(--ui-primary)' : 'transparent', fg: on ? 'var(--ui-text-highlighted)' : 'var(--ui-text-toned)', fw: on ? 500 : 400 } })
|
||||
const rows = (L.loading ? Array.from({ length: 6 }, () => ({ skel: true })) : (L.rows || [])).map(a => ({ ...a, showOn: !a.busy && a.on, showDraft: !a.busy && a.t && !a.on, op: a.busy ? '0.55' : '1', bg: a.menu ? 'var(--ui-bg-elevated)' : 'transparent', menuBg: a.menu ? 'var(--ui-bg-accented)' : 'transparent', menuPub: a.on ? 'Unpublish' : 'Publish', menuIcon: a.on ? 'globe-lock' : 'globe' }))
|
||||
const AVT = ['var(--rc-sand)', 'var(--ui-bg-accented)', 'var(--ui-bg-elevated)'], ini2 = n => n.replace(/^Dr\.\s*/, '').split(/\s+/).slice(0, 2).map(x => x[0]).join('').toUpperCase()
|
||||
const auInfo = a => { if (a.skel) return {}; const au = a.au || []; return { hasAu: au.length > 0, noAu: au.length === 0, avs: au.slice(0, 3).map((n, i) => ({ i: ini2(n), bg: AVT[(n.length + i) % 3], ml: i ? '-6px' : '0' })), auMore: au.length > 3 ? '+' + (au.length - 3) : '', auNames: au.join(', '), auFirst: au.length ? au[0] + (au.length > 1 ? ' +' + (au.length - 1) : '') : 'No authors', site: a.site || '' } }
|
||||
const rows = (L.loading ? Array.from({ length: 6 }, () => ({ skel: true })) : (L.rows || [])).map(a => ({ ...a, seoSug: a.seo > 0, seoN: a.seo, seoTitle: a.seo + (a.seo === 1 ? ' suggestion' : ' suggestions'), seoHid: a.seo === 'hidden', showOn: !a.busy && a.on, showDraft: !a.busy && a.t && !a.on, op: a.busy ? '0.55' : '1', bg: a.menu ? 'var(--ui-bg-elevated)' : 'transparent', menuBg: a.menu ? 'var(--ui-bg-accented)' : 'transparent', menuPub: a.on ? 'Unpublish' : 'Publish', menuIcon: a.on ? 'globe-lock' : 'globe', ...auInfo(a) }))
|
||||
const e = s.ed || {}
|
||||
const saveMap = { clean: ['check', 'Saved', 'var(--ui-text-muted)'], dirty: ['circle-dot', 'Unsaved changes', 'var(--ui-warning)'], saving: ['loader-circle', 'Saving…', 'var(--ui-text-muted)'], saved: ['check', 'Saved at 11:02', 'var(--ui-text-muted)'], error: ['circle-alert', 'Save failed', 'var(--ui-error)'], offline: ['wifi-off', 'Waiting for connection', 'var(--ui-text-muted)'] }
|
||||
const sv = saveMap[e.save || 'saved']
|
||||
@@ -522,7 +536,7 @@ class Component extends DCLogic {
|
||||
const edReady = k === 'editor' && !e.loading && !e.notfound
|
||||
const edTitle = e.title || 'How we price a bathroom renovation'
|
||||
return {
|
||||
lk, tbOverflow: m ? 'hidden' : 'visible', tbShift: m ? -(LK.shift || 0) + 'px' : '0px', tbFadeL: m && !!LK.shift, tbFadeR: m && !LK.end, act, cl, rt, purgeDlg, rowDir: m ? 'column' : 'row', rowAlign: m ? 'stretch' : 'flex-start', rowJust: m ? 'flex-start' : 'space-between', rowGap: m ? '12px' : '16px', setScroll: -(s.scrollY || 0) + 'px', offText: s.offText || 'You\'re offline. You can keep writing, but saving and publishing will wait until you\'re back online.', cr, s, nav, crumbs, who, ini, pf, dn, dnSave, rsNote, rsBtn,
|
||||
lk, edSeo: this.props.edSeo || null, seoOpen: !!this.props.edSeo, seoClosed: !this.props.edSeo, seoRot: this.props.edSeo ? '0deg' : '-90deg', seoSummary: e.seoSummary || 'Ready', seoFg: /suggest/.test(e.seoSummary || '') ? 'var(--ui-warning)' : 'var(--ui-text-muted)', naOn: !!L.needs, naBg: L.needs ? 'var(--rc-sand)' : 'var(--ui-bg)', naFg: L.needs ? 'var(--rc-on-sand)' : 'var(--ui-text-toned)', naBd: L.needs ? 'var(--rc-sand)' : 'var(--ui-border-accented)', naFw: L.needs ? 500 : 400, naN: L.needsN || 3, edMeta: this.props.edMeta || null, metaOpen: !!this.props.edMeta, metaClosed: !this.props.edMeta, metaRot: this.props.edMeta ? '0deg' : '-90deg', metaSummary: e.metaSummary || 'Inès Duarte', edSheet: m && !!e.sheet, pAu: (() => { const q = s.pa || {}; return { none: q.k !== 'has', has: q.k === 'has', err: !!q.err, slug: q.slug || 'marta-alves', slugNote: !!q.slug, btn: q.loading ? 'Creating…' : 'Create my author profile', icon: q.loading ? 'loader-circle' : 'feather', op: q.loading ? 0.7 : 1 } })(), showSites: !s.role || s.role === 'owner', authorsCol: L.authors !== false, multi: !!L.multi, multiDesk: !m && !!L.multi, multiMob: m && !!L.multi, gridCols: (L.authors !== false ? 'minmax(0,1fr) 104px ' : 'minmax(0,1fr) ') + (L.multi ? '130px ' : '') + '110px 130px 140px 44px', sfText: L.site || 'All sites', sfFg: L.site ? 'var(--ui-text-highlighted)' : 'var(--ui-text-muted)', sfMenu: !!L.siteMenu, sfOpts: ['All sites', 'Renew', 'Journal', 'Projects', 'Archive'].map(x => { const on = (L.site || 'All sites') === x; return { t: x, on, op: on ? 1 : 0, bg: on ? 'var(--ui-bg-elevated)' : 'transparent' } }), tbOverflow: m ? 'hidden' : 'visible', tbShift: m ? -(LK.shift || 0) + 'px' : '0px', tbFadeL: m && !!LK.shift, tbFadeR: m && !LK.end, act, cl, rt, purgeDlg, rowDir: m ? 'column' : 'row', rowAlign: m ? 'stretch' : 'flex-start', rowJust: m ? 'flex-start' : 'space-between', rowGap: m ? '12px' : '16px', setScroll: -(s.scrollY || 0) + 'px', offText: s.offText || 'You\'re offline. You can keep writing, but saving and publishing will wait until you\'re back online.', cr, s, nav, crumbs, who, ini, pf, dn, dnSave, rsNote, rsBtn,
|
||||
langSeg: [['en','English'],['fr','Français']].map(([k,tt])=>{const on=(s.lang||'en')===k;return {act:'lang-'+k,code:k,t:tt,on,op:on?1:0}}), themeSeg: [['system','monitor','System'],['light','sun','Light'],['dark','moon','Dark']].map(([k,icon,tt])=>{const on=(s.mode||'light')===k;return {act:'theme-'+k,icon,t:tt,on,op:on?1:0}}), menuOpen: !!s.userMenu, deskMenu: !m && !!s.userMenu, mobMenu: m && !!s.userMenu, pfItemBg: 'var(--ui-bg-elevated)',
|
||||
chipBg: s.userMenu || s.nav === 'profile' ? 'var(--rc-sand)' : 'transparent', chipFg: s.userMenu || s.nav === 'profile' ? 'var(--rc-on-sand)' : 'var(--ui-text-highlighted)',
|
||||
isSettings: k === 'settings', isProfile: k === 'profile', pfLoading: k === 'profile' && !!pf.loading, pfReady: k === 'profile' && !pf.loading,
|
||||
|
||||
@@ -0,0 +1,438 @@
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<script src="./support.js"></script>
|
||||
</head>
|
||||
<body>
|
||||
<x-dc>
|
||||
<dc-import name="AppFrame" s="{{ shell }}" mobile="{{ mob }}" slot-body="{{ main }}" slot-overlays="{{ ov }}" ed-meta="{{ edMeta }}" ed-seo="{{ edSeo }}" hint-size="100%,100%"></dc-import>
|
||||
</x-dc>
|
||||
<script type="text/x-dc" data-dc-script data-props="{"$preview":{"width":1440,"height":900},"s":{"editor":null,"tsType":"object"},"mobile":{"editor":null,"tsType":"boolean"}}">
|
||||
class Component extends DCLogic {
|
||||
renderVals() {
|
||||
const s = this.props.s || {}, m = !!this.props.mobile
|
||||
const P = t => Object.fromEntries(t.split(';').filter(x => x.trim()).map(x => { const i = x.indexOf(':'); const k = x.slice(0, i).trim(); return [k.startsWith('--') ? k : k.replace(/-([a-z])/g, (_, c) => c.toUpperCase()), x.slice(i + 1).trim()] }))
|
||||
const h = React.createElement
|
||||
const D = (t, ...c) => h('div', { style: P(t) }, ...c)
|
||||
const S = (t, ...c) => h('span', { style: P(t) }, ...c)
|
||||
const I = (n, z = 16, t = '') => h('span', { 'aria-hidden': 'true', style: { display: 'inline-block', flexShrink: 0, width: z, height: z, backgroundColor: 'currentColor', WebkitMask: 'url(https://api.iconify.design/lucide/' + n + '.svg) center / contain no-repeat', mask: 'url(https://api.iconify.design/lucide/' + n + '.svg) center / contain no-repeat', ...(t ? P(t) : {}) } })
|
||||
const bh = m ? 44 : 32, ih = m ? 44 : 40, fs = m ? 16 : 13
|
||||
const B = (label, o = {}) => {
|
||||
const k = o.k || 'outline'
|
||||
const bg = k === 'primary' ? 'var(--ui-primary)' : k === 'danger' ? 'var(--ui-error)' : 'var(--ui-bg)'
|
||||
const fg = k === 'primary' || k === 'danger' ? 'var(--ui-bg)' : k === 'del' ? 'var(--ui-error)' : 'var(--ui-text-highlighted)'
|
||||
const bd = k === 'primary' || k === 'danger' ? bg : 'var(--ui-border-accented)'
|
||||
return S('height:' + (o.h || bh) + 'px;padding:0 ' + (o.px || 12) + 'px;display:flex;align-items:center;justify-content:center;gap:6px;background:' + bg + ';color:' + fg + ';border:1px solid ' + bd + ';font-weight:500;font-size:' + (o.fs || 13) + 'px;white-space:nowrap;opacity:' + (o.dis ? 0.4 : 1) + ';' + (o.full ? 'flex:1;' : '') + (o.ring ? 'outline:2px solid var(--ui-primary);outline-offset:2px;' : ''), o.icon && I(o.icon, o.z || 16), label)
|
||||
}
|
||||
const Alert = (tone, icon, title, text, action) => D('display:flex;gap:10px;padding:12px 14px;background:var(--rc-' + tone + '-soft);color:var(--ui-' + tone + ')', S('display:flex;padding-top:2px', I(icon)), D('flex:1;display:flex;flex-direction:column;gap:8px', D('display:flex;flex-direction:column;gap:2px', S('font-weight:600', title), text && S('color:var(--ui-text-toned)', text)), action && B(action, { icon: 'rotate-cw', z: 14, h: m ? 44 : 28, fs: 12, px: 10 })))
|
||||
const Empty = (icon, title, text, action, primary) => D('background:var(--ui-bg);border:1px solid var(--ui-border);padding:56px 24px;display:flex;flex-direction:column;align-items:center;gap:12px;text-align:center', S('width:44px;height:44px;display:flex;align-items:center;justify-content:center;background:var(--ui-bg-elevated);color:var(--ui-text-toned)', I(icon, 20)), S('font-weight:600;font-size:15px;color:var(--ui-text-highlighted)', title), S('color:var(--ui-text-muted);max-width:340px;text-wrap:pretty', text), action && B(action, { k: primary ? 'primary' : 'outline', icon: primary ? 'plus' : null, px: 16 }))
|
||||
const Note = t => S('align-self:flex-start;min-height:20px;padding:1px 6px;display:inline-flex;align-items:center;border:1px dashed var(--ui-border-accented);color:var(--ui-text-toned);font:500 11px/16px \'IBM Plex Mono\',monospace', t)
|
||||
const BG = { def: ['background:var(--rc-sand);color:var(--rc-on-sand)', 'star'], linked: ['background:var(--rc-info-soft);color:var(--ui-info)', 'link'], guest: ['border:1px solid var(--ui-border-accented);color:var(--ui-text-toned)', 'user'], noidx: ['background:var(--rc-warning-soft);color:var(--ui-warning)', 'eye-off'], prim: ['border:1px solid var(--ui-border-accented);color:var(--ui-text-toned)'] }
|
||||
const Bd = (t, k, sz = 20) => S('height:' + sz + 'px;padding:0 6px;display:inline-flex;align-items:center;gap:4px;font-size:12px;font-weight:500;white-space:nowrap;flex-shrink:0;' + BG[k][0], BG[k][1] && I(BG[k][1], 12), t)
|
||||
const mono = 'font-family:\'IBM Plex Mono\',monospace;'
|
||||
// ---------- data
|
||||
const SITES = [
|
||||
{ n: 'Renew', key: 'renew', url: 'https://renew.example', c: 268, def: true, robots: 'Index', loc: 'en', img: 'north-wall.jpg' },
|
||||
{ n: 'Journal', key: 'journal', url: 'https://journal.renew.example', c: 38, robots: 'Index', loc: '', img: null },
|
||||
{ n: 'Projects', key: 'projects', url: 'https://projects.renew.example', c: 6, robots: 'Noindex', loc: 'fr', img: 'kitchen-after.webp' },
|
||||
{ n: 'Archive', key: 'archive', url: 'https://archive.renew.example', c: 0, robots: 'Noindex', loc: '', img: null }
|
||||
]
|
||||
const AUTH = [
|
||||
{ name: 'Inès Duarte', slug: 'ines-duarte', user: 'ines.duarte@renew.example', c: 9, img: true, web: 'https://ines-duarte.example', bio: 'Site manager and restoration carpenter. Writes about timber and joinery.' },
|
||||
{ name: 'Jonas Pereira', slug: 'jonas-pereira', user: 'jonas@renew.example', c: 6, img: true, bio: 'Heat pumps, insulation and the numbers behind them.' },
|
||||
{ name: 'Camille Roche', slug: 'camille-roche', c: 3, bio: 'Freelance writer on lime and stone.' },
|
||||
{ name: 'Paul Huber', slug: 'paul-huber', c: 2, img: true, bio: '' },
|
||||
{ name: 'Léa Fontaine', slug: 'lea-fontaine', c: 0, bio: '' },
|
||||
{ name: 'Dr. Alexandra Konstantinopoulou-Whitfield', slug: 'dr-alexandra-konstantinopoulou-whitfield', c: 1, bio: 'Conservation architect.' }
|
||||
]
|
||||
const AV = n => AUTH.find(a => a.name === n) || { name: n, slug: n.toLowerCase().replace(/[^a-z0-9]+/g, '-'), c: 0 }
|
||||
const TONE = ['var(--rc-sand)', 'var(--ui-bg-accented)', 'var(--ui-bg-elevated)']
|
||||
const ini = n => n.replace(/^Dr\.\s*/, '').split(/\s+/).slice(0, 2).map(x => x[0]).join('').toUpperCase()
|
||||
const Av = (a, z = 32, ring) => S('width:' + z + 'px;height:' + z + 'px;flex-shrink:0;display:flex;align-items:center;justify-content:center;background:' + (a.img ? 'repeating-linear-gradient(135deg, var(--ui-border) 0 1px, transparent 1px 8px), ' : '') + TONE[a.name.length % 3] + ';color:var(--ui-text-highlighted);border:' + (ring ? '2px solid var(--ui-bg)' : '1px solid var(--ui-border)') + ';font:600 ' + Math.round(z * 0.36) + 'px/1 \'IBM Plex Sans\',sans-serif', ini(a.name))
|
||||
const pl = (n, w) => n === 0 ? 'No ' + w + 's' : n + ' ' + w + (n === 1 ? '' : 's')
|
||||
const host = u => u.replace('https://', '')
|
||||
// ---------- fields
|
||||
const F = (lab, val, o = {}) => D('display:flex;flex-direction:column;gap:6px;min-width:0', (lab || o.count) && D('display:flex;justify-content:space-between;gap:8px', S('font-weight:500;color:var(--ui-text-highlighted)', lab, o.opt && S('font-weight:400;color:var(--ui-text-muted)', ' (optional)')), o.count && S('font:400 12px \'IBM Plex Mono\',monospace;color:' + (o.countErr ? 'var(--ui-error)' : 'var(--ui-text-muted)'), o.count)),
|
||||
D('display:flex;align-items:' + (o.area ? 'flex-start' : 'center') + ';min-height:' + (o.area ? (m ? 120 : 96) : ih) + 'px;border:1px solid ' + (o.err ? 'var(--ui-error)' : o.focus ? 'var(--ui-primary)' : 'var(--ui-border-accented)') + ';' + (o.err ? 'box-shadow:inset 0 0 0 1px var(--ui-error);' : o.focus ? 'box-shadow:inset 0 0 0 1px var(--ui-primary);' : '') + 'background:' + (o.dis ? 'var(--ui-bg-elevated)' : 'var(--ui-bg)') + ';font-size:' + fs + 'px', o.pre, S('flex:1;min-width:0;padding:' + (o.area ? '8px 10px' : '0 10px') + ';color:' + (o.val === false ? 'var(--ui-text-muted)' : 'var(--ui-text-highlighted)') + ';' + (o.area ? '' : 'overflow:hidden;text-overflow:ellipsis;white-space:nowrap;') + (o.mono ? mono + 'font-size:' + (m ? 14 : 12) + 'px;' : ''), val), o.sel && I('chevron-down', 14, 'margin-right:10px;color:var(--ui-text-muted)'), o.suffix),
|
||||
o.err && S('display:flex;gap:6px;align-items:flex-start;color:var(--ui-error);font-size:12px;line-height:18px', I('circle-alert', 14, 'margin-top:2px'), o.err), o.help && S('color:var(--ui-text-muted);font-size:12px;line-height:18px;text-wrap:pretty', o.help))
|
||||
const Link = (t, icon) => S('display:inline-flex;align-items:center;gap:4px;min-height:' + (m ? 44 : 20) + 'px;color:var(--ui-text-highlighted);text-decoration:underline;text-underline-offset:3px;font-size:12px;font-weight:500', icon && I(icon, 12), t)
|
||||
const Slug = (lab, o) => {
|
||||
const mode = o.mode || 'empty'
|
||||
if (mode === 'saved') return F(lab, o.value, { mono: true, dis: !!o.locked, help: o.locked ? o.lockHelp : o.help2, suffix: o.locked && I('lock', 14, 'margin-right:10px;color:var(--ui-text-muted)') })
|
||||
if (mode === 'empty') return F(lab, o.emptyText || 'Generated from the name', { val: false, dis: true, mono: true, help: o.help })
|
||||
if (mode === 'auto') return F(lab, o.value, { mono: true, dis: true, help: o.help, suffix: S('display:flex;align-items:center;gap:6px;padding:0 4px', S('height:20px;padding:0 6px;display:inline-flex;align-items:center;border:1px dashed var(--ui-border-accented);font:500 11px \'IBM Plex Mono\',monospace;color:var(--ui-text-toned)', 'Auto'), S('width:' + (m ? 44 : 28) + 'px;height:' + (m ? 44 : 28) + 'px;display:flex;align-items:center;justify-content:center;color:var(--ui-text-highlighted)', I('pencil', 14))) })
|
||||
return D('display:flex;flex-direction:column;gap:6px', F(lab, o.value, { mono: true, focus: !o.err, err: o.err, help: o.err ? null : o.help2 || o.help }), o.suggest && D('display:flex;align-items:center;gap:8px;flex-wrap:wrap', B('Use ' + o.suggest, { h: m ? 44 : 28, fs: 12, px: 10, icon: 'wand-sparkles', z: 12 })), mode === 'manual' && Link(o.reset || 'Reset to match the name', 'rotate-ccw'))
|
||||
}
|
||||
const Seg = (opts, on) => D('display:flex;border:1px solid var(--ui-border-accented);width:100%', ...opts.map(([k, t]) => S('flex:1;height:' + (m ? 44 : 32) + 'px;display:flex;align-items:center;justify-content:center;font-weight:' + (on === k ? 500 : 400) + ';background:' + (on === k ? 'var(--rc-sand)' : 'var(--ui-bg)') + ';color:' + (on === k ? 'var(--rc-on-sand)' : 'var(--ui-text-toned)') + ';font-size:' + (m ? 14 : 13) + 'px', t)))
|
||||
const Sw = (on, lab, help, dis) => D('display:flex;gap:12px;align-items:flex-start;opacity:' + (dis ? 0.6 : 1), S('width:32px;height:18px;margin-top:2px;padding:2px;display:flex;flex-shrink:0;justify-content:' + (on ? 'flex-end' : 'flex-start') + ';background:' + (on ? 'var(--ui-primary)' : 'var(--ui-bg-accented)'), S('width:14px;height:14px;background:var(--ui-bg)')), D('display:flex;flex-direction:column;gap:2px', S('font-weight:500;color:var(--ui-text-highlighted)', lab), help && S('color:var(--ui-text-muted);font-size:12px;line-height:18px;text-wrap:pretty', help)))
|
||||
const Opts = (items, on, hdr) => D('border:1px solid var(--ui-border);background:var(--ui-bg);box-shadow:var(--rc-shadow-pop);padding:4px', hdr, ...items.map(([t, sub, k, av]) => D('min-height:' + (m ? 48 : 36) + 'px;padding:4px 8px;display:flex;align-items:center;gap:8px;background:' + (on === t ? 'var(--ui-bg-elevated)' : 'transparent') + ';color:var(--ui-text-highlighted)', av, D('flex:1;min-width:0;display:flex;flex-direction:column', S('overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-weight:500', t), sub && S('font-size:12px;color:var(--ui-text-muted);overflow:hidden;text-overflow:ellipsis;white-space:nowrap', sub)), on === t && I('check', 14))))
|
||||
const Pick = (img, lab, help, o = {}) => D('display:flex;flex-direction:column;gap:6px', S('font-weight:500;color:var(--ui-text-highlighted)', lab, S('font-weight:400;color:var(--ui-text-muted)', ' (optional)')),
|
||||
D('display:flex;align-items:center;gap:12px', o.av ? Av(o.av, 64) : S('width:' + (img ? 96 : 96) + 'px;aspect-ratio:1.91/1;flex-shrink:0;display:flex;align-items:center;justify-content:center;border:1px ' + (img ? 'solid' : 'dashed') + ' var(--ui-border-accented);background:' + (img ? 'repeating-linear-gradient(135deg, var(--ui-border) 0 1px, transparent 1px 10px), var(--rc-sand)' : 'var(--ui-bg)') + ';color:var(--ui-text-muted)', I('image', 18)),
|
||||
D('flex:1;min-width:0;display:flex;flex-direction:column;gap:6px', img && S('font-size:12px;color:var(--ui-text-highlighted);overflow:hidden;text-overflow:ellipsis;white-space:nowrap;' + mono, img), D('display:flex;gap:8px;flex-wrap:wrap', B(img ? 'Change image' : 'Choose image', { icon: 'images', h: m ? 44 : 28, fs: 12, px: 10 }), img && B('Remove', { h: m ? 44 : 28, fs: 12, px: 10 })))),
|
||||
help && S('color:var(--ui-text-muted);font-size:12px;line-height:18px', help))
|
||||
// ---------- overlays
|
||||
const Shell = (o, body) => D('position:absolute;inset:0;z-index:' + (o.z || 50) + ';background:var(--rc-overlay);display:flex;align-items:' + (m ? 'flex-end' : 'flex-start') + ';justify-content:center;padding:' + (m ? '0' : (o.top || 140) + 'px 16px 16px'),
|
||||
D('width:' + (m ? '100%' : (o.w || 460) + 'px') + ';max-height:100%;background:var(--ui-bg);box-shadow:var(--rc-shadow-modal);display:flex;flex-direction:column', m && D('display:flex;justify-content:center;padding-top:8px;flex-shrink:0', S('display:block;width:36px;height:4px;background:var(--ui-border-accented)')),
|
||||
D('padding:20px 24px 0;display:flex;align-items:flex-start;gap:12px', D('flex:1;display:flex;flex-direction:column;gap:4px', S('font:600 16px/24px \'IBM Plex Sans\',sans-serif;color:var(--ui-text-highlighted)', o.title), o.desc && S('color:var(--ui-text-muted);text-wrap:pretty', o.desc)), o.close && S('width:' + (m ? 44 : 28) + 'px;height:' + (m ? 44 : 28) + 'px;display:flex;align-items:center;justify-content:center;color:var(--ui-text-muted)', I('x'))),
|
||||
D('padding:20px 24px 0;display:flex;flex-direction:column;gap:16px;min-height:0;overflow:hidden', body),
|
||||
D('padding:20px 24px;display:flex;flex-direction:' + (m ? 'column-reverse' : 'row') + ';justify-content:flex-end;gap:8px;flex-shrink:0', o.cancel && B(o.cancel, { dis: o.loading }), o.confirm && S('height:' + bh + 'px;padding:0 12px;display:flex;align-items:center;justify-content:center;gap:6px;background:' + (o.tone === 'danger' ? 'var(--ui-error)' : 'var(--ui-primary)') + ';color:var(--ui-bg);font-weight:500;white-space:nowrap;opacity:' + (o.cdis ? 0.4 : 1), o.loading && I('loader-circle'), o.confirm))))
|
||||
const Panel = (o, body, ...pv) => D('position:absolute;inset:0;z-index:' + (o.z || 40) + ';display:flex;justify-content:' + (m ? 'center' : 'flex-end') + ';align-items:' + (m ? 'flex-end' : 'stretch') + ';background:var(--rc-overlay)',
|
||||
D('width:' + (m ? '100%' : (o.w || 480) + 'px') + ';height:' + (m ? '92%' : '100%') + ';background:var(--ui-bg);box-shadow:var(--rc-shadow-modal);display:flex;flex-direction:column', m && D('display:flex;justify-content:center;padding-top:8px;flex-shrink:0', S('display:block;width:36px;height:4px;background:var(--ui-border-accented)')),
|
||||
D('flex-shrink:0;display:flex;align-items:center;gap:12px;padding:' + (m ? '4px 6px 4px 16px' : '0 12px 0 20px') + ';height:56px;border-bottom:1px solid var(--ui-border)', S('flex:1;min-width:0;font:600 16px/24px \'IBM Plex Sans\',sans-serif;color:var(--ui-text-highlighted);overflow:hidden;text-overflow:ellipsis;white-space:nowrap', o.title), S('width:' + (m ? 44 : 28) + 'px;height:' + (m ? 44 : 28) + 'px;display:flex;align-items:center;justify-content:center;color:var(--ui-text-muted)', I('x'))),
|
||||
D('flex:1;min-height:0;overflow:hidden;padding:' + (m ? 16 : 20) + 'px;display:flex;flex-direction:column;gap:18px', o.notice && Alert('error', 'circle-x', o.notice), body, ...pv),
|
||||
D('flex-shrink:0;padding:' + (m ? '12px 16px' : '12px 20px') + ';border-top:1px solid var(--ui-border);display:flex;flex-direction:' + (m ? 'column-reverse' : 'row') + ';justify-content:' + (o.ro ? 'flex-end' : 'space-between') + ';gap:8px', B(o.ro ? 'Close' : 'Cancel', { dis: o.saving }), !o.ro && S('height:' + bh + 'px;padding:0 16px;display:flex;align-items:center;justify-content:center;gap:6px;background:var(--ui-primary);color:var(--ui-bg);font-weight:500;white-space:nowrap;opacity:' + (o.cdis ? 0.4 : 1), o.saving && I('loader-circle'), o.confirm))))
|
||||
const Toasts = () => D('position:absolute;z-index:60;display:flex;flex-direction:column;gap:8px;' + (m ? 'left:16px;right:16px;bottom:16px' : 'right:24px;bottom:24px;width:356px'), ...s.toasts.map(t => D('display:flex;gap:10px;padding:12px 14px;background:var(--ui-bg);border:1px solid var(--ui-border);box-shadow:var(--rc-shadow-pop)', S('margin-top:2px;display:flex;color:var(--ui-' + t[0] + ')', I(t[1])), D('flex:1;display:flex;flex-direction:column;gap:6px', D('display:flex;flex-direction:column;gap:2px', S('font-weight:600;color:var(--ui-text-highlighted)', t[2]), S('color:var(--ui-text-muted)', t[3])), t[4] && B(t[4], { icon: 'rotate-cw', z: 14, h: m ? 44 : 28, fs: 12, px: 10 })), I('x'))))
|
||||
// media picker (shared by site image and author avatar)
|
||||
const IMGS = ['north-wall.jpg', 'kitchen-after.webp', 'kitchen-before.webp', 'logo-renew.svg', 'window-frame.jpg', 'lime-plaster.jpg', 'floorboards.jpg', 'bathroom-tiles.png']
|
||||
const Picker = pk => {
|
||||
const cols = m ? 3 : 4
|
||||
return Shell({ title: pk.title, desc: pk.desc, close: true, w: 640, top: 40, z: pk.z || 55, cancel: 'Cancel', confirm: 'Use image', cdis: pk.sel == null }, D('display:flex;flex-direction:column;gap:12px',
|
||||
D('display:flex;gap:20px;border-bottom:1px solid var(--ui-border)', ...['Upload', 'Library'].map(t => S('height:' + (m ? 44 : 36) + 'px;display:flex;align-items:center;gap:6px;border-bottom:2px solid ' + (t === 'Library' ? 'var(--ui-primary)' : 'transparent') + ';margin-bottom:-1px;font-weight:' + (t === 'Library' ? 500 : 400) + ';color:' + (t === 'Library' ? 'var(--ui-text-highlighted)' : 'var(--ui-text-toned)'), I(t === 'Upload' ? 'upload' : 'images', 14), t))),
|
||||
D('height:' + ih + 'px;padding:0 10px;display:flex;align-items:center;gap:8px;border:1px solid var(--ui-border-accented);color:var(--ui-text-muted);font-size:' + fs + 'px', I('search', 14), 'Search by filename'),
|
||||
D('display:grid;grid-template-columns:repeat(' + cols + ',minmax(0,1fr));gap:10px', ...IMGS.slice(0, m ? 6 : 8).map((n, i) => D('display:flex;flex-direction:column;gap:4px', S('position:relative;display:flex;align-items:center;justify-content:center;aspect-ratio:' + (pk.sq ? '1/1' : '4/3') + ';background:repeating-linear-gradient(135deg, var(--ui-border) 0 1px, transparent 1px 12px), ' + TONE[i % 3] + ';color:var(--ui-text-muted);border:1px solid ' + (pk.sel === i ? 'var(--ui-primary)' : 'var(--ui-border)') + ';' + (pk.sel === i ? 'box-shadow:inset 0 0 0 1px var(--ui-primary);' : ''), I('image', 18), pk.sel === i && S('position:absolute;top:4px;right:4px;width:20px;height:20px;display:flex;align-items:center;justify-content:center;background:var(--ui-primary);color:var(--ui-bg)', I('check', 14))), S('font-size:12px;color:var(--ui-text-toned);overflow:hidden;text-overflow:ellipsis;white-space:nowrap', n)))),
|
||||
pk.sq && S('color:var(--ui-text-muted);font-size:12px', 'Shown as a square. Choose an image with the face or logo near the middle.')))
|
||||
}
|
||||
// ---------- list parts
|
||||
const menuItem = (icon, t, o = {}) => D('min-height:' + (m ? 48 : 32) + 'px;padding:' + (m ? '0 16px' : '0 8px') + ';display:flex;align-items:center;gap:' + (m ? 12 : 8) + 'px;color:' + (o.err ? 'var(--ui-error)' : 'var(--ui-text-highlighted)') + ';opacity:' + (o.dis ? 0.4 : 1) + ';background:' + (o.hv ? 'var(--ui-bg-elevated)' : 'transparent') + ';font-size:' + (m ? 15 : 13) + 'px', I(icon, m ? 18 : 16), t)
|
||||
const sep = D('height:1px;background:var(--ui-border);margin:4px 0')
|
||||
const MenuBox = (items, title, desc) => m ?
|
||||
D('position:absolute;inset:0;z-index:45;background:var(--rc-overlay);display:flex;align-items:flex-end', D('width:100%;background:var(--ui-bg);box-shadow:var(--rc-shadow-modal);padding:8px 0 24px', D('display:flex;justify-content:center;padding-bottom:8px', S('display:block;width:36px;height:4px;background:var(--ui-border-accented)')), D('display:flex;align-items:center;padding:0 6px 0 16px;min-height:44px', S('flex:1;font-weight:600;font-size:15px;color:var(--ui-text-highlighted)', title), S('width:44px;height:44px;display:flex;align-items:center;justify-content:center;color:var(--ui-text-muted)', I('x'))), ...items, desc && S('display:block;padding:4px 16px 0 46px;color:var(--ui-text-muted);font-size:12px;line-height:18px', desc))) :
|
||||
D('position:absolute;right:12px;top:44px;z-index:5;width:220px;background:var(--ui-bg);border:1px solid var(--ui-border);box-shadow:var(--rc-shadow-pop);padding:4px', ...items)
|
||||
const Dots = () => S('width:' + (m ? 44 : 32) + 'px;height:' + (m ? 44 : 32) + 'px;display:flex;align-items:center;justify-content:center;color:var(--ui-text-muted)', s.ro ? I('chevron-right', 14) : I(m ? 'ellipsis-vertical' : 'ellipsis', m ? 18 : 16))
|
||||
const ph = 'Search by name or slug', q = s.q
|
||||
const SearchBox = (ph2 = ph) => D('height:' + bh + 'px;' + (m ? '' : 'width:280px;') + 'padding:0 4px 0 10px;display:flex;align-items:center;gap:8px;border:1px solid var(--ui-border-accented);background:var(--ui-bg);color:' + (q ? 'var(--ui-text-highlighted)' : 'var(--ui-text-muted)') + (m ? ';font-size:16px' : ''), I('search', 14), S('flex:1', q || ph2), q && S('width:' + (m ? 36 : 24) + 'px;height:24px;display:flex;align-items:center;justify-content:center;color:var(--ui-text-muted)', I('x', 14)))
|
||||
const Head = (title, desc, btn) => D('display:flex;align-items:flex-end;gap:16px;flex-wrap:wrap', D('flex:1;min-width:200px;display:flex;flex-direction:column;gap:2px', S('font:600 20px/28px \'IBM Plex Sans\',sans-serif;color:var(--ui-text-highlighted)', title), S('color:var(--ui-text-muted)', desc)), !m && btn && B(btn, { k: 'primary', icon: 'plus' }))
|
||||
const TH = (cols, labels) => D('display:grid;grid-template-columns:' + cols + ';gap:12px;height:36px;align-items:center;padding:0 12px;background:var(--ui-bg-elevated);color:var(--ui-text-muted);font-weight:500', ...labels.map(l => S('', l)))
|
||||
const Skel = n => D('background:var(--ui-bg);border:1px solid var(--ui-border);' + (m ? 'margin:0 -16px;border-left:0;border-right:0' : ''), ...Array.from({ length: n }, () => D('display:flex;align-items:center;gap:12px;height:' + (m ? 72 : 52) + 'px;padding:0 16px;border-bottom:1px solid var(--ui-border-muted)', S('display:block;width:' + (m ? 32 : 28) + 'px;height:' + (m ? 32 : 28) + 'px;background:var(--ui-bg-accented)'), D('flex:1;display:flex;flex-direction:column;gap:8px', S('display:block;width:40%;height:13px;background:var(--ui-bg-accented)'), S('display:block;width:60%;height:11px;background:var(--ui-bg-accented)')))))
|
||||
|
||||
// ---------- pagination (same Paginator as Articles and Media)
|
||||
const fmtN = n => String(n).replace(/\B(?=(\d{3})+(?!\d))/g, ',')
|
||||
const slugify = t => t.normalize('NFD').replace(/[\u0300-\u036f]/g, '').toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '')
|
||||
const SN = ['Atelier', 'Birchwood', 'Cedar Row', 'Dovetail', 'Eastgate', 'Fieldnotes', 'Granary', 'Harbour', 'Ironwork', 'Joinery Guide', 'Kiln', 'Larch', 'Millstone', 'Nettle', 'Orchard', 'Planing', 'Quarry', 'Ridgeway', 'Slate', 'Tannery', 'Underhill', 'Veneer', 'Workshop', 'Yardline', 'Zinc Works']
|
||||
const RN = ['Journal', 'Projects', 'Archive', 'Press', 'Careers', 'Docs', 'Events', 'Shop']
|
||||
const genSites = g => { const st = (g.page - 1) * g.per, n = Math.min(12, g.per, g.total - st); return Array.from({ length: n }, (_, i) => { const gi = st + i; let name
|
||||
if (g.q) name = 'Renew ' + RN[gi % RN.length] + (gi >= RN.length ? ' ' + (Math.floor(gi / RN.length) + 1) : '')
|
||||
else if (gi < SITES.length) return SITES[gi]
|
||||
else { const k = gi - SITES.length; name = SN[k % SN.length] + (k >= SN.length ? ' ' + (Math.floor(k / SN.length) + 1) : '') }
|
||||
const key = slugify(name); return { n: name, key, url: 'https://' + (g.q ? key.replace(/^renew-/, '') : key) + '.renew.example', c: (gi * 37) % 90, robots: 'Index' } }) }
|
||||
const FN = ['Anaïs', 'Bruno', 'Clara', 'Diego', 'Elise', 'Félix', 'Greta', 'Hugo', 'Iris', 'Julien', 'Karim', 'Lucie', 'Mathieu', 'Nora', 'Oscar', 'Pilar', 'Quentin', 'Rosa', 'Samir', 'Tess']
|
||||
const QF = ['Marc', 'Marie', 'Marta', 'Mario', 'Marina', 'Marius', 'Marlène', 'Marcel']
|
||||
const LN = ['Marchand', 'Nunes', 'Oliveira', 'Perrin', 'Quintela', 'Rocha', 'Santos', 'Teixeira', 'Vidal', 'Weber']
|
||||
const genAuthors = g => { const st = (g.page - 1) * g.per, n = Math.min(12, g.per, g.total - st); return Array.from({ length: n }, (_, i) => { const gi = st + i
|
||||
if (!g.q && gi < AUTH.length) return AUTH[gi]
|
||||
const name = (g.q ? QF[gi % QF.length] : FN[gi % FN.length]) + ' ' + LN[(gi * 3 + 1) % LN.length], sl = slugify(name)
|
||||
return { name, slug: sl, user: gi % 3 === 0 ? sl.split('-')[0] + '@renew.example' : undefined, c: (gi * 5) % 12, img: gi % 2 === 0 } }) }
|
||||
const PagerBlock = (g, noun) => {
|
||||
const pages = Math.max(1, Math.ceil(g.total / g.per)), busy = !!g.loading, dim = busy ? 0.4 : 1
|
||||
const out = []
|
||||
if (g.err) out.push(Alert('error', 'circle-x', g.err, 'Check your connection and try again.', 'Retry'))
|
||||
if (pages === 1) return D('flex-shrink:0;display:flex;flex-direction:column;gap:12px', ...out, S('display:block;color:var(--ui-text-muted)', pl(g.total, noun)))
|
||||
const from = (g.page - 1) * g.per + 1, to = Math.min(g.page * g.per, g.total)
|
||||
const back = g.page === 1 ? 0.4 : 1, fwd = g.page === pages ? 0.4 : 1
|
||||
const PB = (ic, op) => S('width:' + bh + 'px;height:' + bh + 'px;display:flex;align-items:center;justify-content:center;border:1px solid var(--ui-border-accented);background:var(--ui-bg);color:var(--ui-text-highlighted);opacity:' + op, I(ic))
|
||||
const set = new Set([1, pages, g.page - 1, g.page, g.page + 1].filter(n => n >= 1 && n <= pages))
|
||||
const arr = pages <= 7 ? Array.from({ length: pages }, (_, i) => i + 1) : [...set].sort((a, b) => a - b)
|
||||
const nums = []
|
||||
arr.forEach((n, i) => {
|
||||
if (i && n - arr[i - 1] > 1) nums.push(S('min-width:' + bh + 'px;height:' + bh + 'px;display:flex;align-items:center;justify-content:center;color:var(--ui-text-muted)', '…'))
|
||||
const cur = n === g.page
|
||||
nums.push(S('min-width:' + bh + 'px;height:' + bh + 'px;padding:0 6px;display:flex;align-items:center;justify-content:center;border:1px solid ' + (cur ? 'var(--ui-primary)' : 'var(--ui-border-accented)') + ';background:' + (cur ? 'var(--rc-sand)' : 'var(--ui-bg)') + ';color:' + (cur ? 'var(--rc-on-sand)' : 'var(--ui-text-highlighted)') + ';font-weight:' + (cur ? 600 : 400), String(n)))
|
||||
})
|
||||
const Size = () => D('position:relative;opacity:' + dim, S('height:' + bh + 'px;padding:0 8px 0 12px;display:flex;align-items:center;gap:8px;border:1px solid var(--ui-border-accented);background:var(--ui-bg);color:var(--ui-text-highlighted)', g.per + ' per page', I('chevron-down', 14)),
|
||||
g.sizeOpen && D('position:absolute;' + (m ? 'right' : 'left') + ':0;bottom:calc(100% + 4px);z-index:40;width:160px;background:var(--ui-bg);border:1px solid var(--ui-border);box-shadow:var(--rc-shadow-pop);padding:4px', ...[5, 25, 50, 100].map(n => D('height:' + bh + 'px;padding:0 8px;display:flex;align-items:center;background:' + (n === g.per ? 'var(--rc-sand)' : 'transparent') + ';color:' + (n === g.per ? 'var(--rc-on-sand)' : 'var(--ui-text-highlighted)') + ';font-weight:' + (n === g.per ? 600 : 400), n + ' per page'))))
|
||||
const sum = S('color:var(--ui-text-muted)', busy ? 'Loading page ' + g.loading + '…' : 'Showing ' + from + '–' + to + ' of ' + fmtN(g.total))
|
||||
const NB = (t, left) => S('flex:1;height:44px;display:flex;align-items:center;justify-content:center;gap:6px;border:1px solid var(--ui-border-accented);background:var(--ui-bg);color:var(--ui-text-highlighted);font-weight:500;opacity:' + (left ? back : fwd), left && I('chevron-left'), t, !left && I('chevron-right'))
|
||||
if (m) out.push(D('display:flex;flex-direction:column;gap:12px', D('display:flex;align-items:center;gap:12px;flex-wrap:wrap;justify-content:space-between', sum, Size()), D('display:flex;align-items:center;gap:8px;opacity:' + dim, NB('Previous', true), S('padding:0 4px;color:var(--ui-text-highlighted);font-weight:500;white-space:nowrap', 'Page ' + g.page + ' of ' + fmtN(pages)), NB('Next', false))))
|
||||
else out.push(D('display:flex;align-items:center;gap:16px', D('flex:1;display:flex', sum), Size(), D('display:flex;align-items:center;gap:4px;justify-content:flex-end;opacity:' + dim, PB('chevrons-left', back), PB('chevron-left', back), ...nums, PB('chevron-right', fwd), PB('chevrons-right', fwd))))
|
||||
return D('flex-shrink:0;display:flex;flex-direction:column;gap:12px', ...out)
|
||||
}
|
||||
const fab = label => m && !s.ro && !s.panel && !s.modal && !s.menu && s.list !== 'empty' && D('position:absolute;left:16px;right:16px;bottom:16px;height:48px;display:flex;align-items:center;justify-content:center;gap:8px;background:var(--ui-primary);color:var(--ui-bg);font-weight:500;font-size:15px;box-shadow:var(--rc-shadow-pop)', I('plus', 18), label)
|
||||
const shellBase = { kind: 'slot', display: 'Marta Alves' }
|
||||
let main = null, shell = s.shell, edMeta = null, edSeo = null
|
||||
const ov = []
|
||||
// ---------- Sites
|
||||
const siteForm = () => {
|
||||
const p = s.panel, f = { name: '', key: '', keyMode: 'empty', url: '', img: null, sname: p.mode === 'add' ? '' : (p.f || {}).name, tpl: '%title% | %site%', ddesc: '', robots: 'Index', loc: '', def: false, ...p.f }, er = p.err || {}, add = p.mode === 'add'
|
||||
const isDef = !add && SITES[p.i || 0].def
|
||||
const prev = (f.url && !er.url ? f.url : 'https://journal.example.com') + '/how-we-price-a-bathroom-renovation'
|
||||
return Panel({ title: add ? 'Add site' : 'Edit ' + f.name, notice: p.notice, saving: p.saving, confirm: p.saving ? 'Saving…' : add ? 'Add site' : 'Save changes' },
|
||||
D('display:flex;flex-direction:column;gap:18px', F('Name', f.name || 'e.g. Journal', { val: !!f.name, focus: p.focus === 'name', err: er.name }),
|
||||
Slug('Key', { mode: f.keyMode, value: f.key, err: er.key, suggest: er.keySuggest, locked: !add, lockHelp: 'Used in API paths, so it can\'t change.', help: 'Lowercase letters, numbers and hyphens. Used in API paths. It can\'t be changed after the site is added.', help2: 'Lowercase letters, numbers and hyphens. Used in API paths. It can\'t be changed after the site is added.' }),
|
||||
F('Base URL', f.url || 'https://blog.example.com', { val: !!f.url, mono: true, focus: p.focus === 'url', err: er.url, help: er.url ? null : 'The public address of the frontend. Use https and no path.' }),
|
||||
Pick(f.img, 'Default social image', 'Used when an article has no image of its own.'),
|
||||
F('Site name', f.sname || 'e.g. Renew', { val: !!f.sname, focus: p.focus === 'sname', help: 'Shown in titles through the template, and sent as the Open Graph site name.' }),
|
||||
D('display:flex;flex-direction:column;gap:6px', F('Title template', f.tpl, { mono: true, focus: p.focus === 'tpl', err: er.tpl, help: er.tpl ? null : 'Use %title% for the article title and %site% for the site name.' }), !er.tpl && D('display:flex;gap:6px;align-items:center;padding:8px 10px;background:var(--ui-bg-elevated);min-width:0', S('flex-shrink:0;font-size:12px;color:var(--ui-text-muted)', 'Example'), S('flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;color:var(--ui-text-highlighted)', f.tpl.replace('%title%', 'How we price a bathroom renovation').replace('%site%', f.sname || 'Renew')))),
|
||||
F('Default description', f.ddesc || 'One or two sentences about the site.', { opt: true, area: true, val: !!f.ddesc, count: [...f.ddesc].length + ' / 320', help: 'Used when an article has no description, excerpt or body text.' }),
|
||||
D('display:flex;flex-direction:column;gap:6px', S('font-weight:500;color:var(--ui-text-highlighted)', 'Default robots policy'), Seg([['Index', 'Index'], ['Noindex', 'Noindex']], f.robots), S('color:var(--ui-text-muted);font-size:12px;line-height:18px', f.robots === 'Index' ? 'Search engines may list this site\'s pages.' : 'Asks search engines not to list this site\'s pages.')),
|
||||
F('Locale', f.loc || 'e.g. en or fr-CH', { opt: true, val: !!f.loc, mono: true, err: er.loc, help: er.loc ? null : 'A language tag. Leave empty if the site has no single language.' }),
|
||||
Sw(isDef || f.def, isDef ? 'Default site' : 'Make this the default site', isDef ? 'New articles start on the default site. To change it, make another site the default.' : 'New articles start here. The current default is Renew.', isDef)),
|
||||
D('display:flex;flex-direction:column;gap:4px;padding:12px;background:var(--ui-bg-elevated)', S('font-size:12px;color:var(--ui-text-muted)', 'Canonical URL preview'), S('font:400 12px/18px \'IBM Plex Mono\',monospace;color:var(--ui-text-highlighted);word-break:break-all', prev), er.url && S('font-size:12px;color:var(--ui-text-muted)', 'Shown when the base URL is valid.')),
|
||||
D('display:flex;flex-direction:column;gap:6px;padding:12px;background:var(--ui-bg-elevated)', S('font-size:12px;color:var(--ui-text-muted)', 'How articles use these defaults'), ...[['Title', 'Article title, then the template.'], ['Description', 'Used last, after the article\'s description, excerpt and body.'], ['Image', 'Used when an article has no cover image.'], ['Robots', 'Used unless an article is hidden from search engines.']].map(([a, b]) => D('display:flex;gap:8px', S('width:84px;flex-shrink:0;font-weight:500;color:var(--ui-text-highlighted)', a), S('color:var(--ui-text-toned);text-wrap:pretty', b)))))
|
||||
}
|
||||
const sitesPage = () => {
|
||||
if (s.forbidden) return D('flex:1;min-height:0;overflow:hidden;padding:' + (m ? '16px' : '24px') + ';display:flex;flex-direction:column;gap:16px', Empty('lock', 'You don\'t have access to Sites', 'Only the owner can manage sites. Ask the owner of this site if you need a change.', 'Back to Settings'))
|
||||
const pg = s.pg && { ...s.pg, q }, st = s.sites || {}, rows = pg ? (pg.empty ? [] : genSites(pg)) : st.only ? [{ ...SITES[0], c: 312 }] : st.gone ? SITES.filter((_, i) => i !== 1) : SITES
|
||||
const grid = 'minmax(0,1.1fr) minmax(0,1.5fr) 110px 44px'
|
||||
let body
|
||||
if (st.state === 'loading') body = Skel(3)
|
||||
else if (st.state === 'error') body = Alert('error', 'circle-x', 'Couldn\'t load sites', 'Check your connection and try again.', 'Try again')
|
||||
else if (pg && pg.loading) body = Skel(m ? 6 : 8)
|
||||
else if (pg && pg.empty) body = Empty('search', 'No sites match "' + q + '"', 'Check the spelling, or search for a shorter part of the name.', 'Clear search')
|
||||
else {
|
||||
const mi = st.menu
|
||||
const items = i => { const x = rows[i]; return x.def ? [menuItem('pencil', 'Edit', { hv: !m }), menuItem('trash-2', 'Delete…', { dis: true, err: true })] : [menuItem('pencil', 'Edit', { hv: !m }), menuItem('star', 'Set as default'), sep, menuItem('trash-2', 'Delete…', { err: true })] }
|
||||
const tip = 'The default site can\'t be deleted. Make another site the default first.'
|
||||
const trs = rows.map((x, i) => {
|
||||
const open = mi === i
|
||||
const nameEl = D('display:flex;align-items:center;gap:8px;min-width:0', S('font-weight:500;color:var(--ui-text-highlighted);overflow:hidden;text-overflow:ellipsis;white-space:nowrap', x.n), x.def && Bd('Default', 'def'), x.robots === 'Noindex' && Bd('Noindex', 'noidx'))
|
||||
if (m) return D('position:relative;display:flex;align-items:center;gap:8px;padding:12px 4px 12px 16px;min-height:76px;border-bottom:1px solid var(--ui-border);background:' + (open ? 'var(--ui-bg-elevated)' : 'var(--ui-bg)'), D('flex:1;min-width:0;display:flex;flex-direction:column;gap:4px', nameEl, S('font:400 12px/18px \'IBM Plex Mono\',monospace;color:var(--ui-text-toned);overflow:hidden;text-overflow:ellipsis;white-space:nowrap', host(x.url)), S('font-size:12px;color:var(--ui-text-muted)', pl(x.c, 'article'))), Dots())
|
||||
return D('position:relative;display:grid;grid-template-columns:' + grid + ';gap:12px;min-height:52px;align-items:center;padding:0 12px;border-top:1px solid var(--ui-border);background:' + (open ? 'var(--ui-bg-elevated)' : 'var(--ui-bg)'), D('display:flex;flex-direction:column;gap:2px;min-width:0', nameEl, S('font:400 12px/16px \'IBM Plex Mono\',monospace;color:var(--ui-text-muted)', x.key)), S('font:400 12px/18px \'IBM Plex Mono\',monospace;color:var(--ui-text-toned);overflow:hidden;text-overflow:ellipsis;white-space:nowrap', x.url), S('color:var(--ui-text-muted)', pl(x.c, 'article')), Dots(),
|
||||
open && !m && MenuBox(items(i)), open && !m && rows[i].def && s.tip && D('position:absolute;right:240px;top:76px;z-index:6;max-width:240px;padding:6px 8px;background:var(--ui-bg-inverted);color:var(--ui-text-inverted);font-size:12px;line-height:18px;box-shadow:var(--rc-shadow-pop)', tip))
|
||||
})
|
||||
if (mi != null && m) ov.push(MenuBox(items(mi), rows[mi].n, rows[mi].def ? tip : null))
|
||||
body = D('display:flex;flex-direction:column;gap:12px', D('background:var(--ui-bg);border:1px solid var(--ui-border);' + (m ? 'margin:0 -16px;border-left:0;border-right:0' : ''), !m && TH(grid, ['Site', 'Base URL', 'Articles', '']), ...trs),
|
||||
st.only && S('color:var(--ui-text-muted);text-wrap:pretty', 'Add another site if your content is shown on more than one frontend. Each article belongs to one site.'))
|
||||
}
|
||||
return D('flex:1;min-height:0;overflow:hidden;padding:' + (m ? '16px 16px 88px' : '24px') + ';display:flex;flex-direction:column;gap:16px;position:relative', Head('Sites', 'The frontends that display your content.', 'Add site'), pg && SearchBox('Search by name or key'), pg ? D('flex:1;min-height:0;overflow:hidden', body) : body, pg && !pg.empty && PagerBlock(pg, 'site'))
|
||||
}
|
||||
const sitesModal = () => {
|
||||
const k = s.modal.k, x = s.modal, tgt = SITES[x.i ?? 1]
|
||||
if (k === 'setdef') return Shell({ title: 'Make ' + tgt.n + ' the default site?', desc: 'New articles start on this site. Articles that are already on other sites stay where they are.', cancel: 'Cancel', confirm: x.loading ? 'Saving…' : 'Make default', loading: x.loading, close: true }, D('display:none'))
|
||||
if (k === 'pick') return Picker({ title: 'Choose an image', desc: 'The default social image for ' + (x.n || 'this site') + '.', sel: x.sel })
|
||||
const n = tgt.c
|
||||
if (k === 'del0') return Shell({ title: 'Delete this site?', desc: '"' + tgt.n + '" will be deleted. No articles belong to it. This can\'t be undone.', cancel: 'Cancel', confirm: x.loading ? 'Deleting…' : 'Delete site', tone: 'danger', loading: x.loading }, x.notice ? Alert('error', 'circle-x', 'Couldn\'t delete the site, so it\'s still there. Try again in a moment.') : D('display:none'))
|
||||
const to = SITES[0]
|
||||
return Shell({ title: 'Delete this site?', desc: '"' + tgt.n + '" will be deleted. ' + pl(n, 'article') + ' belong to it, so choose a site to move them to. This can\'t be undone.', cancel: 'Cancel', confirm: x.loading ? 'Moving articles…' : 'Move ' + n + ' articles and delete', tone: 'danger', loading: x.loading, cdis: x.dis },
|
||||
D('display:flex;flex-direction:column;gap:16px', x.notice && Alert('error', 'circle-x', 'Couldn\'t delete the site', 'No articles were moved. Try again in a moment.'),
|
||||
F('Move articles to', to.n + ' · ' + host(to.url), { sel: true, focus: !!x.open, help: x.open ? null : pl(n, 'article') + ' will move to ' + to.n + '. Their canonical host changes to ' + host(to.url) + '.', dis: x.loading }),
|
||||
x.open && Opts(SITES.filter(y => y.n !== tgt.n).map(y => [y.n, host(y.url), 0]), to.n)))
|
||||
}
|
||||
// ---------- Authors
|
||||
const socials = { X: 'https://x.com/username', LinkedIn: 'https://www.linkedin.com/in/username', GitHub: 'https://github.com/username', Mastodon: 'https://mastodon.social/@username', Custom: 'https://example.com' }
|
||||
const authorForm = () => {
|
||||
const p = s.panel, f = { av: null, name: '', slug: '', slugMode: 'empty', bio: '', web: '', links: [], user: null, ...p.f }, er = p.err || {}, add = p.mode === 'add'
|
||||
const bl = [...f.bio].length
|
||||
const sl = f.links.map((l, i) => D('display:flex;gap:8px;align-items:flex-start', D('width:' + (m ? 112 : 108) + 'px;flex-shrink:0', F(null, l.t, { sel: true })), D('flex:1;min-width:0', F(null, l.v || socials[l.t], { val: !!l.v, mono: true, err: l.err, focus: l.focus })), S('width:' + (m ? 44 : 40) + 'px;height:' + ih + 'px;flex-shrink:0;display:flex;align-items:center;justify-content:center;color:var(--ui-text-muted);border:1px solid var(--ui-border-accented)', I('trash-2', 16))))
|
||||
const linked = f.user && !f.unlinkAsk
|
||||
const ownUser = D('display:flex;flex-direction:column;gap:6px', S('font-weight:500;color:var(--ui-text-highlighted)', 'Linked user'), D('display:flex;align-items:center;gap:10px;min-height:' + ih + 'px;padding:0 10px;border:1px solid var(--ui-border);background:var(--ui-bg-elevated)', I('link', 14, 'color:var(--ui-info)'), S('flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;color:var(--ui-text-highlighted)', f.user), I('lock', 14, 'color:var(--ui-text-muted)')), S('color:var(--ui-text-muted);font-size:12px;line-height:18px', 'This is your author profile. Only an owner or admin can change the link.'))
|
||||
const userF = p.own ? ownUser : f.user ? D('display:flex;flex-direction:column;gap:6px', S('font-weight:500;color:var(--ui-text-highlighted)', 'Linked user', S('font-weight:400;color:var(--ui-text-muted)', ' (optional)')), D('display:flex;align-items:center;gap:10px;min-height:' + ih + 'px;padding:0 6px 0 10px;border:1px solid var(--ui-border-accented)', I('link', 14, 'color:var(--ui-info)'), S('flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;color:var(--ui-text-highlighted)', f.user), B('Unlink', { h: m ? 44 : 28, fs: 12, px: 10 })), S('color:var(--ui-text-muted);font-size:12px;line-height:18px', 'New articles by this user start with this author.')) :
|
||||
D('display:flex;flex-direction:column;gap:6px', F('Linked user', f.uopen ? 'Choose a user' : 'No linked user', { opt: true, val: false, sel: true, focus: !!f.uopen, help: f.uopen ? null : 'Link a CMS user if this author has an account. Guest writers need no link.' }), f.uopen && (f.noUsers ? D('padding:12px;border:1px solid var(--ui-border);background:var(--ui-bg);color:var(--ui-text-muted)', 'Every user already has an author.') : Opts([['Marta Alves', 'marta@renew.example', 0, Av({ name: 'Marta Alves' }, 24)], ['Rui Santos', 'rui@renew.example', 0, Av({ name: 'Rui Santos' }, 24)]], null, S('display:block;padding:4px 8px 6px;font-size:12px;color:var(--ui-text-muted)', 'Users without an author'))))
|
||||
const pv = D('display:flex;gap:12px;padding:12px;background:var(--ui-bg-elevated);align-items:flex-start', Av({ name: f.name || 'Author', img: !!f.av }, 40), D('flex:1;min-width:0;display:flex;flex-direction:column;gap:2px', S('font-size:12px;color:var(--ui-text-muted)', 'Byline preview'), S('font-weight:600;color:var(--ui-text-highlighted);overflow:hidden;text-overflow:ellipsis;white-space:nowrap', f.name || 'Author name'), S('color:var(--ui-text-toned);font-size:12px;line-height:18px;overflow:hidden;display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical', f.bio || 'The bio appears here.')))
|
||||
return Panel({ title: add ? 'Add author' : 'Edit ' + f.name, notice: p.notice, saving: p.saving, confirm: p.saving ? 'Saving…' : add ? 'Add author' : 'Save changes' },
|
||||
D('display:flex;flex-direction:column;gap:18px', Pick(f.av, 'Avatar', null, { av: { name: f.name || 'Author', img: !!f.av } }),
|
||||
F('Name', f.name || 'e.g. Camille Roche', { val: !!f.name, focus: p.focus === 'name', err: er.name }),
|
||||
Slug('Slug', { mode: f.slugMode, value: f.slug, err: er.slug, suggest: er.suggest, help: 'Generated from the name. Used in public author URLs and API paths. Unique across all authors.', help2: 'Lowercase letters, numbers and hyphens. Unique across all authors.' }),
|
||||
F('Bio', f.bio || 'A sentence or two about the author.', { opt: true, area: true, val: !!f.bio, count: bl + ' / 280', countErr: bl > 280, err: er.bio, focus: p.focus === 'bio' }),
|
||||
F('Website', f.web || 'https://example.com', { opt: true, val: !!f.web, mono: true, err: er.web }),
|
||||
D('display:flex;flex-direction:column;gap:8px', S('font-weight:500;color:var(--ui-text-highlighted)', 'Social links', S('font-weight:400;color:var(--ui-text-muted)', ' (optional)')), ...sl, D('display:flex;align-items:center;gap:12px', f.links.length < 5 ? B('Add link', { icon: 'plus', h: m ? 44 : 28, fs: 12, px: 10 }) : S('color:var(--ui-text-muted);font-size:12px', 'You can add up to 5 links.'), S('color:var(--ui-text-muted);font-size:12px', f.links.length + ' of 5'))),
|
||||
userF), pv)
|
||||
}
|
||||
const authorView = () => {
|
||||
const a = AUTH[s.panel.i ?? 0]
|
||||
const lab = (t, v) => D('display:flex;flex-direction:column;gap:4px', S('font-weight:500;color:var(--ui-text-highlighted)', t), v)
|
||||
return Panel({ title: a.name, ro: true }, D('display:flex;flex-direction:column;gap:18px',
|
||||
D('display:flex;gap:14px;align-items:center', Av(a, 64), D('flex:1;min-width:0;display:flex;flex-direction:column;gap:4px', S('font:400 12px/18px \'IBM Plex Mono\',monospace;color:var(--ui-text-muted)', a.slug), D('display:flex;align-items:center;gap:8px;font-size:12px;color:var(--ui-text-muted)', a.user ? Bd('Linked', 'linked') : Bd('Guest', 'guest'), pl(a.c, 'article')))),
|
||||
a.bio && lab('Bio', S('color:var(--ui-text-toned);text-wrap:pretty', a.bio)),
|
||||
a.web && lab('Website', S('color:var(--ui-text-highlighted);text-decoration:underline;text-underline-offset:3px;' + mono, a.web)),
|
||||
D('display:flex;gap:10px;padding:12px;background:var(--ui-bg-elevated);color:var(--ui-text-toned)', I('lock', 14, 'margin-top:3px'), 'Only an owner or admin can change this author.')))
|
||||
}
|
||||
const authorsPage = () => {
|
||||
const st = s.list || 'ok'
|
||||
const pg = s.pg && { ...s.pg, q }
|
||||
let rows = pg ? (pg.empty ? [] : genAuthors(pg)) : AUTH
|
||||
if (q && !pg) rows = AUTH.filter(a => (a.name + a.slug).toLowerCase().includes(q.toLowerCase()))
|
||||
const grid = 'minmax(0,1.4fr) minmax(0,1fr) 110px 100px 44px'
|
||||
let body
|
||||
if (st === 'loading') body = Skel(6)
|
||||
else if (pg && pg.loading) body = Skel(m ? 6 : 8)
|
||||
else if (st === 'error') body = Alert('error', 'circle-x', 'Couldn\'t load authors', 'Check your connection and try again.', 'Try again')
|
||||
else if (st === 'empty') body = Empty('feather', 'No authors yet', 'Authors are the names readers see on articles. They don\'t need an account.', 'Add author', true)
|
||||
else if (q && !rows.length) body = Empty('search', 'No authors match "' + q + '"', 'Check the spelling, or search for a shorter part of the name.', 'Clear search')
|
||||
else {
|
||||
const mi = s.menu
|
||||
const items = [menuItem('pencil', 'Edit', { hv: !m }), sep, menuItem('trash-2', 'Delete…', { err: true })]
|
||||
if (mi != null && m) ov.push(MenuBox(items, rows[mi].name))
|
||||
const acct = a => a.user ? Bd('Linked', 'linked') : Bd('Guest', 'guest')
|
||||
const trs = rows.map((a, i) => {
|
||||
const open = mi === i
|
||||
if (m) return D('position:relative;display:flex;align-items:center;gap:12px;padding:12px 4px 12px 16px;min-height:76px;border-bottom:1px solid var(--ui-border);background:' + (open ? 'var(--ui-bg-elevated)' : 'var(--ui-bg)'), Av(a, 40), D('flex:1;min-width:0;display:flex;flex-direction:column;gap:3px', S('font-weight:500;font-size:15px;line-height:21px;color:var(--ui-text-highlighted);overflow:hidden;text-overflow:ellipsis;white-space:nowrap', a.name), S('font:400 12px/16px \'IBM Plex Mono\',monospace;color:var(--ui-text-muted);overflow:hidden;text-overflow:ellipsis;white-space:nowrap', a.slug), D('display:flex;align-items:center;gap:8px;font-size:12px;color:var(--ui-text-muted)', acct(a), pl(a.c, 'article'))), Dots())
|
||||
return D('position:relative;display:grid;grid-template-columns:' + grid + ';gap:12px;min-height:52px;align-items:center;padding:0 12px;border-top:1px solid var(--ui-border);background:' + (open ? 'var(--ui-bg-elevated)' : 'var(--ui-bg)'), D('display:flex;align-items:center;gap:10px;min-width:0', Av(a, 32), S('font-weight:500;color:var(--ui-text-highlighted);overflow:hidden;text-overflow:ellipsis;white-space:nowrap', a.name)), S('font:400 12px/18px \'IBM Plex Mono\',monospace;color:var(--ui-text-muted);overflow:hidden;text-overflow:ellipsis;white-space:nowrap', a.slug), D('display:flex', acct(a)), S('color:var(--ui-text-muted)', pl(a.c, 'article')), Dots(), open && MenuBox(items))
|
||||
})
|
||||
body = D('background:var(--ui-bg);border:1px solid var(--ui-border);' + (m ? 'margin:0 -16px;border-left:0;border-right:0' : ''), !m && TH(grid, ['Author', 'Slug', 'Account', 'Articles', '']), ...trs)
|
||||
}
|
||||
const showTool = st !== 'empty' && st !== 'error'
|
||||
return D('flex:1;min-height:0;overflow:hidden;padding:' + (m ? '16px 16px 88px' : '24px') + ';display:flex;flex-direction:column;gap:16px;position:relative', Head('Authors', s.ro ? 'The names readers see on your articles. Only an owner or admin can change authors.' : 'The names readers see on your articles. An author doesn\'t need an account.', s.ro ? null : 'Add author'), showTool && SearchBox(), pg ? D('flex:1;min-height:0;overflow:hidden', body) : body, pg && !pg.empty && PagerBlock(pg, 'author'))
|
||||
}
|
||||
const authorsModal = () => {
|
||||
const x = s.modal, k = x.k, a = AUTH[x.i ?? 2]
|
||||
if (k === 'pick') return Picker({ title: 'Choose an image', desc: 'The avatar for ' + (x.n || 'this author') + '.', sel: x.sel, sq: true })
|
||||
if (k === 'unlink') return Shell({ title: 'Unlink ' + a.name + '?', desc: a.name + ' will stay on their articles. New articles by ' + a.user + ' will no longer start with this author.', cancel: 'Cancel', confirm: x.loading ? 'Unlinking…' : 'Unlink user', loading: x.loading, close: true }, D('display:none'))
|
||||
if (k === 'relink') return Shell({ title: 'Link ' + a.name + ' to a user?', desc: 'Only users without an author are listed.', cancel: 'Cancel', confirm: 'Link user', cdis: true, close: true }, D('display:flex;flex-direction:column;gap:12px', F('Linked user', 'Choose a user', { sel: true, val: false, focus: true }), Opts([['Marta Alves', 'marta@renew.example', 0, Av({ name: 'Marta Alves' }, 24)], [ 'Rui Santos', 'rui@renew.example', 0, Av({ name: 'Rui Santos' }, 24)]])))
|
||||
const n = a.c
|
||||
if (k === 'del0') return Shell({ title: 'Delete this author?', desc: '"' + a.name + '" will be deleted. No articles credit this author. This can\'t be undone.', cancel: 'Cancel', confirm: x.loading ? 'Deleting…' : 'Delete author', tone: 'danger', loading: x.loading }, D('display:none'))
|
||||
if (k === 'blocked') return Shell({ title: 'Can\'t delete this author', desc: '"' + a.name + '" is credited on ' + pl(n, 'article') + '. Choose another author to credit instead, or remove ' + a.name + ' from those articles first.', cancel: 'Close', confirm: 'Reassign articles', close: true }, a.user ? Alert('info', 'info', 'Linked to ' + a.user, 'Deleting the author doesn\'t affect the user account.') : D('display:none'))
|
||||
const to = AUTH[0]
|
||||
return Shell({ title: 'Delete this author?', desc: '"' + a.name + '" will be deleted and is credited on ' + pl(n, 'article') + '. This can\'t be undone.', cancel: 'Cancel', confirm: x.loading ? 'Reassigning…' : 'Delete and reassign ' + n + ' articles', tone: 'danger', loading: x.loading, close: !x.loading },
|
||||
D('display:flex;flex-direction:column;gap:16px', x.notice && Alert('error', 'circle-x', 'Couldn\'t delete the author', 'Nothing was changed. Try again in a moment.'),
|
||||
F('Credit these articles to', x.none ? 'Nobody' : to.name, { sel: true, focus: !!x.open, dis: x.loading, help: x.open ? null : x.none ? 'The articles keep any other authors. Articles with only this author will have no byline.' : 'Where an article has several authors, ' + a.name + ' is removed and the others stay.' }),
|
||||
x.open && Opts([...AUTH.filter(y => y.name !== a.name).slice(0, 4).map(y => [y.name, y.slug, 0, Av(y, 24)]), ['Nobody', 'Remove the byline', 0, S('width:24px;height:24px;display:flex;align-items:center;justify-content:center;border:1px dashed var(--ui-border-accented);color:var(--ui-text-muted)', I('user-x', 14))]], x.none ? 'Nobody' : to.name),
|
||||
a.user && S('color:var(--ui-text-muted);font-size:12px', 'Linked to ' + a.user + '. The user account isn\'t affected.')))
|
||||
}
|
||||
// ---------- Editor: site and authors
|
||||
const metaUI = () => {
|
||||
const mt = s.meta || {}, au = (mt.authors || []).map(AV), n = au.length, st = mt.state || 'ok'
|
||||
const out = []
|
||||
if (mt.hint) out.push(D('display:flex;gap:10px;padding:12px;background:var(--rc-info-soft);color:var(--ui-info)', S('display:flex;padding-top:2px', I('info')), D('flex:1;min-width:0;display:flex;flex-direction:column;gap:8px', D('display:flex;flex-direction:column;gap:2px', S('font-weight:600', 'You don\'t have an author profile yet'), S('color:var(--ui-text-toned)', 'Create one to be credited on your articles.')), B('Create my author profile', { icon: 'feather', h: m ? 44 : 28, fs: 12, px: 10 })), S('width:' + (m ? 44 : 24) + 'px;height:' + (m ? 44 : 24) + 'px;margin:' + (m ? '-10px -10px 0 0' : '-4px -4px 0 0') + ';display:flex;align-items:center;justify-content:center;color:var(--ui-text-toned)', I('x', 14))))
|
||||
if (mt.sites) out.push(D('display:flex;flex-direction:column;gap:6px', F('Site', (mt.site || 'Journal') + ' · ' + host(SITES.find(x => x.n === (mt.site || 'Journal')).url), { sel: true, focus: mt.open === 'site' }), mt.open === 'site' ? Opts(SITES.map(x => [x.n, host(x.url), 0]), mt.site || 'Journal') : D('display:flex;align-items:center;gap:6px;color:var(--ui-text-muted);font-size:12px;line-height:18px', I('link', 12), S('', 'Canonical host: ', S('color:var(--ui-text-toned);' + mono, host(SITES.find(x => x.n === (mt.site || 'Journal')).url))))))
|
||||
const chip = (a, i) => {
|
||||
const grab = mt.grab === i, lift = mt.drag === i
|
||||
return D('display:flex;align-items:center;gap:' + (m ? 8 : 6) + 'px;min-height:' + (m ? 48 : 32) + 'px;padding:0 ' + (m ? 4 : 2) + 'px 0 2px;border:1px solid ' + (grab || lift ? 'var(--ui-primary)' : 'var(--ui-border-accented)') + ';background:' + (lift ? 'var(--ui-bg)' : 'var(--ui-bg)') + ';' + (grab ? 'outline:2px solid var(--ui-primary);outline-offset:1px;' : '') + (lift ? 'box-shadow:var(--rc-shadow-pop);position:relative;z-index:2;transform:translateX(4px);' : ''),
|
||||
S('width:' + (m ? 36 : 24) + 'px;height:' + (m ? 36 : 24) + 'px;flex-shrink:0;display:flex;align-items:center;justify-content:center;color:' + (grab || lift ? 'var(--ui-text-highlighted)' : 'var(--ui-text-muted)'), I('grip-vertical', 14)), Av(a, m ? 28 : 22),
|
||||
S('flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-weight:500;color:var(--ui-text-highlighted)', a.name),
|
||||
i === 0 && n > 1 && Bd('Primary', 'prim', 18),
|
||||
S('width:' + (m ? 44 : 24) + 'px;height:' + (m ? 44 : 24) + 'px;flex-shrink:0;display:flex;align-items:center;justify-content:center;color:var(--ui-text-muted)', I('x', 14)))
|
||||
}
|
||||
const list = []
|
||||
au.forEach((a, i) => { if (mt.drop === i) list.push(D('height:2px;background:var(--ui-primary);margin:-1px 0')); list.push(chip(a, i)) })
|
||||
const body = [S('font-weight:500;color:var(--ui-text-highlighted)', 'Authors')]
|
||||
if (!n) body.push(D('padding:12px;border:1px dashed var(--ui-border-accented);color:var(--ui-text-muted);text-wrap:pretty', 'No authors. This article will have no byline.'))
|
||||
else body.push(D('display:flex;flex-direction:column;gap:4px', ...list))
|
||||
const trig = D('display:flex;align-items:center;gap:8px;min-height:' + ih + 'px;padding:0 10px;border:1px solid ' + (mt.open === 'authors' ? 'var(--ui-primary)' : 'var(--ui-border-accented)') + ';' + (mt.open === 'authors' ? 'box-shadow:inset 0 0 0 1px var(--ui-primary);' : '') + 'background:var(--ui-bg);color:var(--ui-text-muted);font-size:' + fs + 'px', I('plus', 14), S('flex:1;color:' + (mt.q ? 'var(--ui-text-highlighted)' : 'var(--ui-text-muted)'), mt.open === 'authors' ? (mt.q || 'Search authors') : 'Add an author'), I('chevron-down', 14))
|
||||
body.push(trig)
|
||||
if (mt.open === 'authors') {
|
||||
const chosen = au.map(a => a.name), q2 = mt.q
|
||||
let opts = AUTH.filter(a => !q2 || a.name.toLowerCase().includes(q2.toLowerCase()))
|
||||
const create = D('min-height:' + (m ? 48 : 36) + 'px;padding:4px 8px;display:flex;align-items:center;gap:8px;color:var(--ui-text-highlighted);font-weight:500;border-top:1px solid var(--ui-border)', I('plus', 16), q2 ? 'Create author "' + q2 + '"…' : 'Create author…')
|
||||
let inner
|
||||
if (st === 'loading') inner = [D('display:flex;flex-direction:column;gap:10px;padding:10px 8px', ...[0, 1, 2].map(() => D('display:flex;gap:8px;align-items:center', S('display:block;width:24px;height:24px;background:var(--ui-bg-accented)'), S('display:block;width:50%;height:12px;background:var(--ui-bg-accented)'))))]
|
||||
else if (st === 'error') inner = [D('padding:10px 8px;display:flex;flex-direction:column;gap:8px', S('color:var(--ui-error);font-weight:500', 'Couldn\'t load authors'), S('color:var(--ui-text-muted)', 'Check your connection and try again.'), B('Try again', { icon: 'rotate-cw', z: 14, h: m ? 44 : 28, fs: 12, px: 10 }))]
|
||||
else if (!opts.length) inner = [D('padding:10px 8px;color:var(--ui-text-muted)', 'No author matches "' + q2 + '".')]
|
||||
else inner = opts.map(a => D('min-height:' + (m ? 48 : 36) + 'px;padding:4px 8px;display:flex;align-items:center;gap:8px;color:var(--ui-text-highlighted);opacity:' + (chosen.includes(a.name) ? 0.6 : 1), Av(a, 24), D('flex:1;min-width:0;display:flex;flex-direction:column', S('overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-weight:500', a.name), S('font-size:12px;color:var(--ui-text-muted);overflow:hidden;text-overflow:ellipsis;white-space:nowrap;' + mono, a.slug)), chosen.includes(a.name) && I('check', 14)))
|
||||
body.push(D('border:1px solid var(--ui-border);background:var(--ui-bg);box-shadow:var(--rc-shadow-pop);' + (m ? '' : ''), D('padding:4px', ...inner), st === 'error' || mt.noCreate ? null : create))
|
||||
}
|
||||
if (mt.grab != null) body.push(S('font-size:12px;line-height:18px;color:var(--ui-text-toned);padding:6px 8px;background:var(--ui-bg-elevated)', au[mt.grab].name + ' grabbed. Position ' + (mt.grab + 1) + ' of ' + n + '. Use the up and down arrow keys to move, Space to drop, Escape to cancel.'))
|
||||
else if (n > 1 && mt.open !== 'authors') body.push(S('font-size:12px;line-height:18px;color:var(--ui-text-muted)', 'Drag to reorder. The first author is the primary byline.'))
|
||||
out.push(D('display:flex;flex-direction:column;gap:8px', ...body))
|
||||
return D('display:flex;flex-direction:column;gap:16px', ...out)
|
||||
}
|
||||
const newAuthorModal = () => {
|
||||
const x = s.modal
|
||||
return Shell({ z: 60, title: 'Create author', desc: 'Adds a byline for this article. You can add a bio and avatar later in Authors.', cancel: 'Cancel', confirm: x.loading ? 'Creating…' : 'Create author', loading: x.loading, close: true, cdis: !x.name },
|
||||
D('display:flex;flex-direction:column;gap:16px', x.notice && Alert('error', 'circle-x', 'Couldn\'t create the author', 'The article is unchanged. Try again in a moment.'),
|
||||
F('Name', x.name || 'e.g. Camille Roche', { val: !!x.name, focus: !x.name && !x.loading, err: x.err, dis: x.loading }),
|
||||
Slug('Slug', { mode: x.name ? (x.err ? 'manual' : 'auto') : 'empty', value: x.slug, help: 'Generated from the name. Unique across all authors.', err: x.slugErr, suggest: x.suggest }),
|
||||
x.me && D('display:flex;gap:10px;align-items:flex-start', S('width:20px;height:20px;flex-shrink:0;margin-top:1px;display:flex;align-items:center;justify-content:center;border:1px solid var(--ui-primary);background:var(--ui-primary);color:var(--ui-bg)', I('check', 14)), D('display:flex;flex-direction:column', S('font-weight:500;color:var(--ui-text-highlighted)', 'This is me'), S('color:var(--ui-text-muted);font-size:12px', 'Links the author to marta@renew.example.')))))
|
||||
}
|
||||
// ---------- Editor: search and sharing
|
||||
const ATT = 'How we price a bathroom renovation', ASLUG = 'how-we-price-a-bathroom-renovation', AD1 = 'A bathroom renovation is priced by room size, plumbing changes and finish level.'
|
||||
const SUG = {
|
||||
title_long: ['The meta title is 74 characters. Search engines may cut it off after about 60.', 'meta title'],
|
||||
title_empty: ['No meta title yet. The article title is used instead.', 'meta title'],
|
||||
desc_short: ['The description is 41 characters. About 70 to 160 reads best in results.', 'meta description'],
|
||||
desc_long: ['The description is 212 characters. Search engines may cut it off after about 160.', 'meta description'],
|
||||
cover_alt: ['The cover image has no alt text. Add a short description of it.', 'cover image'],
|
||||
cover_none: ['No cover image. The site\'s social image is used.', 'cover image'],
|
||||
slug_long: ['The slug is 86 characters. Shorter addresses are easier to share.', 'URL slug'],
|
||||
no_au: ['This article has no authors, so the structured data has no author.', 'authors'],
|
||||
no_h: ['The body has no headings. H2 headings help readers scan the article.', 'body'],
|
||||
body_alt: ['2 images in the body have no alt text.', 'body'],
|
||||
short: ['The article is under 300 words. That is fine for a short note.', 'body']
|
||||
}
|
||||
const Chip = t => S('height:20px;padding:0 6px;align-self:flex-start;display:inline-flex;align-items:center;gap:4px;border:1px dashed var(--ui-border-accented);font:500 11px/16px \'IBM Plex Mono\',monospace;color:var(--ui-text-toned);white-space:nowrap', I('corner-down-right', 10), t)
|
||||
const Ct = (n, lo, hi) => S('font:400 12px \'IBM Plex Mono\',monospace;color:' + (n && (n < lo || n > hi) ? 'var(--ui-warning)' : 'var(--ui-text-muted)'), n + ' / ' + hi)
|
||||
const FW = (lab, val, o = {}) => D('display:flex;flex-direction:column;gap:6px;min-width:0', D('display:flex;justify-content:space-between;align-items:center;gap:8px', S('font-weight:500;color:var(--ui-text-highlighted)', lab, !o.req && S('font-weight:400;color:var(--ui-text-muted)', ' (optional)')), o.ct), F(null, val, o), o.fb && Chip(o.fb))
|
||||
const Dis = (t, o = {}) => D('display:flex;flex-direction:column;gap:12px;padding:12px;border:1px solid var(--ui-border)', D('display:flex;align-items:center;gap:8px;min-height:' + (m ? 44 : 24) + 'px;color:var(--ui-text-highlighted)', I(o.open ? 'chevron-down' : 'chevron-right', 14), S('font-weight:600', t), o.tag && Note(o.tag), S('flex:1;text-align:right;font-size:12px;color:var(--ui-text-muted);overflow:hidden;text-overflow:ellipsis;white-space:nowrap', o.sum)), ...(o.open ? o.kids : []))
|
||||
const SugRow = (c, o = {}) => D('display:flex;align-items:flex-start;gap:8px', S('display:flex;padding-top:2px;color:var(--ui-warning)', I('lightbulb', 14)), D('flex:1;min-width:0;display:flex;flex-direction:column;gap:2px', S('text-wrap:pretty;color:var(--ui-text-highlighted)', SUG[c][0]), Link('Go to ' + SUG[c][1], 'arrow-right')), !o.compact && S('width:' + (m ? 44 : 24) + 'px;height:' + (m ? 44 : 24) + 'px;flex-shrink:0;display:flex;align-items:center;justify-content:center;color:var(--ui-text-muted)', I('x', 14)))
|
||||
const Sugs = (codes, st, o = {}) => {
|
||||
const box = (...c) => D('display:flex;flex-direction:column;gap:12px;padding:12px;background:var(--ui-bg-elevated)', ...c)
|
||||
if (st === 'loading') return box(D('display:flex;align-items:center;gap:8px;color:var(--ui-text-toned)', I('loader-circle', 14), 'Checking this article…'), ...[70, 90, 55].map(w => S('display:block;height:12px;width:' + w + '%;background:var(--ui-bg-accented)')))
|
||||
if (!codes.length) return box(D('display:flex;align-items:flex-start;gap:8px', S('display:flex;padding-top:2px;color:var(--ui-success)', I('circle-check', 14)), D('display:flex;flex-direction:column;gap:2px', S('font-weight:600;color:var(--ui-text-highlighted)', 'All good'), S('color:var(--ui-text-muted)', o.dismissed ? o.dismissed + ' dismissed suggestions are hidden.' : 'Nothing to suggest for this article.')), o.dismissed && Link('Show dismissed')))
|
||||
const shown = o.compact ? codes.slice(0, 3) : codes
|
||||
return box(...shown.map(c => SugRow(c, o)), o.compact && codes.length > 3 && S('color:var(--ui-text-muted);font-size:12px', '+' + (codes.length - 3) + ' more in Search and sharing'), !o.compact && S('color:var(--ui-text-muted);font-size:12px;line-height:18px;text-wrap:pretty', 'Suggestions never block saving or publishing. Dismiss one and it stays hidden for this article.' ))
|
||||
}
|
||||
const SEOSIDE = (k) => {
|
||||
const codes = k.codes || [], st = k.state || 'ok'
|
||||
return D('display:flex;flex-direction:column;gap:12px',
|
||||
D('display:flex;flex-direction:column;gap:4px;padding:8px;background:var(--ui-bg-elevated)', S('font-size:12px;color:var(--ui-text-muted)', 'Address'), S('font:400 12px/18px \'IBM Plex Mono\',monospace;color:var(--ui-text-highlighted);word-break:break-all', host(SITES[k.site || 0].url) + '/' + (k.slug || ASLUG))),
|
||||
k.hidden && D('display:flex;gap:8px;color:var(--ui-warning)', S('display:flex;padding-top:2px', I('eye-off', 14)), S('color:var(--ui-text-toned);text-wrap:pretty', 'Hidden from search engines. This only sets a flag in the API.')),
|
||||
Sugs(codes, st, { compact: true, dismissed: k.dismissed }),
|
||||
D('display:flex;flex-direction:column;gap:8px', B('Edit search and sharing', { icon: 'search', h: m ? 44 : 32 }), B('What the frontend gets', { icon: 'braces', h: m ? 44 : 32 })))
|
||||
}
|
||||
const trunc = (t, n) => [...t].length > n ? [...t].slice(0, n - 1).join('').trimEnd() + '…' : t
|
||||
const SERP = (p, site) => {
|
||||
const dev = p.dev || 'desktop', tt = trunc((p.mt || ATT) + ' | ' + site.n, dev === 'desktop' ? 60 : 70)
|
||||
const dd = p.md || p.ex || AD1, dt = trunc(dd, dev === 'desktop' ? 160 : 120)
|
||||
const fb = [!p.mt && 'Using article title', !p.md && p.ex && 'Using excerpt', !p.md && !p.ex && 'Using first sentence of the body'].filter(Boolean)
|
||||
return D('display:flex;flex-direction:column;gap:8px', D('display:flex;justify-content:space-between;align-items:center;gap:8px', S('font-weight:600;color:var(--ui-text-highlighted)', 'Search result'), D('display:flex;border:1px solid var(--ui-border-accented);width:150px', ...[['desktop', 'Desktop'], ['mobile', 'Mobile']].map(([k, t]) => S('flex:1;height:' + (m ? 44 : 24) + 'px;display:flex;align-items:center;justify-content:center;font-size:12px;font-weight:' + (dev === k ? 500 : 400) + ';background:' + (dev === k ? 'var(--rc-sand)' : 'var(--ui-bg)') + ';color:' + (dev === k ? 'var(--rc-on-sand)' : 'var(--ui-text-toned)'), t)))),
|
||||
D('padding:14px;border:1px solid var(--ui-border);background:var(--ui-bg);display:flex;flex-direction:column;gap:4px;' + (dev === 'mobile' && !m ? 'width:280px;' : ''), D('display:flex;align-items:center;gap:8px;min-width:0', S('width:22px;height:22px;flex-shrink:0;display:flex;align-items:center;justify-content:center;border-radius:50%;background:var(--ui-bg-elevated);font:600 11px/1 \'IBM Plex Sans\',sans-serif;color:var(--ui-text-highlighted)', site.n[0]), D('display:flex;flex-direction:column;min-width:0', S('font-size:12px;line-height:16px;color:var(--ui-text-highlighted)', site.n), S('font-size:11px;line-height:14px;color:var(--ui-text-muted);overflow:hidden;text-overflow:ellipsis;white-space:nowrap', host(site.url) + ' › ' + (p.slug || ASLUG).slice(0, 36)))), S('font:400 ' + (dev === 'desktop' ? 18 : 16) + 'px/1.3 \'IBM Plex Sans\',sans-serif;color:var(--ui-info);margin-top:4px;word-break:break-word', tt), S('font-size:13px;line-height:19px;color:var(--ui-text-toned);word-break:break-word', dt)),
|
||||
fb.length ? D('display:flex;gap:6px;flex-wrap:wrap', ...fb.map(Chip)) : null, (p.mt || ATT).length + site.n.length + 3 > (dev === 'desktop' ? 60 : 70) ? S('font-size:12px;color:var(--ui-text-muted)', 'Cut off here, the way a search engine would.') : null)
|
||||
}
|
||||
const SOC = (p, site) => {
|
||||
const sx = p.soc || {}, hasImg = !!(sx.img || p.cover), t = sx.t || p.mt || ATT, d = sx.d || p.md || p.ex || AD1
|
||||
return D('display:flex;flex-direction:column;gap:8px', S('font-weight:600;color:var(--ui-text-highlighted)', 'Social card'),
|
||||
D('border:1px solid var(--ui-border);background:var(--ui-bg)', S('display:flex;align-items:center;justify-content:center;aspect-ratio:1.91/1;background:repeating-linear-gradient(135deg, var(--ui-border) 0 1px, transparent 1px 12px), var(--rc-sand);color:var(--ui-text-muted);font:400 11px \'IBM Plex Mono\',monospace', hasImg ? (sx.img || 'north-wall.jpg') : (site.img || 'site social image')), D('padding:10px 12px;display:flex;flex-direction:column;gap:2px;border-top:1px solid var(--ui-border)', S('font-size:11px;line-height:16px;text-transform:uppercase;color:var(--ui-text-muted)', host(site.url)), S('font-weight:600;color:var(--ui-text-highlighted);overflow:hidden;text-overflow:ellipsis;white-space:nowrap', t), S('font-size:12px;line-height:18px;color:var(--ui-text-toned);overflow:hidden;display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical', d))),
|
||||
D('display:flex;gap:6px;flex-wrap:wrap', ...[!sx.t && 'Using meta title', !sx.d && 'Using meta description', !sx.img && (p.cover ? 'Using cover image' : 'Using site social image')].filter(Boolean).map(Chip)))
|
||||
}
|
||||
const seoPanel = () => {
|
||||
const p = s.seo.panel, site = SITES[p.site || 0], dis = p.state === 'saving', er = p.err || {}
|
||||
const sl = p.slug || ASLUG, sm = p.slugMode || 'auto'
|
||||
const cv = p.cover, soc = p.soc || {}
|
||||
const left = D('display:flex;flex-direction:column;gap:18px;margin-top:' + (p.scrollY ? -p.scrollY + 'px' : '0'),
|
||||
D('display:flex;flex-direction:column;gap:8px', Slug('URL slug', { mode: sm === 'taken' ? 'manual' : sm, value: sl, err: sm === 'taken' ? 'The slug "' + sl + '" is already used on ' + site.n + '.' : er.slug, suggest: sm === 'taken' ? sl + '-2' : null, reset: 'Reset to match the title', emptyText: 'Generated from the title', help: 'Generated from the title until you edit it. Lowercase letters, numbers and hyphens. Unique on ' + site.n + '.', help2: 'Lowercase letters, numbers and hyphens. Unique on ' + site.n + '.' }), D('display:flex;gap:6px;align-items:center;padding:8px 10px;background:var(--ui-bg-elevated);min-width:0', I('link', 12, 'color:var(--ui-text-muted)'), S('font:400 12px/18px \'IBM Plex Mono\',monospace;color:var(--ui-text-highlighted);word-break:break-all', site.url + '/' + sl))),
|
||||
FW('Meta title', p.mt || ATT, { val: !!p.mt, ct: Ct([...(p.mt || '')].length, 30, 60), focus: p.focus === 'mt', dis, fb: p.mt ? null : 'Using article title', help: 'Recommended 30 to 60 characters. This is a guide, not a limit.' }),
|
||||
FW('Meta description', p.md || p.ex || AD1, { val: !!p.md, area: true, ct: Ct([...(p.md || '')].length, 70, 160), focus: p.focus === 'md', dis, fb: p.md ? null : p.ex ? 'Using excerpt' : 'Using first sentence of the body', help: 'Recommended 70 to 160 characters.' }),
|
||||
FW('Excerpt', p.ex || 'A short summary. It is also sent as the article teaser.', { val: !!p.ex, area: true, ct: S('font:400 12px \'IBM Plex Mono\',monospace;color:' + (p.exErr ? 'var(--ui-error)' : 'var(--ui-text-muted)'), [...(p.ex || '')].length + ' / 300'), err: p.exErr, dis, help: p.exErr ? null : 'Used as the description when there is none, and as the teaser for the frontend.' }),
|
||||
D('display:flex;flex-direction:column;gap:10px', Pick(cv ? 'north-wall.jpg' : null, 'Cover image', cv ? null : 'Using the site social image' + (site.img ? ' (' + site.img + ')' : '') + '.'), cv && FW('Alt text', cv.alt || 'Describe the image for people who can\'t see it', { req: true, val: !!cv.alt, dis, help: cv.alt ? null : 'Needed before the cover counts as ready. Sent as image alt in the API.' })),
|
||||
Dis('Social sharing', { open: p.social, tag: 'Optional', sum: p.social ? '' : (soc.t || soc.d || soc.img) ? 'Customised' : 'Uses the meta values', kids: [FW('Social title', soc.t || p.mt || ATT, { val: !!soc.t, ct: Ct([...(soc.t || '')].length, 0, 90), dis, fb: soc.t ? null : 'Using meta title' }), FW('Social description', soc.d || p.md || p.ex || AD1, { val: !!soc.d, area: true, dis, fb: soc.d ? null : 'Using meta description' }), Pick(soc.img || null, 'Social image', soc.img ? null : 'Using the cover image.')] }),
|
||||
Dis('Advanced', { open: p.adv, sum: p.adv ? '' : p.canon ? 'Canonical URL set' : 'Canonical URL: automatic', kids: [FW('Canonical URL', p.canon || site.url + '/' + sl, { val: !!p.canon, mono: true, dis, err: er.canon, focus: p.focus === 'canon', fb: p.canon ? null : 'Using site address and slug', help: er.canon ? null : 'Only change this if the same content lives at another address.' })] }),
|
||||
Sw(!!p.noindex, 'Hide from search engines', 'Sets noindex in the API. It doesn\'t change who can read the article.', dis))
|
||||
const right = D('display:flex;flex-direction:column;gap:18px;min-width:0', SERP(p, site), SOC(p, site), D('display:flex;flex-direction:column;gap:8px', S('font-weight:600;color:var(--ui-text-highlighted)', 'Suggestions'), Sugs(p.codes || [], p.sugState, { dismissed: p.dismissed })), D('display:flex;gap:8px;align-items:center', B('What the frontend gets', { icon: 'braces', h: m ? 44 : 28, fs: 12, px: 10 })))
|
||||
const body = m ? D('display:flex;flex-direction:column;gap:18px', Sugs(p.codes || [], p.sugState, { dismissed: p.dismissed }), left, SERP(p, site), SOC(p, site), B('What the frontend gets', { icon: 'braces' })) : D('display:grid;grid-template-columns:minmax(0,1fr) 340px;gap:28px;height:100%;overflow:hidden', D('overflow:hidden;min-height:0', left), right)
|
||||
return Panel({ title: 'Search and sharing', w: 960, z: 60, notice: p.notice, saving: dis, cdis: p.noChange, confirm: dis ? 'Saving…' : 'Save changes' }, body)
|
||||
}
|
||||
const API = { title: ATT + ' | Renew', description: AD1, canonical_url: 'https://renew.example/' + ASLUG, robots: 'index, follow', og: { type: 'article', title: ATT + ' | Renew', description: AD1, url: 'https://renew.example/' + ASLUG, site_name: 'Renew', image: 'https://renew.example/media/north-wall.jpg', image_alt: 'A tiled bathroom wall during renovation', locale: 'en' }, twitter: { card: 'summary_large_image', title: ATT + ' | Renew', description: AD1, image: 'https://renew.example/media/north-wall.jpg', image_alt: 'A tiled bathroom wall during renovation' }, image: { url: 'https://renew.example/media/north-wall.jpg', alt: 'A tiled bathroom wall during renovation', source: 'cover_image' }, authors: [{ name: 'Inès Duarte', url: 'https://ines-duarte.example', same_as: ['https://www.linkedin.com/in/ines-duarte'] }], published_at: '2026-03-12T09:14:00Z', modified_at: '2026-10-15T11:02:00Z', fallbacks: { title: 'article_title', description: 'body_first_sentence', image: 'cover_image', canonical: 'site_base_url_and_slug' }, json_ld: { '@context': 'https://schema.org', '@type': 'Article', headline: ATT, description: AD1, image: ['https://renew.example/media/north-wall.jpg'], author: [{ '@type': 'Person', name: 'Inès Duarte', url: 'https://ines-duarte.example', sameAs: ['https://www.linkedin.com/in/ines-duarte'] }], datePublished: '2026-03-12T09:14:00Z', dateModified: '2026-10-15T11:02:00Z', mainEntityOfPage: 'https://renew.example/' + ASLUG } }
|
||||
const apiDialog = () => {
|
||||
const x = s.seo.api, raw = x.view === 'raw', st = x.state || 'ok'
|
||||
const bar = D('display:flex;align-items:center;justify-content:space-between;gap:8px;flex-wrap:wrap', D('display:flex;border:1px solid var(--ui-border-accented);width:200px', ...[['formatted', 'Formatted'], ['raw', 'Raw JSON']].map(([k, t]) => S('flex:1;height:' + bh + 'px;display:flex;align-items:center;justify-content:center;font-weight:' + ((raw ? 'raw' : 'formatted') === k ? 500 : 400) + ';background:' + ((raw ? 'raw' : 'formatted') === k ? 'var(--rc-sand)' : 'var(--ui-bg)') + ';color:' + ((raw ? 'raw' : 'formatted') === k ? 'var(--rc-on-sand)' : 'var(--ui-text-toned)'), t))), B(x.copied ? 'Copied' : 'Copy JSON', { icon: x.copied ? 'check' : 'copy', dis: st !== 'ok' }))
|
||||
const KV = (k, v, fbk) => D('display:grid;grid-template-columns:' + (m ? '1fr' : '130px minmax(0,1fr)') + ';gap:' + (m ? 2 : 12) + 'px;padding:6px 0;border-bottom:1px solid var(--ui-border-muted)', S('color:var(--ui-text-muted);font:400 12px/20px \'IBM Plex Mono\',monospace', k), D('display:flex;gap:8px;flex-wrap:wrap;align-items:center;min-width:0', S('color:var(--ui-text-highlighted);word-break:break-all;' + (m ? '' : ''), v), fbk && Chip(fbk)))
|
||||
let body
|
||||
if (st === 'loading') body = D('display:flex;flex-direction:column;gap:12px', ...[40, 80, 60, 70, 50, 75].map(w => S('display:block;height:14px;width:' + w + '%;background:var(--ui-bg-accented)')))
|
||||
else if (st === 'error') body = Alert('error', 'circle-x', 'Couldn\'t load the SEO data', 'GET /v1/article/12/seo failed. Your article is unchanged. Try again in a moment.', 'Try again')
|
||||
else if (raw) body = S('display:block;max-height:' + (m ? 440 : 400) + 'px;overflow:hidden;padding:12px;background:var(--ui-bg-elevated);white-space:pre;font:400 12px/18px \'IBM Plex Mono\',monospace;color:var(--ui-text-highlighted)', JSON.stringify(API, null, 2))
|
||||
else body = D('display:flex;flex-direction:column', KV('title', API.title, 'article title + template'), KV('description', API.description, 'first sentence of the body'), KV('canonical_url', API.canonical_url, 'site address + slug'), KV('robots', API.robots, 'site default'), KV('og.type', 'article'), KV('og.image', API.image.url, 'cover image'), KV('og.image_alt', API.image.alt), KV('twitter.card', 'summary_large_image'), KV('authors', 'Inès Duarte · ines-duarte.example · 1 social link'), KV('published_at', '12 Mar 2026, 09:14'), KV('modified_at', '15 Oct 2026, 11:02'), KV('json_ld', 'Article · headline, image, author, datePublished, dateModified, mainEntityOfPage'))
|
||||
return Shell({ title: 'What the frontend gets', desc: 'The SEO data returned by GET /v1/article/12/seo, read only. RenewCMS doesn\'t render pages or add meta tags: your frontend does.', close: true, w: 720, top: 40, z: 60, cancel: 'Close' }, D('display:flex;flex-direction:column;gap:12px', x.draft && D('display:flex;gap:8px;padding:10px 12px;background:var(--rc-info-soft);color:var(--ui-info)', I('info', 14, 'margin-top:3px'), S('color:var(--ui-text-toned)', 'This article is a draft. The API returns this data only to signed-in callers until it is published.')), bar, body))
|
||||
}
|
||||
// ---------- compose
|
||||
const v = s.v
|
||||
if (v === 'sites') {
|
||||
Object.assign(shellBase, { nav: 'settings', crumbs: ['Settings', 'Sites'], mTitle: 'Sites', role: s.role }); shell = shellBase
|
||||
main = D('flex:1;min-width:0;min-height:0;display:flex;flex-direction:column;position:relative', sitesPage())
|
||||
if (s.panel) ov.push(siteForm())
|
||||
if (s.modal) ov.push(sitesModal())
|
||||
if (!s.menu && s.fab !== false && !(s.sites && ['loading', 'error'].includes(s.sites.state))) ov.push(fab('Add site'))
|
||||
} else if (v === 'authors') {
|
||||
Object.assign(shellBase, { nav: 'authors', crumbs: ['Authors'], mTitle: 'Authors', role: s.role }); shell = shellBase
|
||||
main = D('flex:1;min-width:0;min-height:0;display:flex;flex-direction:column;position:relative', authorsPage())
|
||||
if (s.panel) ov.push(s.panel.k === 'authorView' ? authorView() : authorForm())
|
||||
if (s.modal) ov.push(authorsModal())
|
||||
if (s.list !== 'empty' && s.list !== 'error' && s.list !== 'loading') ov.push(fab('Add author'))
|
||||
} else if (v === 'editor') {
|
||||
if (s.metaOpen) edMeta = metaUI()
|
||||
if (s.seo && s.seo.side) edSeo = SEOSIDE(s.seo.side)
|
||||
if (s.seo && s.seo.panel) ov.push(seoPanel())
|
||||
if (s.seo && s.seo.pick) ov.push(Picker({ title: 'Choose a cover image', desc: 'The cover for this article.', sel: 1, z: 70 }))
|
||||
if (s.seo && s.seo.api) ov.push(apiDialog())
|
||||
if (s.modal) ov.push(newAuthorModal())
|
||||
if (s.ann) ov.push(D('position:absolute;z-index:20;' + (m ? 'left:16px;right:16px;bottom:88px' : 'left:248px;bottom:20px'), Note(s.ann)))
|
||||
} else if (v === 'profile') {
|
||||
if (s.panel) ov.push(authorForm())
|
||||
}
|
||||
if (s.toasts) ov.push(Toasts())
|
||||
return { shell, mob: m, main, ov: D('display:contents', ...ov), edMeta, edSeo }
|
||||
}
|
||||
}
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -75,7 +75,7 @@
|
||||
<sc-if value="{{ ep.noFields }}"><span style="color:var(--ui-text-muted)">No request body.</span></sc-if></div>
|
||||
<dc-import name="CodeSnippet" tabs="{{ ep.snips }}" hint-size="100%,200px"></dc-import>
|
||||
<div style="display:flex;flex-direction:column;gap:6px"><span style="font-weight:600;color:var(--ui-text-highlighted)">Errors</span>
|
||||
<sc-for list="{{ ep.errs }}" as="e" hint-placeholder-count="2"><div title="{{ e.cap }}" style="display:flex;align-items:baseline;gap:10px"><span style="width:36px;height:20px;flex-shrink:0;display:inline-flex;align-items:center;justify-content:center;border:1px solid var(--ui-border-accented);color:var(--ui-text-toned);font:500 11px 'IBM Plex Mono',monospace">{{ e.c }}</span><span style="min-width:0;color:var(--ui-text-toned);text-wrap:pretty">{{ e.cap }}</span></div></sc-for></div>
|
||||
<sc-for list="{{ ep.errs }}" as="e" hint-placeholder-count="2"><div title="{{ e.cap }}" style="display:flex;align-items:baseline;gap:10px"><span style="width:36px;height:20px;flex-shrink:0;display:inline-flex;align-items:center;justify-content:center;border:1px solid var(--ui-border-accented);color:var(--ui-text-toned);font:500 11px 'IBM Plex Mono',monospace">{{ e.c }}</span><sc-if value="{{ e.plain }}"><span style="min-width:0;color:var(--ui-text-toned);text-wrap:pretty">{{ e.cap }}</span></sc-if><sc-if value="{{ e.code }}"><span style="min-width:0;color:var(--ui-text-toned)"><code>{{ e.cap }}</code></span></sc-if></div></sc-for></div>
|
||||
</div>
|
||||
</sc-if>
|
||||
</div>
|
||||
@@ -104,7 +104,7 @@
|
||||
<span style="color:var(--ui-text-toned);text-wrap:pretty">Every error is a plain-text body with a single sentence. The status code is in the HTTP status line, and the Content-Type is text/plain.</span>
|
||||
<div style="border:1px solid var(--ui-border);background:var(--ui-bg);overflow:hidden">
|
||||
<div style="display:grid;grid-template-columns:{{ errCols }};gap:12px;padding:8px 12px;background:var(--ui-bg-elevated);color:var(--ui-text-muted);font-weight:500"><span>Status</span><span>Meaning</span><sc-if value="{{ desk }}"><span>Typical cause</span></sc-if></div>
|
||||
<sc-for list="{{ errRows }}" as="r" hint-placeholder-count="8"><div style="display:grid;grid-template-columns:{{ errCols }};gap:2px 12px;padding:10px 12px;border-top:1px solid var(--ui-border)"><span style="font:500 13px 'IBM Plex Mono',monospace;color:var(--ui-text-highlighted)">{{ r.c }}</span><span style="font-weight:500;color:var(--ui-text-highlighted)">{{ r.m }}</span><span style="grid-column:{{ errCause }};color:var(--ui-text-toned);text-wrap:pretty">{{ r.w }}</span></div></sc-for>
|
||||
<sc-for list="{{ errRows }}" as="r" hint-placeholder-count="8"><div style="display:grid;grid-template-columns:{{ errCols }};gap:2px 12px;padding:10px 12px;border-top:1px solid var(--ui-border)"><span style="font:500 13px 'IBM Plex Mono',monospace;color:var(--ui-text-highlighted)">{{ r.c }}</span><span style="font-weight:500;color:var(--ui-text-highlighted)">{{ r.m }}</span><span style="grid-column:{{ errCause }};color:var(--ui-text-toned);text-wrap:pretty">{{ r.w }}</span><sc-if value="{{ r.n }}"><span style="grid-column:{{ errNoteCol }};color:var(--ui-text-muted);font-size:12px;line-height:18px;text-wrap:pretty">{{ r.n }}</span></sc-if></div></sc-for>
|
||||
</div>
|
||||
<dc-import name="CodeSnippet" tabs="{{ errSnips }}" hint-size="100%,120px"></dc-import>
|
||||
</section>
|
||||
@@ -134,7 +134,7 @@ class Component extends DCLogic {
|
||||
rootRef = React.createRef()
|
||||
BASE = 'https://cms.renew.example'
|
||||
KEY = 'rcms_Kf3x9QwL0aBc…'
|
||||
IDX = [['auth', 'Authentication'], ['articles', 'Articles'], ['media', 'Media'], ['images', 'Images and variants'], ['users', 'Users and invites'], ['settings', 'Settings'], ['session', 'Session only'], ['errors', 'Errors'], ['notes', 'Notes']]
|
||||
IDX = [['auth', 'Authentication'], ['articles', 'Articles'], ['seo', 'Search and sharing'], ['media', 'Media'], ['images', 'Images and variants'], ['users', 'Users and invites'], ['settings', 'Settings'], ['session', 'Session only'], ['errors', 'Errors'], ['notes', 'Notes']]
|
||||
componentDidMount() {
|
||||
const i = (this.props.s && this.props.s.int) || {}
|
||||
const go = () => { if (i.scroll) this.scrollTo(i.scroll, !!this.props.mobile) }
|
||||
@@ -182,11 +182,15 @@ class Component extends DCLogic {
|
||||
A('art-list', 'GET', '/v1/article/', 'List articles, one page at a time. Anonymous callers get online articles only, and the total counts only those. The total is in the X-Total-Count response header; the body stays a JSON array.', 'Public', 1, [[400, 'Invalid page or size.'], e401], [S('page', 'integer', 'No', '1 or higher. Default 1. A page past the end returns an empty array.'), S('size', 'integer', 'No', 'One of 5, 25, 50 or 100. Default 25.')], { qp: 1, pub: 1, r: j([{ id: 12, title: 'How we price a bathroom renovation', status: 'online' }]) }),
|
||||
A('art-get', 'GET', '/v1/article/{id}', 'Get one article. Drafts answer 404 to anonymous callers.', 'Public', 1, [e401, e404], [], { pub: 1, r: j({ id: 12, title: 'How we price a bathroom renovation', status: 'online', body: 'A bathroom renovation is priced by room size, plumbing changes and finish level.', body_format: 'markdown' }) }),
|
||||
A('art-create', 'POST', '/v1/article/', 'Create a draft article.', 'Verified user', 1, [[400, mm], e401], [S('title', 'string', 'Yes', '3 to 200 characters. Can\'t be changed later.'), S('body', 'string', 'No', 'Optional. Any length.')], { body: { title: 'Choosing tiles for a small bathroom' }, r: j({ id: 13, status: 'draft' }) }),
|
||||
A('art-update', 'PATCH', '/v1/article/{id}', 'Update the body of an article.', 'Verified user', 1, [[400, mm], e401, e404], [S('body', 'string', 'Yes', 'Any length.')], { body: { body: 'Updated text.' }, r: j({ id: 12, status: 'draft' }) }),
|
||||
A('art-update', 'PATCH', '/v1/article/{id}', 'Update the body of an article.', 'Verified user', 1, [[400, mm], e401, e404], [S('body', 'string', 'No', 'Any length.'), S('slug', 'string', 'No', 'Lowercase letters, numbers and hyphens. Unique on the article\'s site. 409 slug_taken if used.'), S('excerpt', 'string', 'No', 'Up to 300 characters. Also the article teaser.'), S('seo_title', 'string', 'No', 'Up to 120 characters. Falls back to the article title.'), S('seo_description', 'string', 'No', 'Up to 320 characters. Falls back to the excerpt, then the first sentence of the body.'), S('cover_image_id', 'integer', 'No', 'A media item. Falls back to the site social image.'), S('cover_image_alt', 'string', 'No', 'Up to 200 characters.'), S('social_title', 'string', 'No', 'Open Graph and Twitter title. Falls back to the resolved title.'), S('social_description', 'string', 'No', 'Falls back to the resolved description.'), S('social_image_id', 'integer', 'No', 'Falls back to the cover image.'), S('canonical_url', 'string', 'No', 'An absolute https URL. Default is the site base URL plus the slug.'), S('noindex', 'boolean', 'No', 'Sets robots to noindex in the SEO object. It doesn\'t change who can read the article.'), S('seo_dismissed', 'string[]', 'No', 'Suggestion codes the editor dismissed. Used by the back-office only.')], { body: { slug: 'bathroom-costs', seo_title: 'What a bathroom renovation costs' }, r: j({ id: 12, status: 'draft', slug: 'bathroom-costs' }) }),
|
||||
A('art-pub', 'PATCH', '/v1/article/{id}/publish', 'Publish an article.', 'Verified user', 1, [e401, e404], [], { r: j({ id: 12, status: 'online' }) }),
|
||||
A('art-unpub', 'PATCH', '/v1/article/{id}/unpublish', 'Unpublish an article.', 'Verified user', 1, [e401, e404], [], { r: j({ id: 12, status: 'draft' }) }),
|
||||
A('art-del', 'DELETE', '/v1/article/{id}', 'Delete an article and its images.', 'Verified user', 1, [e401, e404], [], { r: '204 No Content' })
|
||||
] },
|
||||
seo: { title: 'Search and sharing', desc: 'RenewCMS doesn\'t render pages or add meta tags. These endpoints give your frontend the resolved SEO data and the list of published URLs.', eps: [
|
||||
A('seo-get', 'GET', '/v1/article/{id}/seo', 'The resolved SEO object for one article: title (with the site template applied), description, canonical URL, robots, Open Graph and Twitter values, image with alt, authors, dates and ready-made Article JSON-LD. Every empty field already holds its fallback. Drafts answer 404 to anonymous callers.', 'Public', 1, [e401, e404], [], { pub: 1, r: j({ title: 'How we price a bathroom renovation | Renew', description: 'A bathroom renovation is priced by room size, plumbing changes and finish level.', canonical_url: 'https://renew.example/how-we-price-a-bathroom-renovation', robots: 'index, follow', og: { type: 'article', title: 'How we price a bathroom renovation | Renew', image: 'https://renew.example/media/north-wall.jpg', image_alt: 'A tiled bathroom wall', site_name: 'Renew' }, twitter: { card: 'summary_large_image' }, authors: [{ name: 'Inès Duarte', url: 'https://ines-duarte.example', same_as: [] }], published_at: '2026-03-12T09:14:00Z', modified_at: '2026-10-15T11:02:00Z', json_ld: { '@type': 'Article' } }) }),
|
||||
A('sitemap', 'GET', '/v1/site/{key}/sitemap', 'Published article URLs for one site, each with its last-modified date and a noindex flag, one page at a time. Use it to build your sitemap.xml. The total is in the X-Total-Count response header.', 'Public', 1, [[400, mm], e401, [404, 'site_not_found', true]], [S('page', 'integer', 'No', '1 or higher. Default 1.'), S('size', 'integer', 'No', 'One of 25, 50, 100 or 500. Default 100.')], { qp: 1, pub: 1, r: j([{ url: 'https://renew.example/how-we-price-a-bathroom-renovation', modified_at: '2026-10-15T11:02:00Z', noindex: false }]) })
|
||||
] },
|
||||
media: { title: 'Media', desc: 'The image library. One image can be used in many articles.', eps: [
|
||||
A('med-list', 'GET', '/v1/media/', 'List images.', 'Verified user', 1, [e401], [], { r: j([{ id: 4, filename: 'north-wall.jpg', size: 3900000 }]) }),
|
||||
A('med-up', 'POST', '/v1/media/', 'Upload an image (multipart).', 'Verified user', 1, [[400, mm], e401, [413, 'The file is over 10 MB.'], [415, 'Not a PNG, JPEG, WEBP or SVG image.']], [S('file', 'file', 'Yes', 'PNG, JPEG, WEBP or SVG, up to 10 MB.')], { multi: true, form: [['file', '@north-wall.jpg']], r: j({ id: 4, filename: 'north-wall.jpg', url: '/static/uploadedImages/3f9c.jpg' }) }),
|
||||
@@ -235,7 +239,7 @@ class Component extends DCLogic {
|
||||
bodyTitle: e.qp ? 'Query parameters' : e.multi ? 'Request body · multipart/form-data, 1 file field' : e.body ? 'Request body · JSON' : 'Request body', hasFields: e.fields.length > 0, noFields: e.fields.length === 0, fields: e.fields,
|
||||
tabs: ['fetch', 'curl', 'Response'].map(t => { const k = t === 'Response' ? 'response' : t, on = (k === tab) || (t === tab); return { t, on, bd: on ? 'var(--ui-primary)' : 'transparent', fg: on ? 'var(--ui-text-highlighted)' : 'var(--ui-text-toned)', pick: () => this.setState(s => ({ tab: { ...s.tab, [e.id]: k } })) } }),
|
||||
snips: [{ k: 'fetch', label: 'fetch', code: fe }, { k: 'curl', label: 'curl', code: curl }, { k: 'response', label: 'Response', code: e.r }],
|
||||
errs: e.errs.map(([c, cap]) => ({ c, cap })) }
|
||||
errs: e.errs.map(([c, cap, code]) => ({ c, cap, code: !!code, plain: !code })) }
|
||||
}) }
|
||||
})
|
||||
}
|
||||
@@ -263,11 +267,11 @@ class Component extends DCLogic {
|
||||
fCols: mob ? 'minmax(0,1fr) auto auto' : '120px 72px 72px minmax(0,1fr)', ruleCol: mob ? '1 / -1' : 'auto',
|
||||
sessGroups: [sg('System · owner only', [['GET', '/v1/system/update', 'Update status'], ['POST', '/v1/system/update/check', 'Check for update'], ['POST', '/v1/system/update/download', 'Download update'], ['POST', '/v1/system/update/restart', 'Restart']]), sg('Sign in and account', [['POST', '/v1/auth/login', 'Log in'], ['POST', '/v1/auth/logout', 'Log out'], ['POST', '/v1/auth/register', 'Register'], ['POST', '/v1/auth/verify', 'Verify email'], ['POST', '/v1/auth/password-reset', 'Reset password']]), sg('API key management', [['GET', '/v1/api-key', 'List keys'], ['POST', '/v1/api-key', 'Create a key'], ['DELETE', '/v1/api-key/{id}', 'Revoke a key']])],
|
||||
sessCols: mob ? 'none' : '280px minmax(0,1fr) auto', sessGap: mob ? '2px' : '16px', sessPad: mob ? '8px 14px' : '0 14px', chipSelf: mob ? 'flex-start' : 'center',
|
||||
errCols: mob ? '56px minmax(0,1fr)' : '64px 200px minmax(0,1fr)', errCause: mob ? '2' : 'auto',
|
||||
errCols: mob ? '56px minmax(0,1fr)' : '64px 200px minmax(0,1fr)', errCause: mob ? '2' : 'auto', errNoteCol: mob ? '2' : '3',
|
||||
errRows: [
|
||||
{ c: 400, m: 'Bad request', w: '"The request cannot be processed due to a mismatch in the format of the body." or "The expiry must be a date in the future." Image requests answer with a JSON body whose error is "unknown_variant" or "unsupported_parameter".' },
|
||||
{ c: 401, m: 'Unauthorized', w: '"You must be logged in to access this resource." Sent for an invalid, unknown, expired or revoked key, even on public routes, and for a key whose user was deleted or unverified.' },
|
||||
{ c: 403, m: 'Forbidden', w: '"This action needs a real session." (a session-only route called with a key), "Only the owner can do this." or "You must verify your account to access this resource."' },
|
||||
{ c: 403, m: 'Forbidden', n: 'Site SEO defaults are owner only. Article SEO fields need only the right to edit the article.', w: '"This action needs a real session." (a session-only route called with a key), "Only the owner can do this." or "You must verify your account to access this resource."' },
|
||||
{ c: 404, m: 'Not found', w: '"Article not found", "Image not found", "Invite not found" or "API key not found". Drafts answer 404 to anonymous callers.' },
|
||||
{ c: 429, m: 'Too many requests', w: '"Too many requests. Please try again later." A per-key limit of 120 requests per minute also sends a Retry-After header.' },
|
||||
{ c: 500, m: 'Server error', w: '"Internal server error"' }
|
||||
|
||||
@@ -168,7 +168,7 @@ class Component extends DCLogic {
|
||||
out.push(D('display:flex;flex-direction:column;gap:12px;padding:4px 0 16px', D('display:flex;align-items:center;gap:12px;flex-wrap:wrap;justify-content:space-between', sum, Size()),
|
||||
g.pages > 1 && D('display:flex;align-items:center;gap:8px', S('flex:1;height:44px;display:flex;align-items:center;justify-content:center;gap:6px;border:1px solid var(--ui-border-accented);background:var(--ui-bg);color:var(--ui-text-highlighted);font-weight:500;opacity:' + back + ';' + ring('prev'), I('chevron-left'), 'Previous'), S('padding:0 4px;color:var(--ui-text-highlighted);font-weight:500;white-space:nowrap', 'Page ' + g.page + ' of ' + g.pages), S('flex:1;height:44px;display:flex;align-items:center;justify-content:center;gap:6px;border:1px solid var(--ui-border-accented);background:var(--ui-bg);color:var(--ui-text-highlighted);font-weight:500;opacity:' + fwd + ';' + ring('next'), 'Next', I('chevron-right')))))
|
||||
} else {
|
||||
out.push(D('display:flex;align-items:center;gap:16px', D('flex:1;display:flex;align-items:center;gap:16px', sum, Size()), g.pages > 1 && D('display:flex;align-items:center;gap:4px;justify-content:flex-end', PB('chevrons-left', back), PB('chevron-left', back, ring('prev')), ...nums, PB('chevron-right', fwd, ring('next')), PB('chevrons-right', fwd))))
|
||||
out.push(D('display:flex;align-items:center;gap:16px', D('flex:1;display:flex', sum), Size(), g.pages > 1 && D('display:flex;align-items:center;gap:4px;justify-content:flex-end', PB('chevrons-left', back), PB('chevron-left', back, ring('prev')), ...nums, PB('chevron-right', fwd, ring('next')), PB('chevrons-right', fwd))))
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
@@ -37,10 +37,10 @@
|
||||
<div style="display:flex;flex-wrap:wrap;gap:40px;align-items:flex-start">
|
||||
<sc-for list="{{ g.states }}" as="st" hint-placeholder-count="4">
|
||||
<div style="display:flex;flex-direction:column;gap:12px">
|
||||
<div style="display:flex;flex-direction:column;gap:2px;max-width:1040px"><span style="font:600 16px/24px 'IBM Plex Sans',sans-serif;color:var(--ui-text-highlighted)">{{ st.name }}</span><span style="font-size:13px;color:var(--ui-text-muted)">{{ st.trigger }}</span></div>
|
||||
<div style="display:flex;flex-direction:column;gap:2px;max-width:1040px"><span style="font:600 16px/24px 'IBM Plex Sans',sans-serif;color:var(--ui-text-highlighted)">{{ st.name }}<sc-if value="{{ st.clock }}"><span style="margin-left:10px;padding:1px 6px;border:1px dashed var(--ui-border-accented);color:var(--ui-text-toned);font:500 11px/16px 'IBM Plex Mono',monospace;vertical-align:middle">Clock-sensitive</span></sc-if></span><span style="font-size:13px;color:var(--ui-text-muted)">{{ st.trigger }}</span></div>
|
||||
<div style="display:flex;gap:24px;align-items:flex-start">
|
||||
<div style="width:720px;height:450px;overflow:hidden;border:1px solid var(--ui-border);flex-shrink:0"><div style="width:1440px;height:900px;zoom:0.5"><sc-if value="{{ st.notMedia }}"><dc-import name="AppFrame" s="{{ st }}" mobile="{{ false }}" hint-size="1440px,900px"></dc-import></sc-if><sc-if value="{{ st.isMedia }}"><dc-import name="MediaFrame" s="{{ st }}" mobile="{{ false }}" hint-size="1440px,900px"></dc-import></sc-if><sc-if value="{{ st.isAct }}"><dc-import name="ActivityFrame" s="{{ st }}" mobile="{{ false }}" hint-size="1440px,900px"></dc-import></sc-if><sc-if value="{{ st.isVar }}"><dc-import name="VariantsFrame" s="{{ st.vs }}" mobile="{{ false }}" hint-size="1440px,900px"></dc-import></sc-if><sc-if value="{{ st.isImg }}"><div style="width:1440px;height:900px;overflow:hidden;box-sizing:border-box;background:var(--ui-bg-muted);padding:40px 280px"><dc-import name="IntegrationImages" s="{{ st.img }}" mobile="{{ false }}" hint-size="880px,820px"></dc-import></div></sc-if></div></div>
|
||||
<div style="width:293px;height:633px;overflow:hidden;border:1px solid var(--ui-border);flex-shrink:0"><div style="width:390px;height:844px;zoom:0.75"><sc-if value="{{ st.notMedia }}"><dc-import name="AppFrame" s="{{ st.m }}" mobile="{{ true }}" hint-size="390px,844px"></dc-import></sc-if><sc-if value="{{ st.isMedia }}"><dc-import name="MediaFrame" s="{{ st.m }}" mobile="{{ true }}" hint-size="390px,844px"></dc-import></sc-if><sc-if value="{{ st.isAct }}"><dc-import name="ActivityFrame" s="{{ st.m }}" mobile="{{ true }}" hint-size="390px,844px"></dc-import></sc-if><sc-if value="{{ st.isVar }}"><dc-import name="VariantsFrame" s="{{ st.vm }}" mobile="{{ true }}" hint-size="390px,844px"></dc-import></sc-if><sc-if value="{{ st.isImg }}"><div style="width:390px;height:844px;overflow:hidden;box-sizing:border-box;background:var(--ui-bg-muted);padding:16px"><dc-import name="IntegrationImages" s="{{ st.img }}" mobile="{{ true }}" hint-size="358px,800px"></dc-import></div></sc-if></div></div>
|
||||
<div style="width:720px;height:450px;overflow:hidden;border:1px solid var(--ui-border);flex-shrink:0"><div style="width:1440px;height:900px;zoom:0.5"><sc-if value="{{ st.notMedia }}"><dc-import name="AppFrame" s="{{ st }}" mobile="{{ false }}" hint-size="1440px,900px"></dc-import></sc-if><sc-if value="{{ st.isMedia }}"><dc-import name="MediaFrame" s="{{ st }}" mobile="{{ false }}" hint-size="1440px,900px"></dc-import></sc-if><sc-if value="{{ st.isAct }}"><dc-import name="ActivityFrame" s="{{ st }}" mobile="{{ false }}" hint-size="1440px,900px"></dc-import></sc-if><sc-if value="{{ st.isDir }}"><dc-import name="DirectoryFrame" s="{{ st.m }}" mobile="{{ false }}" hint-size="390px,844px"></dc-import></sc-if><sc-if value="{{ st.isVar }}"><dc-import name="VariantsFrame" s="{{ st.vs }}" mobile="{{ false }}" hint-size="1440px,900px"></dc-import></sc-if><sc-if value="{{ st.isImg }}"><div style="width:1440px;height:900px;overflow:hidden;box-sizing:border-box;background:var(--ui-bg-muted);padding:40px 280px"><dc-import name="IntegrationImages" s="{{ st.img }}" mobile="{{ false }}" hint-size="880px,820px"></dc-import></div></sc-if></div></div>
|
||||
<div style="width:293px;height:633px;overflow:hidden;border:1px solid var(--ui-border);flex-shrink:0"><div style="width:390px;height:844px;zoom:0.75"><sc-if value="{{ st.notMedia }}"><dc-import name="AppFrame" s="{{ st.m }}" mobile="{{ true }}" hint-size="390px,844px"></dc-import></sc-if><sc-if value="{{ st.isMedia }}"><dc-import name="MediaFrame" s="{{ st.m }}" mobile="{{ true }}" hint-size="390px,844px"></dc-import></sc-if><sc-if value="{{ st.isAct }}"><dc-import name="ActivityFrame" s="{{ st.m }}" mobile="{{ true }}" hint-size="390px,844px"></dc-import></sc-if><sc-if value="{{ st.isDir }}"><dc-import name="DirectoryFrame" s="{{ st.m }}" mobile="{{ true }}" hint-size="390px,844px"></dc-import></sc-if><sc-if value="{{ st.isVar }}"><dc-import name="VariantsFrame" s="{{ st.vm }}" mobile="{{ true }}" hint-size="390px,844px"></dc-import></sc-if><sc-if value="{{ st.isImg }}"><div style="width:390px;height:844px;overflow:hidden;box-sizing:border-box;background:var(--ui-bg-muted);padding:16px"><dc-import name="IntegrationImages" s="{{ st.img }}" mobile="{{ true }}" hint-size="358px,800px"></dc-import></div></sc-if></div></div>
|
||||
</div>
|
||||
</div>
|
||||
</sc-for>
|
||||
@@ -53,6 +53,7 @@
|
||||
</sc-for>
|
||||
|
||||
<section data-screen-label="States matrix: controls" style="display:flex;flex-direction:column;gap:20px"><div style="display:flex;flex-direction:column;gap:6px;max-width:1100px"><h2 style="margin:0;font:600 28px/36px 'IBM Plex Sans',sans-serif;color:var(--ui-text-highlighted)">States matrix: controls</h2><p style="margin:4px 0 0;font-size:15px;line-height:24px;color:var(--ui-text-toned);text-wrap:pretty">Hover, focus-visible, active and disabled for every interactive element, once. Focus-visible is a 2 px --ui-primary outline with a 2 px offset (inset for tabs, segmented controls and rows). Disabled is 40% opacity (rows 55%). The mobile column set has no hover and uses 44 px targets. The theme switch above applies to both.</p></div><div style="display:flex;gap:40px;align-items:flex-start;flex-wrap:wrap"><dc-import name="StatesMatrix" mobile="{{ false }}" hint-size="1240px,2400px"></dc-import><dc-import name="StatesMatrix" mobile="{{ true }}" hint-size="390px,2400px"></dc-import></div></section>
|
||||
<section data-screen-label="Sites and authors: copy" style="display:flex;flex-direction:column;gap:20px;max-width:1240px"><h2 style="margin:0;font:600 28px/36px 'IBM Plex Sans',sans-serif;color:var(--ui-text-highlighted)">Sites and authors: copy per state</h2><div style="background:var(--ui-bg);border:1px solid var(--ui-border)"><sc-for list="{{ dirCopy }}" as="r" hint-placeholder-count="5"><div style="display:grid;grid-template-columns:300px minmax(0,1fr);gap:16px;padding:10px 12px;border-top:1px solid var(--ui-border);line-height:20px"><span style="font:500 13px 'IBM Plex Mono',monospace;color:var(--ui-text-highlighted)">{{ r.a }}</span><span style="color:var(--ui-text-highlighted);text-wrap:pretty">{{ r.b }}</span></div></sc-for></div></section>
|
||||
<section style="display:flex;flex-direction:column;gap:20px;max-width:1240px"><h2 style="margin:0;font:600 28px/36px 'IBM Plex Sans',sans-serif;color:var(--ui-text-highlighted)">Activity: copy per state</h2><div style="background:var(--ui-bg);border:1px solid var(--ui-border)"><sc-for list="{{ spCopy }}" as="r" hint-placeholder-count="5"><div style="display:grid;grid-template-columns:220px minmax(0,1fr);padding:10px 12px;border-top:1px solid var(--ui-border);line-height:20px"><span style="font:500 13px 'IBM Plex Mono',monospace;color:var(--ui-text-highlighted)">{{ r.a }}</span><span style="color:var(--ui-text-highlighted);text-wrap:pretty">{{ r.b }}</span></div></sc-for></div></section>
|
||||
<section style="display:flex;flex-direction:column;gap:20px;max-width:1240px"><h2 style="margin:0;font:600 28px/36px 'IBM Plex Sans',sans-serif;color:var(--ui-text-highlighted)">Activity: component inventory (Nuxt UI v4)</h2><div style="background:var(--ui-bg);border:1px solid var(--ui-border)"><sc-for list="{{ spComps }}" as="r" hint-placeholder-count="5"><div style="display:grid;grid-template-columns:220px minmax(0,1fr);padding:10px 12px;border-top:1px solid var(--ui-border);line-height:20px"><span style="font:500 13px 'IBM Plex Mono',monospace;color:var(--ui-text-highlighted)">{{ r.a }}</span><span style="color:var(--ui-text-highlighted);text-wrap:pretty">{{ r.b }}</span></div></sc-for></div></section>
|
||||
<section style="display:flex;flex-direction:column;gap:20px;max-width:1240px"><h2 style="margin:0;font:600 28px/36px 'IBM Plex Sans',sans-serif;color:var(--ui-text-highlighted)">Activity: API calls</h2><div style="background:var(--ui-bg);border:1px solid var(--ui-border)"><sc-for list="{{ spApi }}" as="r" hint-placeholder-count="5"><div style="display:grid;grid-template-columns:220px minmax(0,1fr);padding:10px 12px;border-top:1px solid var(--ui-border);line-height:20px"><span style="font:500 13px 'IBM Plex Mono',monospace;color:var(--ui-text-highlighted)">{{ r.a }}</span><span style="color:var(--ui-text-highlighted);text-wrap:pretty">{{ r.b }}</span></div></sc-for></div></section>
|
||||
@@ -94,18 +95,18 @@ class Component extends DCLogic {
|
||||
}
|
||||
boGroups() {
|
||||
const base = [
|
||||
{ t: 'How we price a bathroom renovation', on: true, c: '12 Mar 2026', u: '2 hours ago' },
|
||||
{ t: 'Choosing lime plaster for old stone walls', on: false, c: '9 Sep 2026', u: 'Yesterday' },
|
||||
{ t: 'Before and after: the Rue Verte kitchen', on: true, c: '28 Aug 2026', u: '3 days ago' },
|
||||
{ t: 'Winter checklist for timber windows', on: false, c: '2 Sep 2026', u: '5 days ago' },
|
||||
{ t: 'Why we reuse original floorboards', on: true, c: '14 Jun 2026', u: '18 Aug 2026' },
|
||||
{ t: 'Our first passive-house retrofit', on: true, c: '3 Apr 2026', u: '2 Jul 2026' }
|
||||
{ t: 'How we price a bathroom renovation', au: ['Inès Duarte'], on: true, c: '12 Mar 2026', u: '2 hours ago' },
|
||||
{ t: 'Choosing lime plaster for old stone walls', au: ['Inès Duarte', 'Camille Roche'], on: false, c: '9 Sep 2026', u: 'Yesterday', seo: 2 },
|
||||
{ t: 'Before and after: the Rue Verte kitchen', au: ['Jonas Pereira'], on: true, c: '28 Aug 2026', u: '3 days ago', seo: 'hidden' },
|
||||
{ t: 'Winter checklist for timber windows', au: ['Inès Duarte', 'Jonas Pereira', 'Camille Roche', 'Paul Huber', 'Léa Fontaine'], on: false, c: '2 Sep 2026', u: '5 days ago', seo: 3 },
|
||||
{ t: 'Why we reuse original floorboards', au: ['Paul Huber'], on: true, c: '14 Jun 2026', u: '18 Aug 2026' },
|
||||
{ t: 'Our first passive-house retrofit', au: [], on: true, c: '3 Apr 2026', u: '2 Jul 2026' }
|
||||
]
|
||||
const more = [
|
||||
{ t: 'Repointing a gable wall in lime mortar', on: true, c: '21 May 2026', u: '4 Jun 2026' },
|
||||
{ t: 'What a heat pump survey includes', on: false, c: '30 Jul 2026', u: '1 Aug 2026' },
|
||||
{ t: 'Choosing a damp-proof course', on: true, c: '7 Feb 2026', u: '19 Apr 2026' },
|
||||
{ t: 'Reglazing sash windows without replacing them', on: true, c: '16 Jan 2026', u: '2 Mar 2026' }
|
||||
{ t: 'Repointing a gable wall in lime mortar', au: ['Camille Roche'], on: true, c: '21 May 2026', u: '4 Jun 2026' },
|
||||
{ t: 'What a heat pump survey includes', au: ['Jonas Pereira'], on: false, c: '30 Jul 2026', u: '1 Aug 2026' },
|
||||
{ t: 'Choosing a damp-proof course', au: ['Inès Duarte'], on: true, c: '7 Feb 2026', u: '19 Apr 2026' },
|
||||
{ t: 'Reglazing sash windows without replacing them', au: ['Inès Duarte', 'Paul Huber'], on: true, c: '16 Jan 2026', u: '2 Mar 2026' }
|
||||
]
|
||||
const pgRows = n => [...base, ...more].slice(0, n).map(r => ({ ...r }))
|
||||
const PG = (g, o = {}) => { const rn = o.rows || 10; const { rows: _r, ...rest } = o; const { list: xl, ...ro } = rest; return L({ ...ro, list: { rows: pgRows(rn), pg: { per: 25, total: 312, pages: 13, ...g }, ...(xl || {}) } }) }
|
||||
@@ -197,7 +198,7 @@ class Component extends DCLogic {
|
||||
withM({ ...L({ list: { q: 'tiles', empty: { icon: 'search', title: 'No articles match "tiles"', text: 'Check the spelling, or search for a shorter part of the title.', action: 'Clear search' } } }), name: 'No results', trigger: 'Search matched nothing. The tab counts still show the full list.' }),
|
||||
withM({ ...L({ list: { tab: 2, counts: [4, 4, 0], empty: { icon: 'pencil-line', title: 'No drafts', text: 'Everything you\'ve written is online.', action: 'New article' } } }), name: 'No drafts', trigger: 'Drafts tab with nothing in it. The "Online" tab has an equivalent "Nothing is online yet" state.' }),
|
||||
withM({ ...L({ list: { rows: rows({ 3: { busy: 'Publishing…' } }) } }), name: 'Action in progress', trigger: 'Publish chosen from the row menu. That row is disabled.' }),
|
||||
withM({ ...L({ list: { rows: rows({ 3: { on: true, u: 'Just now' } }) }, toasts: [T('success', 'circle-check', 'Article published', '"Winter checklist for timber windows" is now online.')] }), name: 'Published', trigger: '200: the row updates in place and a toast confirms.' }),
|
||||
withM({ ...L({ list: { rows: rows({ 3: { on: true, u: 'Just now' } }) }, toasts: [T('success', 'circle-check', 'Article published', '"Winter checklist for timber windows" is now online.')] }), clock: true, name: 'Published', trigger: '200: the row updates in place and a toast confirms.' }),
|
||||
withM({ ...L({ toasts: [T('error', 'circle-x', 'Couldn\'t unpublish', 'The server didn\'t respond. Nothing changed.', 'Retry')] }), name: 'Action failed', trigger: 'A 500 or network error. The row stays as it was, and the toast stays until retried or dismissed.' }),
|
||||
withM({ ...L({ list: { counts: [5, 4, 1], rows: rows().filter((r, i) => i !== 1) }, toasts: [T('info', 'info', 'That article no longer exists', 'It was deleted somewhere else, so we removed it from the list.')] }), name: 'Row vanished (404)', trigger: 'Any row action gets a 404.' }),
|
||||
withM({ ...L({ modal: del(false) }), name: 'Delete: confirm', trigger: 'Delete… from the row menu.' }),
|
||||
@@ -309,7 +310,7 @@ class Component extends DCLogic {
|
||||
Mp({ upload: upT([rowOk('kitchen-roof.jpg', '2.2 MB', 2), { n: 'porch-steps.jpg', sz: '2.6 MB', st: 'prog', p: '1.1 of 2.6 MB', pct: '42%', im: 11 }, rowDup, rowRej, rowFail, { n: 'attic.jpg', sz: '1.9 MB', st: 'wait', im: 3 }]), name: 'Upload: several files, mixed', trigger: 'Upload button or drop, several files. Each file has its own row and progress. Files upload two at a time. A row can end as added, "Already in your library", rejected in the browser, or failed. Rejected and failed rows stay until dismissed.' }),
|
||||
Mp({ upload: upT([rowOk('kitchen-roof.jpg', '2.2 MB', 2), rowOk('porch-steps.jpg', '2.6 MB', 11), rowDup, rowRej, rowFail], { title: 'Upload finished', sub: '5 images', done: true, summary: '2 uploaded · 1 already in your library · 2 need attention' }), name: 'Upload: summary', trigger: 'All rows settled. The summary counts each outcome. "Use existing" selects the existing image and drops the row; "Upload anyway" stores a second copy, which then appears under Duplicates. "Try again" retries one file. Announced when it finishes.' }),
|
||||
Mp({ upload: upT([rowRej, { n: 'notes.pdf', sz: '210 KB', st: 'rej', title: 'notes.pdf isn\'t an image', msg: 'Images can be up to 10 MB. Use a PNG, JPEG, WEBP or SVG image.' }, { n: 'broken.png', sz: '3.0 MB', st: 'rej', title: 'broken.png couldn\'t be read', msg: 'The server couldn\'t read this image. Save it again as a PNG or JPEG, then try again.' }], { title: 'Nothing was uploaded', sub: '3 files were rejected', done: true }), name: 'Upload: rejected files (413, 400)', trigger: 'Type and size are checked in the browser first, so nothing is sent. A server 413 or 400 for a file that got through shows the same row with its own message.' }),
|
||||
Mp({ limited: true, name: 'Upload: too many requests (429)', trigger: 'Rate limited. Retry-After is counted down in the button. It re-enables at zero. Already-added files are kept.' }),
|
||||
Mp({ limited: true, clock: true, name: 'Upload: too many requests (429)', trigger: 'Rate limited. Retry-After is counted down in the button. It re-enables at zero. Already-added files are kept.' }),
|
||||
Mp({ tab: 'dups', name: 'Duplicates: groups', trigger: 'The Duplicates tab. Groups of identical images side by side, each with its uploader, upload date and "Used in N articles". The suggested copy to keep is the most used, then the oldest.' }),
|
||||
Mp({ tab: 'dups', modal: { k: 'purge' }, name: 'Purge duplicates: confirm', trigger: '"Purge duplicates" in the toolbar, next to the sort menu (in the stacked toolbar on mobile). Opens the same dialog as Settings; every other state is on the Media cleanup board.' }),
|
||||
Mp({ tab: 'dups', member: true, name: 'Duplicates: no purge button (member)', trigger: 'Verified users who are not owner or admin. The "Purge duplicates" button is hidden. "Merge into this one" is unchanged.' }),
|
||||
@@ -362,7 +363,7 @@ class Component extends DCLogic {
|
||||
withM({ kind: 'integration', nav: 'integration', crumbs: ['Integration'], mTitle: 'Integration', name: "3b. Copied: CodeBlock", trigger: "The Copy button in the API key example after a click. Back to \"Copy\" after 2 s.", int: {"scroll":"auth","copied":"auth"} }, { int: {"scroll":"auth","copied":"auth"} }),
|
||||
withM({ kind: 'integration', nav: 'integration', crumbs: ['Integration'], mTitle: 'Integration', name: "4. Authentication", trigger: "The API key card with its example, the \"Manage API keys\" link (goes to the API keys board) and the two notes.", int: {"scroll":"auth"} }, { int: {"scroll":"auth"} }),
|
||||
withM({ kind: 'integration', nav: 'integration', crumbs: ['Integration'], mTitle: 'Integration', name: "5. Session only", trigger: "Routes API keys cannot call. Dashed, muted and locked, so they read as unavailable and not as an error.", int: {"scroll":"session"} }, { int: {"scroll":"session"} }),
|
||||
withM({ kind: 'integration', nav: 'integration', crumbs: ['Integration'], mTitle: 'Integration', name: "6. Errors", trigger: "Status table and the plain-text error response (status line plus a one-sentence body). Key-specific causes are in the 401, 403 and 429 rows.", int: {"scroll":"errors"} }, { int: {"scroll":"errors"} }),
|
||||
withM({ kind: 'integration', nav: 'integration', crumbs: ['Integration'], mTitle: 'Integration', name: "6. Errors", trigger: "Status table and the plain-text error response (status line plus a one-sentence body). Key-specific causes are in the 401, 403 and 429 rows. The 403 row carries a muted note line (12/18, --ui-text-muted, aligned with the cause column, 2 px row gap above it): \"Site SEO defaults are owner only. Article SEO fields need only the right to edit the article.\" The 404 and 429 rows and everything below move down by the height of the wrapped note: two 18 px lines on desktop, three on mobile, plus the 2 px gap.", int: {"scroll":"errors"} }, { int: {"scroll":"errors"} }),
|
||||
withM({ kind: 'integration', nav: 'integration', crumbs: ['Integration'], mTitle: 'Integration', name: "7. Navigation", trigger: "Desktop: the sticky index with the active item (Media). Mobile: the \"Jump to\" select open. Keyboard: the index buttons and the select are in the tab order, Enter jumps, Escape closes the list.", int: {"scroll":"media"} }, { int: {"scroll":"media","jump":true} })
|
||||
] },
|
||||
{ label: 'Activity', title: 'Activity, owner and admin', route: '/activity', api: 'GET /v1/activity · GET /v1/activity/summary', note: 'New route in the sidebar after Users. Owner and admin see everything; regular users get "My activity". Copy, component mapping and API calls are at the bottom of this board.', states: [
|
||||
@@ -433,16 +434,16 @@ class Component extends DCLogic {
|
||||
withM({ ...U({ modal: { title: 'Cancel this invite?', desc: 'The link sent to sam.oliveira@renew.example will stop working. You can invite the address again later.', cancel: 'Keep invite', confirm: 'Cancel invite', tone: 'danger', notice: 'Couldn\'t cancel the invite. Try again in a moment.' } }), name: 'Cancel invite: failed', trigger: '500 or network failure. The dialog stays open.' }),
|
||||
withM({ ...U({ users: { rows: people.slice(1) }, toasts: [T('success', 'circle-check', 'Invite cancelled', 'sam.oliveira@renew.example can no longer use the link.')] }), name: 'Cancel invite: done', trigger: '204: the row disappears and a toast confirms.' }),
|
||||
withM({ ...U({ users: { rows: people.map(p => p.st === 'expired' ? { ...p, busy: 'Renewing…' } : p) } }), name: 'Renew invite: sending', trigger: '"Renew invite" on an Expired row. No confirmation, since it only sends an email. The button shows progress and is disabled.' }),
|
||||
withM({ ...U({ users: { rows: [{ ...people[1], st: 'pending', c: 'Today', hl: true }, ...people.filter((p, i) => i !== 1)] }, toasts: [T('success', 'circle-check', 'Invite renewed', 'p.huber@gmail.com has 3 days to accept the new link.')] }), name: 'Renew invite: done', trigger: '200: the row becomes Pending with today\'s date, moves to the top, and the old link stops working.' }),
|
||||
withM({ ...U({ users: { rows: [{ ...people[1], st: 'pending', c: 'Today', hl: true }, ...people.filter((p, i) => i !== 1)] }, toasts: [T('success', 'circle-check', 'Invite renewed', 'p.huber@gmail.com has 3 days to accept the new link.')] }), clock: true, name: 'Renew invite: done', trigger: '200: the row becomes Pending with today\'s date, moves to the top, and the old link stops working.' }),
|
||||
withM({ ...U({ toasts: [T('error', 'circle-x', 'Couldn\'t renew the invite', 'Try again in a moment.')] }), name: 'Renew invite: failed', trigger: '500 or network failure. The row stays Expired and the button can be pressed again.' }),
|
||||
withM({ ...U({ users: { rows: [{ email: 'lea.martin@renew.example', role: 'admin', st: 'pending', c: 'Today', hl: true }, ...people] } , toasts: [T('success', 'circle-check', 'Invite sent', 'lea.martin@renew.example has 3 days to accept.')] }), name: 'Invite sent', trigger: '201: the dialog closes, the new invite appears at the top as Pending, and a toast confirms.' })
|
||||
] },
|
||||
{ label: 'Settings', title: 'Settings: Updates', route: '/settings', api: 'GET /v1/system/update · POST …/check · POST …/download · POST …/update/restart (all pending)', note: 'The page is one column of cards, top to bottom: Version, Updates, Media cleanup, Retention (owner only). The screens below are scrolled to the card they show. New Updates card under Version, owner only. Update downloads and checks the new version and changes nothing. Restart installs it and restarts the site (about 10 seconds). "Restart later" is simply leaving the card or the dialog. A plain Restart shows only when no update is waiting. Admins see the version and a note. When the server isn\'t prepared, the card shows the notice and a "How to update" link with no buttons. Progress is a progressbar with a value, announced at 25% steps and when each step changes. The card is a polite live region. After the restart the page reloads, focus lands on the "Updates" heading, and a toast confirms. Buttons are disabled while any step runs, and any owner on any device sees the same state from the server. Cue elsewhere: see Home. Out of scope: choosing versions, downgrades, automatic updates, update history.', states: [
|
||||
SU({ icon: 'circle-check', tone: 'success', title: 'You\'re up to date', text: 'You have the latest version of RenewCMS.', meta: LAST, btns: [B('Check for updates', 'sec', 'refresh-cw'), B('Restart', 'sec', 'power')], hint: RESTART_FOOT }, { name: 'Up to date', trigger: 'Opened with no newer version. Restart is available but not emphasised.' }),
|
||||
SU({ icon: 'circle-check', tone: 'success', title: 'You\'re up to date', text: 'You have the latest version of RenewCMS.', meta: LAST, btns: [B('Check for updates', 'sec', 'refresh-cw'), B('Restart', 'sec', 'power')], hint: RESTART_FOOT }, { clock: true, name: 'Up to date', trigger: 'Opened with no newer version. Restart is available but not emphasised.' }),
|
||||
SU({ icon: 'loader-circle', title: 'Checking for updates…', text: 'This usually takes a few seconds.', btns: [B('Checking…', 'sec', 'loader-circle', true)] }, { name: 'Checking', trigger: 'Check for updates pressed, or the first open after 24 hours. Announced as "Checking for updates". Buttons are disabled.' }),
|
||||
SU({ icon: 'wifi-off', tone: 'warning', title: 'Couldn\'t check for updates', text: 'RenewCMS couldn\'t reach the update server. Check your connection and try again. Your site isn\'t affected.', meta: 'Last checked yesterday at 18:12', btns: [B('Try again', 'primary', 'rotate-cw'), B('Restart', 'sec', 'power')], hint: RESTART_FOOT }, { name: 'Check failed', trigger: 'Offline, or the update server didn\'t answer (500, network). The last known result is kept.' }),
|
||||
SU({ icon: 'circle-arrow-up', tone: 'info', title: 'Version 2.3.0 is available', text: 'You have v2.2.0-beta. Update downloads the new version and checks it. Nothing changes until you restart.', meta: LAST, notes: NOTES(false), btns: [B('Update', 'primary', 'download')], hint: 'Takes about 2 minutes. Your site stays online.' }, { name: 'Update available', trigger: 'A newer version exists. Release notes are collapsed. Update is the one primary button.', navBadge: true }),
|
||||
SU({ icon: 'circle-arrow-up', tone: 'info', title: 'Version 2.3.0 is available', text: 'You have v2.2.0-beta. Update downloads the new version and checks it. Nothing changes until you restart.', meta: LAST, notes: NOTES(true), btns: [B('Update', 'primary', 'download')], hint: 'Takes about 2 minutes. Your site stays online.' }, { name: 'Update available, notes open', trigger: '"What\'s new in 2.3.0" expanded. It is a button with aria-expanded, and the list is plain text.', navBadge: true }),
|
||||
SU({ icon: 'wifi-off', tone: 'warning', title: 'Couldn\'t check for updates', text: 'RenewCMS couldn\'t reach the update server. Check your connection and try again. Your site isn\'t affected.', meta: 'Last checked yesterday at 18:12', btns: [B('Try again', 'primary', 'rotate-cw'), B('Restart', 'sec', 'power')], hint: RESTART_FOOT }, { clock: true, name: 'Check failed', trigger: 'Offline, or the update server didn\'t answer (500, network). The last known result is kept.' }),
|
||||
SU({ icon: 'circle-arrow-up', tone: 'info', title: 'Version 2.3.0 is available', text: 'You have v2.2.0-beta. Update downloads the new version and checks it. Nothing changes until you restart.', meta: LAST, notes: NOTES(false), btns: [B('Update', 'primary', 'download')], hint: 'Takes about 2 minutes. Your site stays online.' }, { clock: true, name: 'Update available', trigger: 'A newer version exists. Release notes are collapsed. Update is the one primary button.', navBadge: true }),
|
||||
SU({ icon: 'circle-arrow-up', tone: 'info', title: 'Version 2.3.0 is available', text: 'You have v2.2.0-beta. Update downloads the new version and checks it. Nothing changes until you restart.', meta: LAST, notes: NOTES(true), btns: [B('Update', 'primary', 'download')], hint: 'Takes about 2 minutes. Your site stays online.' }, { clock: true, name: 'Update available, notes open', trigger: '"What\'s new in 2.3.0" expanded. It is a button with aria-expanded, and the list is plain text.', navBadge: true }),
|
||||
SU({ icon: 'download', tone: 'info', title: 'Downloading version 2.3.0…', text: 'You can leave this page. The download continues and your site stays online.', pct: 42, barLabel: 'Downloading version 2.3.0', barText: '42% · 11 of 26 MB', btns: [B('Updating…', 'sec', 'loader-circle', true)] }, { name: 'Downloading', trigger: 'Update pressed (202). Progress polls every second. Announced as "Downloading, 25 percent" and so on, never every tick.', navBadge: true }),
|
||||
SU({ icon: 'shield-check', tone: 'info', title: 'Checking the download…', text: 'Making sure the file is complete and safe to install. This takes a few seconds.', indet: true, barLabel: 'Checking the download', barText: 'Almost there', btns: [B('Updating…', 'sec', 'loader-circle', true)] }, { name: 'Verifying', trigger: 'The download finished. No percentage, so the bar is indeterminate. Announced as "Checking the download".', navBadge: true }),
|
||||
SU({ icon: 'circle-check', tone: 'success', title: 'Version 2.3.0 is ready to install', text: 'The download is checked. Restart to install it. Your site will be unavailable for about 10 seconds.', meta: 'Nothing has changed yet.', notes: NOTES(false), btns: [B('Restart', 'primary', 'power')], hint: 'Not now? Leave this page. The update waits here, and the banner on Home reminds you.' }, { name: 'Ready to install', trigger: 'The file passed its checks. Restart becomes the primary action. "Restart later" is closing the dialog or leaving the page.', navBadge: true }),
|
||||
@@ -450,19 +451,19 @@ class Component extends DCLogic {
|
||||
SU({ icon: 'circle-check', tone: 'success', title: 'Version 2.3.0 is ready to install', text: 'The download is checked. Restart to install it. Your site will be unavailable for about 10 seconds.', meta: 'Nothing has changed yet.', btns: [B('Restart', 'primary', 'power')] }, { name: 'Restart: request failed', trigger: '500 or network failure before the restart began. The site is still running.', navBadge: true, modal: installModal({ notice: 'Couldn\'t start the restart. Nothing was changed and your site is still running. Try again in a moment.' }) }),
|
||||
SU({ icon: 'circle-check', tone: 'success', title: 'Version 2.3.0 is ready to install', text: '', btns: [] }, { name: 'Restarting to install', trigger: 'Full-page overlay, so it survives the server going away. The page polls until the site answers, then reloads. It is a live region announced once as "Installing version 2.3.0. Your site is restarting."', overlay: { title: 'Installing version 2.3.0', text: 'Your site is restarting with the new version. This takes about 10 seconds. This page reloads on its own when the site is back.', meta: 'Started at 09:51', barL: '30%' } }),
|
||||
SU({ icon: 'circle-check', tone: 'success', title: '', text: '', btns: [] }, { name: 'Restarting, taking longer', trigger: 'No answer after 60 seconds. The copy changes and a manual reload appears. The overlay stays until the site is back.', overlay: { title: 'Still restarting', text: 'This is taking longer than usual. Keep this page open. It reloads on its own when the site is back, or you can reload it now.', meta: 'Started at 09:51 · 1 minute ago', btn: 'Reload page', barL: '65%' } }),
|
||||
SU({ icon: 'circle-check', tone: 'success', title: 'You\'re on version 2.3.0', text: 'The update is installed and your site is running again.', meta: 'Updated today at 09:52', btns: [B('Check for updates', 'sec', 'refresh-cw'), B('Restart', 'sec', 'power')], hint: RESTART_FOOT, link: 'Read the release notes', v: 'v2.3.0', focus: '2px solid var(--ui-primary)', toasts: undefined }, { name: 'Update done', trigger: 'The page reloaded on the new version. Focus lands on the "Updates" heading (ring shown), the toast is announced, and the version updates.', toasts: [T('success', 'circle-check', 'Update installed', 'RenewCMS is now on version 2.3.0.')] }),
|
||||
SU({ icon: 'circle-check', tone: 'success', title: 'You\'re on version 2.3.0', text: 'The update is installed and your site is running again.', meta: 'Updated today at 09:52', btns: [B('Check for updates', 'sec', 'refresh-cw'), B('Restart', 'sec', 'power')], hint: RESTART_FOOT, link: 'Read the release notes', v: 'v2.3.0', focus: '2px solid var(--ui-primary)', toasts: undefined }, { clock: true, name: 'Update done', trigger: 'The page reloaded on the new version. Focus lands on the "Updates" heading (ring shown), the toast is announced, and the version updates.', toasts: [T('success', 'circle-check', 'Update installed', 'RenewCMS is now on version 2.3.0.')] }),
|
||||
SU({ icon: 'triangle-alert', tone: 'warning', title: 'The update didn\'t install', text: 'RenewCMS put the previous version back, so your site is running as before. Nothing was lost.', meta: 'What to do next: try again in a few minutes. If it fails again, ask whoever manages your server to check the update.', btns: [B('Try again', 'primary', 'rotate-cw')] }, { name: 'Update failed, rolled back', trigger: 'The site came back on v2.2.0-beta. The error toast stays until dismissed and the card keeps the explanation.', toasts: [T('error', 'circle-x', 'The update didn\'t install', 'Your site is back on v2.2.0-beta.')] }),
|
||||
SU({ icon: 'circle-x', tone: 'error', title: 'The download didn\'t finish', text: 'The connection dropped before the file was complete. Nothing was changed and your site is running as before.', btns: [B('Try again', 'primary', 'rotate-cw')] }, { name: 'Download failed', trigger: 'A 500, or the connection dropped. Focus moves to the card heading. Try again restarts the download.', navBadge: true }),
|
||||
SU({ icon: 'triangle-alert', tone: 'warning', title: 'We didn\'t use this update', text: 'The file didn\'t pass our safety check, so it was not installed. Nothing was changed. Try downloading it again. If this keeps happening, contact RenewCMS support.', btns: [B('Try again', 'primary', 'rotate-cw')] }, { name: 'Verification failed', trigger: 'The downloaded file isn\'t trusted. The tone is a warning, and the file is thrown away. Technical detail goes to the server log, not the screen.', navBadge: true }),
|
||||
SU({ icon: 'info', tone: 'info', title: 'Too many tries', text: 'Wait a moment before trying again.', btns: [B('Try again in 0:42', 'sec', 'clock', true)] }, { name: 'Too many requests (429)', trigger: 'Retry-After counted down in the button. It re-enables at zero.' }),
|
||||
SU({ icon: 'info', tone: 'info', title: 'Too many tries', text: 'Wait a moment before trying again.', btns: [B('Try again in 0:42', 'sec', 'clock', true)] }, { clock: true, name: 'Too many requests (429)', trigger: 'Retry-After counted down in the button. It re-enables at zero.' }),
|
||||
SU(notPrep(false), { name: 'Not prepared', trigger: 'The server can\'t update from the browser. No buttons, not even Restart. The command is for the person who runs the server and is a single line. The placeholder command is subject to the real one.', navBadge: true }),
|
||||
SU(notPrep(true), { name: 'Not prepared: command copied', trigger: 'Copy pressed. The button reads "Copied" for 2 s and it is announced.', navBadge: true }),
|
||||
SU({ icon: 'circle-check', tone: 'success', title: 'You\'re up to date', text: 'You have the latest version of RenewCMS.', meta: LAST, btns: [B('Check for updates', 'sec', 'refresh-cw'), B('Restart', 'sec', 'power')], hint: RESTART_FOOT }, { name: 'Plain restart: confirm', trigger: 'Restart with no update waiting. Nothing is installed.', modal: restartModal() }),
|
||||
SU({ icon: 'circle-check', tone: 'success', title: 'You\'re up to date', text: 'You have the latest version of RenewCMS.', meta: LAST, btns: [B('Check for updates', 'sec', 'refresh-cw'), B('Restart', 'sec', 'power')], hint: RESTART_FOOT }, { clock: true, name: 'Plain restart: confirm', trigger: 'Restart with no update waiting. Nothing is installed.', modal: restartModal() }),
|
||||
SU({ icon: 'circle-check', tone: 'success', title: '', text: '', btns: [] }, { name: 'Plain restart: restarting', trigger: 'Same overlay as the update restart with shorter copy.', overlay: { title: 'Restarting your site', text: 'This takes about 10 seconds. This page reloads on its own when the site is back.', meta: 'Started at 09:51', barL: '30%' } }),
|
||||
SU({ icon: 'circle-check', tone: 'success', title: 'Your site is back', text: '', btns: [] }, { name: 'Plain restart: done', trigger: 'The page reloaded. Focus lands on the "Updates" heading.', toasts: [T('success', 'circle-check', 'Site restarted', 'Your site is running again.')] }),
|
||||
SU({ icon: 'circle-arrow-up', tone: 'info', title: 'Version 2.3.0 is available', text: 'You have v2.2.0-beta. Only the owner can update RenewCMS. Ask the owner of this site.', meta: LAST }, { noRet: true, name: 'Admin view', trigger: 'Admins see the version and the note, with no buttons. Up to date: "You\'re up to date" and "Only the owner can update or restart the site." No Home banner or Settings pill.' }),
|
||||
SU({ icon: 'circle-arrow-up', tone: 'info', title: 'Version 2.3.0 is available', text: 'You have v2.2.0-beta. Only the owner can update RenewCMS. Ask the owner of this site.', meta: LAST }, { noRet: true, name: 'Role changed (403)', trigger: 'An owner was changed to admin while the page was open and pressed a button. The card reloads in the admin view.', toasts: [T('error', 'circle-x', 'Only the owner can do this', 'Ask the owner of this site to update RenewCMS.')] }),
|
||||
SU({ icon: 'circle-arrow-up', tone: 'info', title: 'Version 2.3.0 is available', text: 'You have v2.2.0-beta. Update downloads the new version and checks it. Nothing changes until you restart.', meta: LAST, btns: [B('Update', 'primary', 'download', true)] }, { name: 'Update already running (409)', trigger: 'Another owner started it. The card switches to that run\'s progress.', navBadge: true, toasts: [T('info', 'info', 'An update is already running', 'Another owner started it. Progress shows here.')] })
|
||||
SU({ icon: 'circle-arrow-up', tone: 'info', title: 'Version 2.3.0 is available', text: 'You have v2.2.0-beta. Only the owner can update RenewCMS. Ask the owner of this site.', meta: LAST }, { noRet: true, clock: true, name: 'Admin view', trigger: 'Admins see the version and the note, with no buttons. Up to date: "You\'re up to date" and "Only the owner can update or restart the site." No Home banner or Settings pill.' }),
|
||||
SU({ icon: 'circle-arrow-up', tone: 'info', title: 'Version 2.3.0 is available', text: 'You have v2.2.0-beta. Only the owner can update RenewCMS. Ask the owner of this site.', meta: LAST }, { noRet: true, clock: true, name: 'Role changed (403)', trigger: 'An owner was changed to admin while the page was open and pressed a button. The card reloads in the admin view.', toasts: [T('error', 'circle-x', 'Only the owner can do this', 'Ask the owner of this site to update RenewCMS.')] }),
|
||||
SU({ icon: 'circle-arrow-up', tone: 'info', title: 'Version 2.3.0 is available', text: 'You have v2.2.0-beta. Update downloads the new version and checks it. Nothing changes until you restart.', meta: LAST, btns: [B('Update', 'primary', 'download', true)] }, { clock: true, name: 'Update already running (409)', trigger: 'Another owner started it. The card switches to that run\'s progress.', navBadge: true, toasts: [T('info', 'info', 'An update is already running', 'Another owner started it. Progress shows here.')] })
|
||||
], tableTitle: 'Status to copy', table: [
|
||||
{ a: '200', b: 'Check, up to date', c: '"You\'re up to date" / "You have the latest version of RenewCMS." / "Last checked today at 09:41"' },
|
||||
{ a: '200', b: 'Check, newer version', c: '"Version 2.3.0 is available" / "You have v2.2.0-beta. Update downloads the new version and checks it. Nothing changes until you restart."' },
|
||||
@@ -580,7 +581,7 @@ class Component extends DCLogic {
|
||||
im('I8', 'Snippet copied', 'Copy pressed on the snippet. The label reads Copied for 2 s and is announced politely.', { v: 'many', tab: 'js', copied: true }),
|
||||
im('I9', 'URL builder copied', 'Copy pressed on the built URL.', { v: 'many', variant: 'card', urlCopied: true })
|
||||
] }
|
||||
return [...bo, imgG, navG, ...vg.map(adapt)]
|
||||
return [...bo, ...this.dirGroups(bo), imgG, navG, ...vg.map(adapt)]
|
||||
}
|
||||
cell(t, i, o = {}) { return { t, fg: i === 0 && !o.plain ? 'var(--ui-text-highlighted)' : o.muted ? 'var(--ui-text-muted)' : 'var(--ui-text-toned)', fw: i === 0 && !o.plain ? 500 : 400, ff: o.mono ? "'IBM Plex Mono',monospace" : "'IBM Plex Sans',sans-serif", fs: o.mono ? '12px' : '13px' } }
|
||||
tbl(title, cols, tpl, rows, o = {}) { return { title, cols, tpl, rows: rows.map(r => r.map((t, i) => this.cell(t, i, { mono: o.mono && o.mono.includes(i), muted: t === '–' }))) } }
|
||||
@@ -831,6 +832,281 @@ class Component extends DCLogic {
|
||||
{ label: 'Vocabulary and accessibility', title: 'Vocabulary and accessibility', note: 'Use "variant", "generated" and "purge" everywhere. Never "thumbnail preset", "version" or "rendition". Delete removes a variant definition; purge removes only its generated files. Every status is an icon plus text: Generated (circle-check), Not generated (circle-dashed), Generating (loader), Failed (circle-x), Enabled (circle-check), Disabled (circle-off). The comparison slider has a visible focus ring and works from the keyboard. Dialogs trap focus and return it to the opener. Progress is announced with aria-live="polite". Touch targets on mobile are at least 44 px. The only token not already in the system is --rc-on-sand (dark ink on the sand selection color), used for the active nav item in both themes.', tables: [] }
|
||||
]
|
||||
}
|
||||
// DIR-START
|
||||
dirDoc() {
|
||||
const S = (name, trigger, copy, o, mo) => ({ name, trigger, copy, o, mo })
|
||||
const G = (label, title, route, api, note, states) => ({ label, title, route, api, note, states })
|
||||
const edT = 'How we price a bathroom renovation'
|
||||
const fmtP = n => String(n).replace(/\B(?=(\d{3})+(?!\d))/g, ',')
|
||||
const PGS = (v, cfg) => {
|
||||
const { path, noun, N, mid, qN, qText, big, bigPage, single, empty } = cfg, pages = Math.ceil(N / 25)
|
||||
const o = (pg, x = {}) => v === 'sites' ? { v, sites: { state: 'ok' }, pg, ...x } : { v, pg, ...x }
|
||||
const rng = p => 'Showing ' + ((p - 1) * 25 + 1) + '–' + Math.min(p * 25, N) + ' of ' + fmtP(N)
|
||||
const bp = Math.ceil(big / 25), bm = bigPage
|
||||
return [
|
||||
S('First page', path + '. Previous and First are disabled. Mobile: Previous is disabled.', rng(1) + ' · 25 per page · Page 1 of ' + pages + ' · Previous · Next', o({ page: 1, per: 25, total: N })),
|
||||
S('Middle page', path + '?page=' + mid + '. Current page uses --rc-sand and --rc-on-sand.', rng(mid) + ' · Page ' + mid + ' of ' + pages, o({ page: mid, per: 25, total: N })),
|
||||
S('Last page', path + '?page=' + pages + '. Next and Last are disabled.', rng(pages) + ' · Page ' + pages + ' of ' + pages, o({ page: pages, per: 25, total: N })),
|
||||
S('Single page', 'Everything fits on one page. The pager and the page-size select are hidden; only the count remains.', single + ' ' + noun + (single === 1 ? '' : 's'), o({ page: 1, per: 25, total: single })),
|
||||
S('Page size menu', 'The select opens upward: 5, 25, 50 or 100 per page. 25 is the default. Choosing another size sets ?size= and returns to page 1.', '5 per page · 25 per page · 50 per page · 100 per page', o({ page: mid, per: 25, total: N, sizeOpen: true })),
|
||||
S('Loading a page', 'Next was pressed. The rows are replaced by skeleton rows; the pager stays, disabled, and the summary reads "Loading page ' + (mid + 1) + '…".', 'Loading page ' + (mid + 1) + '…', o({ page: mid, per: 25, total: N, loading: mid + 1 })),
|
||||
S('Error loading a page', '500 or network failure on a page change. The current rows and the current page number stay; Retry sits in the notice.', 'Couldn\'t load page ' + (mid + 1) + '. Showing page ' + mid + '. · Check your connection and try again. · Retry', o({ page: mid, per: 25, total: N, err: 'Couldn\'t load page ' + (mid + 1) + '. Showing page ' + mid + '.' })),
|
||||
S('Empty after search', 'A search matched nothing. The empty state replaces the list and the pager is hidden.', 'No ' + noun + 's match "' + empty + '" · Check the spelling, or search for a shorter part of the name. · Clear search', o({ empty: true, total: 0 }, { q: empty })),
|
||||
S('Search resets to page 1', 'Searching "' + qText + '" from page ' + (mid + 2) + ' goes to ' + path + '?q=' + qText + ' (page omitted). Changing the page size does the same.', rng(1).replace(' of ' + fmtP(N), ' of ' + qN), o({ page: 1, per: 25, total: qN }, { q: qText })),
|
||||
S('Long labels on mobile', 'Large totals on a 390 px screen. The summary and the page-size select wrap onto two lines if needed; Previous, "Page ' + bm + ' of ' + bp + '" and Next keep one row.', 'Showing ' + ((bm - 1) * 25 + 1) + '–' + (bm * 25) + ' of ' + fmtP(big) + ' · Page ' + bm + ' of ' + bp, o({ page: bm, per: 25, total: big }))
|
||||
]
|
||||
}
|
||||
const sitesNote = 'Settings, Publishing group. Compact list; actions in the row menu. Default site: no delete action.'
|
||||
return { groups: [
|
||||
G('Sites', 'Sites', '/settings/sites', 'GET /v1/site/ · PATCH /v1/site/{id}/default · DELETE /v1/site/{id}?reassign_to={id}', 'Only the owner can create, edit, set the default or delete a site. Other roles don\'t see the Sites entry under Settings; a direct link shows a 403 page. Choosing a site for an article is not site management: anyone who can edit the article can set its site in the editor and read the site list. New child of Settings, under a "Publishing" heading in the sidebar (Settings also gets a "Publishing" card with a "Manage sites" row, owner only). Columns: name with key, base URL, article count. The default site carries a "Default" badge and has no delete action. A site with robots set to noindex shows a "Noindex" badge. List, row menu and dialogs come from DirectoryFrame and are shared with Authors.', [
|
||||
S('Default', 'The list loaded. Four sites, Renew is the default. Owner only.', 'Sites · The frontends that display your content. · Add site · Site · Base URL · Articles · Default · Noindex · 268 articles · 38 articles · 6 articles · No articles', { v: 'sites', sites: { state: 'ok' } }),
|
||||
S('Only the default site', 'First run: the seeded site only. A hint under the list, no empty-state wall.', 'Add another site if your content is shown on more than one frontend. Each article belongs to one site.', { v: 'sites', sites: { state: 'ok', only: true } }),
|
||||
S('Loading', 'The first load, or a retry. Skeleton rows appear after 150 ms.', '', { v: 'sites', sites: { state: 'loading' } }),
|
||||
S('Error', 'A 500 or network failure on the list request.', 'Couldn\'t load sites · Check your connection and try again. · Try again', { v: 'sites', sites: { state: 'error' } }),
|
||||
S('Row menu', 'The ellipsis button, or Enter on the focused menu button. Mobile: bottom sheet titled with the site name.', 'Edit · Set as default · Delete…', { v: 'sites', sites: { state: 'ok', menu: 1 } }),
|
||||
S('Default site: delete unavailable', 'Menu on the default site. "Delete…" is aria-disabled, stays focusable and explains itself: tooltip on desktop, text in the sheet on touch.', 'The default site can\'t be deleted. Make another site the default first.', { v: 'sites', sites: { state: 'ok', menu: 0 }, tip: true }),
|
||||
S('Set as default: confirm', '"Set as default" in the row menu. On 200 the badge moves and a toast confirms. The button reads "Saving…" while the request runs.', 'Make Journal the default site? · New articles start on this site. Articles that are already on other sites stay where they are. · Cancel · Make default · Default site changed · "Journal" is now the default site.', { v: 'sites', sites: { state: 'ok' }, modal: { k: 'setdef', i: 1 } }),
|
||||
S('Hidden entry (admin)', 'An admin opens Settings. The sidebar has no Publishing group and no Sites entry, and the page has no Publishing card. Roles without Settings have nothing to hide.', 'No Publishing group · No Sites entry · No "Manage sites" row', { v: 'adminSettings' }),
|
||||
S('Forbidden (403)', 'A role other than owner opens /settings/sites from a bookmark or a link. The sidebar has no Sites entry, so the page explains instead of redirecting. The API answers 403.', 'You don\'t have access to Sites · Only the owner can manage sites. Ask the owner of this site if you need a change. · Back to Settings', { v: 'sites', forbidden: true, role: 'admin', fab: false })
|
||||
]),
|
||||
G('Sites: form', 'Sites: add and edit', 'slide-over (desktop) · 92% bottom sheet (mobile)', 'POST /v1/site/ · PATCH /v1/site/{id}', 'Owner only. A slide-over, because the form has a live preview (the canonical URL). Fields: name, key, base URL, default social image (media picker), default robots policy, optional locale, default switch. The key is set when the site is added and can\'t be edited afterwards: the edit form shows it read-only with a lock and the text "Used in API paths, so it can\'t change." Closing with changes asks "Discard changes?" with the existing discard dialog. The slug field, media field and picker are the shared ones from DirectoryFrame (the picker is drawn once, in Authors: form). Locale error: "Use a language tag like en or fr-CH."', [
|
||||
S('Add: empty', '"Add site" in the page header, or the bottom button on mobile.', 'Add site · Name · e.g. Journal · Key · Generated from the name · Base URL · https://blog.example.com · The public address of the frontend. Use https and no path. · Default social image (optional) · Choose image · Used when an article has no image of its own. · Default robots policy · Index · Noindex · Search engines may list this site\'s pages. · Locale (optional) · e.g. en or fr-CH · A language tag. Leave empty if the site has no single language. · Make this the default site · New articles start here. The current default is Renew. · Canonical URL preview · Cancel · Add site', { v: 'sites', sites: { state: 'ok' }, panel: { k: 'site', mode: 'add', focus: 'name' } }),
|
||||
S('Add: key from the name', 'Typing a name fills the key. The pencil unlocks it until the site is added.', 'journal · Auto · Lowercase letters, numbers and hyphens. Used in API paths. It can\'t be changed after the site is added.', { v: 'sites', sites: { state: 'ok' }, panel: { k: 'site', mode: 'add', focus: 'url', f: { name: 'Journal', key: 'journal', keyMode: 'auto' } } }),
|
||||
S('Add: URL not valid', 'On blur or submit. Nothing is sent. A URL with a path and text that is not a URL get their own messages, drawn the same way.', 'Use https. For example https://blog.example.com. · Remove the path. Use only the host, like https://blog.example.com. · Enter a full URL, like https://blog.example.com.', { v: 'sites', sites: { state: 'ok' }, panel: { k: 'site', mode: 'add', f: { name: 'Journal', key: 'journal', keyMode: 'auto', url: 'http://journal.renew.example' }, err: { url: 'Use https. For example https://blog.example.com.' } } }),
|
||||
S('Add: duplicate key', '409 on submit, or on blur after a check.', 'A site with the key "journal" already exists. Choose another key. · Use journal-2', { v: 'sites', sites: { state: 'ok' }, panel: { k: 'site', mode: 'add', f: { name: 'Journal', key: 'journal', keyMode: 'manual', url: 'https://journal2.renew.example' }, err: { key: 'A site with the key "journal" already exists. Choose another key.', keySuggest: 'journal-2' } } }),
|
||||
S('Add: save failed', '500 or network failure. The values stay.', 'Couldn\'t save the site. Your changes are still here. Try again in a moment.', { v: 'sites', sites: { state: 'ok' }, panel: { k: 'site', mode: 'add', notice: 'Couldn\'t save the site. Your changes are still here. Try again in a moment.', f: { name: 'Journal', key: 'journal', keyMode: 'auto', url: 'https://journal.renew.example' } } }),
|
||||
S('Edit: default site', 'Edit on the default site. The key is read-only with a lock, because it is used in API paths. The switch is on and locked.', 'Edit Renew · Key · renew · Used in API paths, so it can\'t change. · Default site · New articles start on the default site. To change it, make another site the default. · Save changes', { v: 'sites', sites: { state: 'ok' }, panel: { k: 'site', mode: 'edit', i: 0, f: { name: 'Renew', key: 'renew', keyMode: 'saved', url: 'https://renew.example', img: 'north-wall.jpg', loc: 'en' } } }),
|
||||
S('Edit: other site, noindex', 'Edit on a non-default site.', 'Edit Projects · Key · projects · Used in API paths, so it can\'t change. · Noindex · Asks search engines not to list this site\'s pages. · Make this the default site', { v: 'sites', sites: { state: 'ok' }, panel: { k: 'site', mode: 'edit', i: 2, f: { name: 'Projects', key: 'projects', keyMode: 'saved', url: 'https://projects.renew.example', img: 'kitchen-after.webp', robots: 'Noindex', loc: 'fr' } } })
|
||||
]),
|
||||
G('Sites: delete', 'Sites: delete', 'dialog (desktop) · bottom sheet (mobile)', 'DELETE /v1/site/{id}?reassign_to={id}', 'Owner only. A site with articles cannot be deleted without a destination: the dialog has a select and shows how many articles move. Destination defaults to the default site. Without reassign_to the server answers 409. This is the shared ReassignDialog from DirectoryFrame; its failed state is drawn once, in Authors: delete.', [
|
||||
S('With articles', '"Delete…" on a site that has articles. The button reads "Moving articles…" while the request runs. On 204 the row leaves the list and a toast reads "Site deleted" · "38 articles moved to Renew."', 'Delete this site? · "Journal" will be deleted. 38 articles belong to it, so choose a site to move them to. This can\'t be undone. · Move articles to · Renew · renew.example · 38 articles will move to Renew. Their canonical host changes to renew.example. · Cancel · Move 38 articles and delete', { v: 'sites', sites: { state: 'ok' }, modal: { k: 'del', i: 1 } }),
|
||||
S('Choose destination', 'The select is open. The site being deleted is not listed.', 'Journal is not offered. Options show name and host.', { v: 'sites', sites: { state: 'ok' }, modal: { k: 'del', i: 1, open: true } }),
|
||||
S('No articles', 'A site with zero articles: plain confirm, no select.', 'Delete this site? · "Archive" will be deleted. No articles belong to it. This can\'t be undone. · Delete site', { v: 'sites', sites: { state: 'ok' }, modal: { k: 'del0', i: 3 } })
|
||||
]),
|
||||
G('Sites: pagination', 'Sites: pagination', '/settings/sites?page=2&size=50', 'GET /v1/site/?q=&page=&size= (total in the X-Total-Count header; array body unchanged)', 'Same Paginator as Articles and Media (components.md). Sizes 5, 25, 50, 100, default 25: the existing pattern, unchanged. Page and size in the URL as page and size; defaults omitted; a page past the end falls back to the last page. Search resets to page 1. The count line "N sites" replaces the pager on a single page. Sites has no search box today: it is added with the pager (same field as Authors, "Search by name or key") and is a proposal to confirm. The list is drawn with generated rows; 61 sites give 3 pages.', PGS('sites', { path: '/settings/sites', noun: 'site', N: 61, mid: 2, qN: 27, qText: 'renew', big: 312, bigPage: 6, single: 4, empty: 'blog' })),
|
||||
G('Authors', 'Authors', '/authors', 'GET /v1/author/?q=&page=&size= · DELETE /v1/author/{id}?reassign_to={id|none}', 'Sidebar entry between Media and Users, visible to every role. Owner and admin create, edit and delete any author. Other roles see the list and the detail read-only. Columns: avatar and name, slug, account (Linked or Guest), article count. Search by name or slug. Long names truncate in the row and show in full on hover. Above 25 authors the list uses the same paginator as Articles (not redrawn). List, panel and dialogs come from DirectoryFrame and are shared with Sites.', [
|
||||
S('Default', 'Owner or admin. The list loaded, newest first.', 'Authors · The names readers see on your articles. An author doesn\'t need an account. · Add author · Search by name or slug · Author · Slug · Account · Articles · Linked · Guest · 9 articles · 1 article · No articles', { v: 'authors' }),
|
||||
S('Loading', 'The first load, or a retry.', '', { v: 'authors', list: 'loading' }),
|
||||
S('Error', '500 or network failure.', 'Couldn\'t load authors · Check your connection and try again. · Try again', { v: 'authors', list: 'error' }),
|
||||
S('Empty, first run', 'Zero authors. Toolbar hidden, one call to action. Other roles see the same text without the button.', 'No authors yet · Authors are the names readers see on articles. They don\'t need an account. · Add author', { v: 'authors', list: 'empty' }),
|
||||
S('No results', 'Search matched nothing.', 'No authors match "zoe" · Check the spelling, or search for a shorter part of the name. · Clear search', { v: 'authors', q: 'zoe' }),
|
||||
S('Row menu', 'Owner or admin. The ellipsis button. Mobile: bottom sheet.', 'Edit · Delete…', { v: 'authors', menu: 2 }),
|
||||
S('Read-only list (other roles)', 'Any role except owner and admin. No Add author button, no row menu and no bottom button on mobile. Search still works. A row opens the read-only detail.', 'Authors · The names readers see on your articles. Only an owner or admin can change authors. · Search by name or slug · Author · Slug · Account · Articles', { v: 'authors', ro: true, role: 'user' }),
|
||||
S('Read-only detail', 'A row was opened by a role without author rights. Same panel width as the form, no fields, Close as the only action. The account email is not shown.', 'Inès Duarte · Linked · 9 articles · Bio · Website · Only an owner or admin can change this author. · Close', { v: 'authors', ro: true, role: 'user', panel: { k: 'authorView', i: 0 } })
|
||||
]),
|
||||
G('Authors: form', 'Authors: add and edit', 'slide-over (desktop) · 92% bottom sheet (mobile)', 'POST /v1/author/ · PATCH /v1/author/{id}', 'Owner and admin. A slide-over, because the form has a live preview (the byline). Fields: avatar (media picker), name, slug (auto, editable), bio with counter, website, social links (X, LinkedIn, GitHub, Mastodon, Custom; up to 5), linked user (only users without an author). Slug field, media field and picker are the shared ones from DirectoryFrame. Saving shows "Saving…" in the button, as in the other forms.', [
|
||||
S('Add: empty', '"Add author". Owner or admin.', 'Add author · Avatar (optional) · Choose image · Name · e.g. Camille Roche · Slug · Generated from the name · Bio (optional) · A sentence or two about the author. · 0 / 280 · Website (optional) · https://example.com · Social links (optional) · Add link · 0 of 5 · Linked user (optional) · No linked user · Link a CMS user if this author has an account. Guest writers need no link. · Byline preview · Author name · The bio appears here. · Cancel · Add author', { v: 'authors', panel: { k: 'author', mode: 'add', focus: 'name' } }),
|
||||
S('Slug from the name', 'Typing a name fills the slug. Auto badge and "Edit slug" pencil.', 'camille-roche · Auto · Generated from the name. Used in public author URLs and API paths. Unique across all authors.', { v: 'authors', panel: { k: 'author', mode: 'add', focus: 'bio', f: { name: 'Camille Roche', slug: 'camille-roche', slugMode: 'auto', bio: 'Freelance writer on lime and stone.' } } }),
|
||||
S('Slug collision', '409 on submit, or on blur after a check.', 'The slug "camille-roche" is already used by another author. · Use camille-roche-2 · Reset to match the name', { v: 'authors', panel: { k: 'author', mode: 'add', f: { name: 'Camille Roche', slug: 'camille-roche', slugMode: 'manual' }, err: { slug: 'The slug "camille-roche" is already used by another author.', suggest: 'camille-roche-2' } } }),
|
||||
S('Validation', 'On submit or blur. Nothing is sent.', 'Enter a name. · Shorten the bio to 280 characters. · 291 / 280 · Enter a full URL starting with https://.', { v: 'authors', panel: { k: 'author', mode: 'add', f: { name: '', bio: 'x'.repeat(291), web: 'example', slugMode: 'empty' }, err: { name: 'Enter a name.', bio: 'Shorten the bio to 280 characters.', web: 'Enter a full URL starting with https://.' } } }),
|
||||
S('Social links', 'Add link adds a row with a type select and a URL. One link is invalid.', 'X · LinkedIn · GitHub · Mastodon · Custom · https://x.com/username · https://www.linkedin.com/in/username · https://github.com/username · https://mastodon.social/@username · https://example.com · Enter a full URL starting with https://. · You can add up to 5 links.', { v: 'authors', panel: { k: 'author', mode: 'edit', i: 2, f: { name: 'Camille Roche', slug: 'camille-roche', slugMode: 'saved', bio: 'Freelance writer on lime and stone.', links: [{ t: 'Mastodon', v: 'https://mastodon.social/@camille' }, { t: 'LinkedIn', v: 'linkedin.com/in/camille', err: 'Enter a full URL starting with https://.' }, { t: 'Custom', v: '', focus: true }] } } }),
|
||||
S('Linked user: choose', 'The select is open. Only users without an author. When none are left it reads "Every user already has an author."', 'Choose a user · Users without an author · Marta Alves · marta@renew.example · Rui Santos · rui@renew.example', { v: 'authors', panel: { k: 'author', mode: 'edit', i: 2, f: { name: 'Camille Roche', slug: 'camille-roche', slugMode: 'saved', uopen: true } } }),
|
||||
S('Edit: linked author', 'Edit on an author linked to a user.', 'Edit Inès Duarte · Linked user (optional) · ines.duarte@renew.example · Unlink · New articles by this user start with this author. · Save changes', { v: 'authors', panel: { k: 'author', mode: 'edit', i: 0, f: { av: 'ines.jpg', name: 'Inès Duarte', slug: 'ines-duarte', slugMode: 'saved', bio: 'Site manager and restoration carpenter. Writes about timber and joinery.', web: 'https://ines-duarte.example', links: [{ t: 'LinkedIn', v: 'https://www.linkedin.com/in/ines-duarte' }], user: 'ines.duarte@renew.example' } } }),
|
||||
S('Avatar: picker', '"Choose image". The existing media picker; shown as a square. The site social image uses this same picker.', 'Choose an image · The avatar for Camille Roche. · Shown as a square. Choose an image with the face or logo near the middle. · Use image', { v: 'authors', panel: { k: 'author', mode: 'edit', i: 2, f: { name: 'Camille Roche', slug: 'camille-roche', slugMode: 'saved' } }, modal: { k: 'pick', n: 'Camille Roche', sel: 1 } }),
|
||||
S('Save failed', '500 or network failure.', 'Couldn\'t save the author. Your changes are still here. Try again in a moment.', { v: 'authors', panel: { k: 'author', mode: 'edit', i: 2, notice: 'Couldn\'t save the author. Your changes are still here. Try again in a moment.', f: { name: 'Camille Roche', slug: 'camille-roche', slugMode: 'saved', bio: 'Freelance writer on lime and stone.' } } }),
|
||||
S('Unlink: confirm', '"Unlink" next to the linked user, owner or admin. On 200 the field returns to "No linked user" and a toast reads "User unlinked" · "Inès Duarte is now a guest author."', 'Unlink Inès Duarte? · Inès Duarte will stay on their articles. New articles by ines.duarte@renew.example will no longer start with this author. · Cancel · Unlink user', { v: 'authors', panel: { k: 'author', mode: 'edit', i: 0, f: { av: 'ines.jpg', name: 'Inès Duarte', slug: 'ines-duarte', slugMode: 'saved', user: 'ines.duarte@renew.example' } }, modal: { k: 'unlink', i: 0 } }),
|
||||
S('Re-link', '"Link user" on a guest author in the row menu or the form. Same list as above.', 'Link Camille Roche to a user? · Only users without an author are listed. · Cancel · Link user', { v: 'authors', modal: { k: 'relink', i: 2 } })
|
||||
]),
|
||||
G('Authors: delete', 'Authors: delete', 'dialog (desktop) · bottom sheet (mobile)', 'DELETE /v1/author/{id}?reassign_to={id|none}', 'Owner and admin. Reassign: the dialog asks who gets the articles, with "Nobody" as the last option, and shows the count in the button. Zero authors are allowed, so Nobody is always valid. The 409 dialog is the server fallback and is drawn once.', [
|
||||
S('Reassign (recommended)', '"Delete…" on an author with articles, owner or admin. The button reads "Reassigning…" while the request runs. On 204 a toast reads "Author deleted" · "3 articles now credit Inès Duarte." A linked author also shows "Linked to ines.duarte@renew.example. The user account isn\'t affected."', 'Delete this author? · "Camille Roche" will be deleted and is credited on 3 articles. This can\'t be undone. · Credit these articles to · Inès Duarte · Where an article has several authors, Camille Roche is removed and the others stay. · Cancel · Delete and reassign 3 articles', { v: 'authors', modal: { k: 'del', i: 2 } }),
|
||||
S('Choose who', 'The select is open. The deleted author is not listed.', 'Nobody · Remove the byline', { v: 'authors', modal: { k: 'del', i: 2, open: true } }),
|
||||
S('Nobody', '"Nobody" chosen.', 'The articles keep any other authors. Articles with only this author will have no byline.', { v: 'authors', modal: { k: 'del', i: 2, none: true } }),
|
||||
S('Failed (shared by site and author delete)', '500 or network failure. Both delete dialogs use this notice.', 'Couldn\'t delete the author · Nothing was changed. Try again in a moment.', { v: 'authors', modal: { k: 'del', i: 2, notice: true } }),
|
||||
S('Server fallback (409)', 'Fallback only. The dialog above always sends reassign_to, so this appears only when the server refuses a stale request because articles still credit the author. Drawn once, not as a flow.', 'Can\'t delete this author · "Camille Roche" is credited on 3 articles. Choose another author to credit instead, or remove Camille Roche from those articles first. · Close · Reassign articles', { v: 'authors', modal: { k: 'blocked', i: 2 } }),
|
||||
S('No articles', 'An author with zero articles: plain confirm.', 'Delete this author? · "Léa Fontaine" will be deleted. No articles credit this author. This can\'t be undone. · Delete author', { v: 'authors', modal: { k: 'del0', i: 4 } })
|
||||
]),
|
||||
G('Authors: pagination', 'Authors: pagination', '/authors?page=3&size=50', 'GET /v1/author/?q=&page=&size= (total in the X-Total-Count header; array body unchanged)', 'Same Paginator as Articles and Media (components.md). Sizes 5, 25, 50, 100, default 25: the existing pattern, unchanged. Page and size in the URL as page and size; defaults omitted; a page past the end falls back to the last page. Search resets to page 1. The count line "N authors" replaces the pager on a single page. The list is drawn with generated rows; 128 authors give 6 pages.', PGS('authors', { path: '/authors', noun: 'author', N: 128, mid: 3, qN: 31, qText: 'mar', big: 1284, bigPage: 12, single: 6, empty: 'zoe' })),
|
||||
G('Editor: site and authors', 'Editor: site and authors', '/article/:id/edit', 'PATCH /v1/article/{id} {site_id, author_ids[]} · GET /v1/site/ · GET /v1/author/ · POST /v1/author/', 'States specific to this feature. The collapsed default (one site, the article has an author) and the Loading and Not found states are drawn in the existing Editor frames, which show the section in the same place; they are not repeated here. The section is open when the install has more than one site or the article has no authors, and collapsed to one summary line otherwise; the choice is remembered per browser. On mobile it is closed by default. With one site the Site select is not rendered. Anyone who can edit the article can set its site and pick authors; "Create author…", the Create author dialog and its "This is me" checkbox are for owner and admin only. For any other role, the "Create my author profile" hint (state 4) creates the profile directly with POST /v1/author/me, with no dialog, then shows the author in the list with a toast. Authors are a reorderable list; the first is the primary byline.', [
|
||||
S('Open: one site, one author', 'The section was opened. No Site select.', 'Authors · Add an author', { v: 'editor', metaOpen: true, meta: { authors: ['Inès Duarte'] } }),
|
||||
S('Open: several sites', 'Site select above the authors, with the canonical host as helper text.', 'Site · Journal · journal.renew.example · Canonical host: journal.renew.example', { v: 'editor', ed: { metaSummary: 'Journal · Inès Duarte' }, metaOpen: true, meta: { sites: true, site: 'Journal', authors: ['Inès Duarte'] } }),
|
||||
S('Site select open', 'The select is open. Options show name and host; the default site is first.', 'Renew · renew.example · Journal · journal.renew.example · Projects · Archive', { v: 'editor', metaOpen: true, meta: { sites: true, site: 'Journal', open: 'site', authors: ['Inès Duarte'] } }),
|
||||
S('No authors, with hint', 'The article has no authors and the user has no author profile. The hint is dismissible and does not return once dismissed. "Create my author profile" creates the profile directly for every role (POST /v1/author/me, no dialog), then the author appears in the list and a toast confirms.', 'You don\'t have an author profile yet · Create one to be credited on your articles. · Create my author profile · No authors. This article will have no byline.', { v: 'editor', metaOpen: true, meta: { hint: true, authors: [] } }),
|
||||
S('Many authors', 'Four authors. The first shows "Primary". Each row has a drag handle and a remove button. Long names truncate with an ellipsis and carry the full name in title and aria-label.', 'Primary · Drag to reorder. The first author is the primary byline. · Dr. Alexandra Konstantinopoulou-Whitfield', { v: 'editor', ed: { metaSummary: 'Inès Duarte +3' }, metaOpen: true, meta: { authors: ['Inès Duarte', 'Jonas Pereira', 'Dr. Alexandra Konstantinopoulou-Whitfield', 'Paul Huber'] } }),
|
||||
S('Add author: open', 'The Add an author combobox is open. Authors already on the article are checked and dimmed. "Create author…" is shown only to owner and admin.', 'Search authors · Create author…', { v: 'editor', metaOpen: true, meta: { authors: ['Inès Duarte'], open: 'authors' } }),
|
||||
S('Add author: no match', 'Typing a name that matches nobody. "Create author…" is shown only to owner and admin.', 'No author matches "Zoe Lambert". · Create author "Zoe Lambert"…', { v: 'editor', metaOpen: true, meta: { authors: ['Inès Duarte'], open: 'authors', q: 'Zoe Lambert' } }),
|
||||
S('Add author: open (no create)', 'A role without author rights. The combobox lists the authors with no "Create author…" row, because that row is shown only to owner and admin.', 'Search authors', { v: 'editor', role: 'user', metaOpen: true, meta: { authors: ['Inès Duarte'], open: 'authors', noCreate: true } }),
|
||||
S('Add author: no match (no create)', 'A role without author rights types a name that matches nobody. Only the message shows; there is no create link, because "Create author…" is shown only to owner and admin.', 'No author matches "Zoe Lambert".', { v: 'editor', role: 'user', metaOpen: true, meta: { authors: ['Inès Duarte'], open: 'authors', q: 'Zoe Lambert', noCreate: true } }),
|
||||
S('Add author: error', 'GET /v1/author/ failed. The article keeps its authors.', 'Couldn\'t load authors · Check your connection and try again. · Try again', { v: 'editor', metaOpen: true, meta: { authors: ['Inès Duarte'], open: 'authors', state: 'error' } }),
|
||||
S('Reorder: keyboard', 'Space or Enter on the handle grabs the row. Arrow keys move it.', 'Jonas Pereira grabbed. Position 2 of 3. Use the up and down arrow keys to move, Space to drop, Escape to cancel.', { v: 'editor', metaOpen: true, meta: { authors: ['Inès Duarte', 'Jonas Pereira', 'Camille Roche'], grab: 1 } }),
|
||||
S('Reorder: pointer', 'Dragging a row. The row lifts and a line shows the drop position.', '', { v: 'editor', metaOpen: true, meta: { authors: ['Inès Duarte', 'Jonas Pereira', 'Camille Roche'], drag: 2, drop: 0 } }),
|
||||
S('Create author: dialog', '"Create author…" in the dropdown, owner and admin only. The writer stays in the editor.', 'Create author · Adds a byline for this article. You can add a bio and avatar later in Authors. · Name · Slug · Zoe Lambert · zoe-lambert · Cancel · Create author', { v: 'editor', metaOpen: true, meta: { authors: ['Inès Duarte'] }, modal: { name: 'Zoe Lambert', slug: 'zoe-lambert' } }),
|
||||
S('Create author: for me', 'Owner and admin only. When the user has no author profile, a checkbox links the new author to them.', 'This is me · Links the author to marta@renew.example.', { v: 'editor', metaOpen: true, meta: { authors: ['Inès Duarte'], hint: true }, modal: { name: 'Marta Alves', slug: 'marta-alves', me: true } }),
|
||||
S('Create author: slug taken', 'The slug exists. The dialog suggests a free one.', 'The slug "zoe-lambert" is already used by another author. · Use zoe-lambert-2', { v: 'editor', metaOpen: true, meta: { authors: ['Inès Duarte'] }, modal: { name: 'Zoe Lambert', slug: 'zoe-lambert', err: true, slugErr: 'The slug "zoe-lambert" is already used by another author.', suggest: 'zoe-lambert-2' } }),
|
||||
S('Create author: failed', '500 or network failure.', 'Couldn\'t create the author · The article is unchanged. Try again in a moment.', { v: 'editor', metaOpen: true, meta: { authors: ['Inès Duarte'] }, modal: { name: 'Zoe Lambert', slug: 'zoe-lambert', notice: true } })
|
||||
]),
|
||||
G('Profile: author profile', 'Profile: author profile', '/profile', 'POST /v1/author/me · GET /v1/auth/me (author field)', 'The "Author profile" card sits between Account and Password in every Profile frame, defined once in AppFrame. The existing Profile frames show its default state ("Create my author profile"). All roles can create their own profile and edit their own linked author. Only the states specific to the card are drawn here.', [
|
||||
S('No author profile', 'The user has no linked author.', 'Author profile · Your public byline on articles. It\'s separate from your account. · You don\'t have an author profile yet. Create one to be credited on your own articles. · Create my author profile · Uses your display name, Marta Alves. You can change it afterwards.', { v: 'profile', pa: { k: 'none' } }),
|
||||
S('Error', '500 or network failure.', 'Couldn\'t create your author profile · Try again in a moment.', { v: 'profile', pa: { k: 'none', err: true } }),
|
||||
S('Created', '201: the card shows the author. The author is named from the display name and linked to the user.', 'Author profile created · Marta Alves is now your byline. · Edit author · Linked to your account. New articles start with this author.', { v: 'profile', pa: { k: 'has' }, toasts: [['success', 'circle-check', 'Author profile created', 'Marta Alves is now your byline.']] }),
|
||||
S('Created, slug adjusted', 'The slug was taken, so the server added a number. No error is shown.', 'Your slug is marta-alves-2 · marta-alves was already used by another author. You can change it in Edit author.', { v: 'profile', pa: { k: 'has', slug: 'marta-alves-2' } }),
|
||||
S('Edit own author', 'Edit author on the card, by a role without author rights. The form opens with the linked user locked and no Unlink. There is no delete action in the form or on this screen.', 'Edit Marta Alves · Linked user · marta@renew.example · This is your author profile. Only an owner or admin can change the link. · Save changes', { v: 'profile', role: 'user', pa: { k: 'has' }, panel: { k: 'author', mode: 'edit', own: true, f: { name: 'Marta Alves', slug: 'marta-alves', slugMode: 'saved', bio: 'Project coordinator. Writes about permits and planning.', user: 'marta@renew.example' } } })
|
||||
]),
|
||||
G('Articles: sites and authors', 'Articles: sites and authors', '/articles?site=journal', 'GET /v1/article/?site={key}&page=&size=&q=&status=', 'Every Articles frame has the Authors column (avatars, at most 3 plus "+N"; "—" when none; on mobile avatars with the first name). When more than one site exists, a Site column and a Site filter appear, read-only text for every role; with one site they are not rendered.', [
|
||||
S('Several sites', 'More than one site exists.', 'Authors · Site · All sites · Renew · Journal · Projects', { v: 'app', list: { multi: true } }),
|
||||
S('Site filter open', 'The Site select in the toolbar. Choosing a site stores ?site=key and resets the page to 1.', 'All sites · Renew · Journal · Projects · Archive', { v: 'app', list: { multi: true, siteMenu: true } }),
|
||||
S('No articles on a site', 'The chosen site has no articles.', 'No articles on "Archive" · Move articles here from the editor, or choose another site. · Show all sites', { v: 'app', list: { multi: true, site: 'Archive', counts: [0, 0, 0], empty: { icon: 'file-text', title: 'No articles on "Archive"', text: 'Move articles here from the editor, or choose another site.', action: 'Show all sites' } } })
|
||||
]),
|
||||
G('Articles: search status', 'Articles: search status', '/articles?seo=suggestions', 'GET /v1/article/?seo=suggestions&page=&size= (items carry seo_status and seo_suggestions)', 'A quiet indicator in the Status cell on desktop and under the title on mobile cards: a lightbulb chip with a count when there are suggestions, an eye-off chip "Hidden" when noindex is on, nothing when the article is ready. The toolbar gets a "Needs attention" toggle with a count next to the search field. Tabs and their counts are unchanged. On a single-site install nothing changes: the Site filter and column stay hidden and the toggle works the same, over all articles.', [
|
||||
S('Status chips', 'Row 2 has 2 suggestions, row 3 is hidden, row 4 has 3, row 5 has 1.', 'Needs attention · 3 · Hidden · 2 suggestions (tooltip) · Hidden from search engines (tooltip)', { v: 'app', list: {} }),
|
||||
S('Needs attention on', 'The toggle is pressed. The list shows only articles with suggestions. Hidden-only articles are not included.', 'Needs attention · 3', { v: 'app', list: { needs: true } }),
|
||||
S('Needs attention: none', 'Nothing to show with the toggle on.', 'Nothing needs attention · Every article has a clean check. Suggestions are optional, so this is just a bonus. · Show all articles', { v: 'app', list: { needs: true, needsN: 0, counts: [0, 0, 0], empty: { icon: 'circle-check', title: 'Nothing needs attention', text: 'Every article has a clean check. Suggestions are optional, so this is just a bonus.', action: 'Show all articles' } } })
|
||||
]),
|
||||
G('Editor: search and sharing', 'Editor: search and sharing', '/article/:id/edit', 'PATCH /v1/article/{id} {slug, excerpt, seo_title, seo_description, cover_image_id, cover_image_alt, social_title, social_description, social_image_id, canonical_url, noindex, seo_dismissed[]}', 'RenewCMS is headless: it never renders pages or adds meta tags. This section helps the writer fill in SEO data and shows what the frontend will receive. Everything is optional and each empty field shows its fallback. Placement: a "Search and sharing" section under "Site and authors" in the sidebar and in the mobile Details sheet. Collapsed by default with a one-line summary (Ready, N suggestions, Hidden from search), remembered per browser. The fields and live previews open in a slide-over (desktop, 960 px) or a 92% sheet over the Details sheet (mobile). Anyone who can edit the article can edit these fields. Suggestions never block saving or publishing: publishing is allowed regardless. Counters are soft guides and turn amber, never red, outside the recommended range. Light and dark follow the theme switch above.', [
|
||||
S('Collapsed: ready', 'The default. Nothing to suggest.', 'Search and sharing · Ready', { v: 'editor', ed: { seoSummary: 'Ready' } }),
|
||||
S('Collapsed: suggestions', 'Summary in the warning colour. No count badge elsewhere.', 'Search and sharing · 2 suggestions', { v: 'editor', ed: { seoSummary: '2 suggestions' } }),
|
||||
S('Collapsed: hidden', 'noindex is on.', 'Search and sharing · Hidden from search', { v: 'editor', ed: { seoSummary: 'Hidden from search' } }),
|
||||
S('Open: ready', 'Address, the all-good message and two actions.', 'Address · renew.example/how-we-price-a-bathroom-renovation · All good · Nothing to suggest for this article. · Edit search and sharing · What the frontend gets', { v: 'editor', ed: { seoSummary: 'Ready' }, seo: { side: { codes: [] } } }),
|
||||
S('Open: suggestions', 'At most three suggestions here, then a count. Each links to its field.', 'The meta title is 74 characters. Search engines may cut it off after about 60. · Go to meta title · The cover image has no alt text. Add a short description of it. · Go to cover image · The body has no headings. H2 headings help readers scan the article. · Go to body · +1 more in Search and sharing', { v: 'editor', ed: { seoSummary: '4 suggestions' }, seo: { side: { codes: ['title_long', 'cover_alt', 'no_h', 'short'] } } }),
|
||||
S('Open: checking', 'While the checks run after the editor loads. The rest of the section stays usable.', 'Checking this article…', { v: 'editor', ed: { seoSummary: 'Checking…' }, seo: { side: { state: 'loading' } } }),
|
||||
S('Open: hidden', 'A line explains the flag.', 'Hidden from search engines. This only sets a flag in the API.', { v: 'editor', ed: { seoSummary: 'Hidden from search' }, seo: { side: { codes: [], hidden: true } } }),
|
||||
S('Open: other site', 'The address uses the article\'s site.', 'journal.renew.example/how-we-price-a-bathroom-renovation', { v: 'editor', ed: { seoSummary: 'Ready' }, seo: { side: { codes: [], site: 1 } } }),
|
||||
S('Panel: defaults', 'A writer who changed nothing. Every value is a fallback and says so.', 'Search and sharing · URL slug · Generated from the title until you edit it. · Meta title · Using article title · Recommended 30 to 60 characters. This is a guide, not a limit. · Meta description · Using first sentence of the body · Recommended 70 to 160 characters. · Excerpt · A short summary. It is also sent as the article teaser. · Cover image · Using the site social image (north-wall.jpg). · Social sharing · Optional · Uses the meta values · Advanced · Canonical URL: automatic · Hide from search engines · Sets noindex in the API. It doesn\'t change who can read the article. · Search result · Social card · Suggestions · What the frontend gets · Cancel · Save changes', { v: 'editor', ed: { seoSummary: '1 suggestion' }, seo: { panel: { codes: ['cover_none'] } } }),
|
||||
S('Panel: filled in', 'Own values everywhere. The fallback chips are gone and the suggestion list shows All good.', 'All good · Nothing to suggest for this article.', { v: 'editor', ed: { seoSummary: 'Ready' }, seo: { panel: { mt: 'What a bathroom renovation costs', md: 'A bathroom renovation is priced by room size, plumbing changes and finish level. Here is how we build a quote.', ex: 'How we price a bathroom renovation, from the survey to the final invoice.', cover: { alt: 'A tiled bathroom wall during renovation' }, codes: [] } } }),
|
||||
S('Panel: outside the soft ranges', 'Counters turn amber. The preview shows the cut-off. Nothing is blocked.', 'The meta title is 74 characters. Search engines may cut it off after about 60. · The description is 41 characters. About 70 to 160 reads best in results. · Cut off here, the way a search engine would.', { v: 'editor', ed: { seoSummary: '2 suggestions' }, seo: { panel: { mt: 'How we price a bathroom renovation: surveys, plumbing, tiling and finishes', md: 'What a bathroom renovation costs.', codes: ['title_long', 'desc_short'] } } }),
|
||||
S('Panel: slug edited', 'The Auto badge is gone. "Reset to match the title" brings it back.', 'Reset to match the title', { v: 'editor', ed: { seoSummary: 'Ready' }, seo: { panel: { slug: 'bathroom-costs', slugMode: 'manual', codes: [] } } }),
|
||||
S('Panel: slug taken', 'Checked on blur and on save. Nothing is saved until a free slug is chosen.', 'The slug "bathroom-costs" is already used on Renew. · Use bathroom-costs-2', { v: 'editor', ed: { seoSummary: 'Ready' }, seo: { panel: { slug: 'bathroom-costs', slugMode: 'taken', codes: [] } } }),
|
||||
S('Panel: cover without alt', 'Alt text is required before the cover counts as ready. It is a suggestion, not an error.', 'Alt text · Needed before the cover counts as ready. Sent as image alt in the API. · Describe the image for people who can\'t see it · The cover image has no alt text. Add a short description of it.', { v: 'editor', ed: { seoSummary: '1 suggestion' }, seo: { panel: { cover: { alt: '' }, codes: ['cover_alt'] } } }),
|
||||
S('Panel: choose cover', 'The shared Media picker.', 'Choose a cover image · The cover for this article. · Use image', { v: 'editor', ed: { seoSummary: '1 suggestion' }, seo: { panel: { codes: ['cover_none'] }, pick: true } }),
|
||||
S('Panel: social sharing open', 'Optional overrides. Each falls back to the meta values.', 'Social sharing · Optional · Social title · Using meta title · Social description · Using meta description · Social image · Using the cover image.', { v: 'editor', ed: { seoSummary: 'Ready' }, seo: { panel: { social: true, cover: { alt: 'A tiled bathroom wall during renovation' }, codes: [] } } }, { seo: { panel: { social: true, scrollY: 560, cover: { alt: 'A tiled bathroom wall during renovation' }, codes: [] } } }),
|
||||
S('Panel: social customised', 'The card shows the overrides, so the Using chips disappear.', 'Customised', { v: 'editor', ed: { seoSummary: 'Ready' }, seo: { panel: { social: true, soc: { t: 'Bathroom costs, explained', d: 'A plain guide to what drives the price.', img: 'kitchen-after.webp' }, codes: [] } } }, { seo: { panel: { social: true, scrollY: 560, soc: { t: 'Bathroom costs, explained', d: 'A plain guide to what drives the price.', img: 'kitchen-after.webp' }, codes: [] } } }),
|
||||
S('Panel: advanced, invalid canonical', 'Collapsed by default. The address must be absolute.', 'Advanced · Canonical URL · Only change this if the same content lives at another address. · Enter a full address starting with https://', { v: 'editor', ed: { seoSummary: 'Ready' }, seo: { panel: { adv: true, canon: 'renew.example/costs', err: { canon: 'Enter a full address starting with https://' }, focus: 'canon', codes: [] } } }, { seo: { panel: { adv: true, scrollY: 640, canon: 'renew.example/costs', err: { canon: 'Enter a full address starting with https://' }, focus: 'canon', codes: [] } } }),
|
||||
S('Panel: hidden from search', 'The switch only sets a flag in the API.', 'Hide from search engines · Sets noindex in the API. It doesn\'t change who can read the article.', { v: 'editor', ed: { seoSummary: 'Hidden from search' }, seo: { panel: { noindex: true, codes: [] } } }, { seo: { panel: { noindex: true, scrollY: 700, codes: [] } } }),
|
||||
S('Panel: mobile search preview', 'The Desktop and Mobile toggle changes the width and where the title is cut.', 'Search result · Desktop · Mobile', { v: 'editor', ed: { seoSummary: 'Ready' }, seo: { panel: { dev: 'mobile', mt: 'How we price a bathroom renovation: surveys, plumbing, tiling and finishes', codes: ['title_long'] } } }),
|
||||
S('Panel: checking', 'Checks run on open and after each pause in typing.', 'Checking this article…', { v: 'editor', ed: { seoSummary: 'Checking…' }, seo: { panel: { sugState: 'loading' } } }),
|
||||
S('Panel: saving', 'Fields are disabled while the request runs.', 'Saving…', { v: 'editor', ed: { seoSummary: 'Ready' }, seo: { panel: { state: 'saving', mt: 'What a bathroom renovation costs', codes: [] } } }),
|
||||
S('Panel: save failed', '500 or network failure. The values stay.', 'Couldn\'t save search and sharing. Your changes are still here. Try again in a moment.', { v: 'editor', ed: { seoSummary: 'Ready' }, seo: { panel: { notice: 'Couldn\'t save search and sharing. Your changes are still here. Try again in a moment.', mt: 'What a bathroom renovation costs', codes: [] } } }),
|
||||
S('Saved', 'The panel closes. The summary updates.', 'Search and sharing saved · Your search and sharing settings are up to date.', { v: 'editor', ed: { seoSummary: 'Ready' }, seo: { side: { codes: [] } }, toasts: [['success', 'circle-check', 'Search and sharing saved', 'Your search and sharing settings are up to date.']] })
|
||||
]),
|
||||
G('Editor: what the frontend gets', 'Editor: what the frontend gets', '/article/:id/edit', 'GET /v1/article/{id}/seo', 'A read-only dialog (desktop, 720 px) or bottom sheet (mobile) with the resolved SEO object exactly as the API returns it. Opened from the sidebar section or the panel. Each value that came from a fallback carries a chip. Formatted shows a compact key and value list, Raw shows the JSON. Copy JSON copies the raw object. Author name, profile URL and social links come from the Authors screen and surface in authors[] and in the JSON-LD author, so Authors itself needs no change.', [
|
||||
S('Formatted', 'Default view.', 'What the frontend gets · The SEO data returned by GET /v1/article/12/seo, read only. RenewCMS doesn\'t render pages or add meta tags: your frontend does. · Formatted · Raw JSON · Copy JSON · Close', { v: 'editor', ed: { seoSummary: 'Ready' }, seo: { side: { codes: [] }, api: {} } }),
|
||||
S('Raw JSON', 'The JSON as the API returns it.', 'Raw JSON', { v: 'editor', ed: { seoSummary: 'Ready' }, seo: { side: { codes: [] }, api: { view: 'raw' } } }),
|
||||
S('Copied', 'The button reads Copied for 2 s and this is announced.', 'Copied', { v: 'editor', ed: { seoSummary: 'Ready' }, seo: { side: { codes: [] }, api: { view: 'raw', copied: true } } }),
|
||||
S('Draft article', 'Drafts answer 404 to anonymous callers.', 'This article is a draft. The API returns this data only to signed-in callers until it is published.', { v: 'editor', ed: { seoSummary: 'Ready' }, seo: { side: { codes: [] }, api: { draft: true } } }),
|
||||
S('Loading', 'Copy is disabled.', '', { v: 'editor', ed: { seoSummary: 'Ready' }, seo: { side: { codes: [] }, api: { state: 'loading' } } }),
|
||||
S('Error', 'GET failed. Nothing in the article changes.', 'Couldn\'t load the SEO data · GET /v1/article/12/seo failed. Your article is unchanged. Try again in a moment. · Try again', { v: 'editor', ed: { seoSummary: 'Ready' }, seo: { side: { codes: [] }, api: { state: 'error' } } })
|
||||
]),
|
||||
G('Sites: SEO defaults', 'Sites: SEO defaults', '/settings/sites', 'PATCH /v1/site/{id} {site_name, title_template, default_description, social_image_id, default_robots}', 'Owner only, like the rest of Sites. The existing add and edit form gains three fields under the default social image (reused, not duplicated): Site name, Title template with a live example, and Default description. The default robots policy keeps its place. A box under the form explains how articles use these defaults. Sites has no separate read-only details view: the edit form is the details, and other roles get the existing 403 page (403 owner_only on PATCH, 401 without a session).', [
|
||||
S('Edit: SEO defaults', 'Edit on the default site.', 'Default social image (optional) · Site name · Shown in titles through the template, and sent as the Open Graph site name. · Title template · Use %title% for the article title and %site% for the site name. · Example · How we price a bathroom renovation | Renew · Default description (optional) · Used when an article has no description, excerpt or body text. · How articles use these defaults · Title · Article title, then the template. · Description · Used last, after the article\'s description, excerpt and body. · Image · Used when an article has no cover image. · Robots · Used unless an article is hidden from search engines.', { v: 'sites', sites: { state: 'ok' }, panel: { k: 'site', mode: 'edit', i: 0, f: { name: 'Renew', key: 'renew', keyMode: 'saved', url: 'https://renew.example', img: 'north-wall.jpg', loc: 'en', ddesc: 'Practical advice on renovating old buildings, from the people who do the work.' } } }),
|
||||
S('Add: defaults', 'New sites start with the default template and nothing else.', 'Site name · e.g. Renew · %title% | %site% · One or two sentences about the site.', { v: 'sites', sites: { state: 'ok' }, panel: { k: 'site', mode: 'add', f: { name: 'Journal', key: 'journal', keyMode: 'auto', url: 'https://journal.renew.example' } } }),
|
||||
S('Template: custom', 'The example updates as the owner types.', 'Example · How we price a bathroom renovation – Journal', { v: 'sites', sites: { state: 'ok' }, panel: { k: 'site', mode: 'edit', i: 1, focus: 'tpl', f: { name: 'Journal', key: 'journal', keyMode: 'saved', url: 'https://journal.renew.example', sname: 'Journal', tpl: '%title% – %site%' } } }),
|
||||
S('Template: not valid', 'The template needs %title%. Nothing is sent.', 'The template must contain %title%.', { v: 'sites', sites: { state: 'ok' }, panel: { k: 'site', mode: 'edit', i: 1, focus: 'tpl', err: { tpl: 'The template must contain %title%.' }, f: { name: 'Journal', key: 'journal', keyMode: 'saved', url: 'https://journal.renew.example', sname: 'Journal', tpl: '%site%' } } }),
|
||||
S('Save failed', '500 or network failure.', 'Couldn\'t save the site. Your changes are still here. Try again in a moment.', { v: 'sites', sites: { state: 'ok' }, panel: { k: 'site', mode: 'edit', i: 0, notice: 'Couldn\'t save the site. Your changes are still here. Try again in a moment.', f: { name: 'Renew', key: 'renew', keyMode: 'saved', url: 'https://renew.example', img: 'north-wall.jpg', loc: 'en' } } })
|
||||
])
|
||||
],
|
||||
specs: [
|
||||
{ label: 'Sites and authors: decisions', title: 'Sites and authors: decisions to confirm', note: 'Only choices that change behaviour or the API. Rows marked Decided were answered in the revision brief and are no longer questions.', tables: [{ cols: ['#', 'Decision', 'Status', 'To confirm'], tpl: '40px minmax(0,1.8fr) 90px minmax(0,1.6fr)', rows: [
|
||||
['1', 'Sites: only the owner can create, edit, set the default or delete. Other roles don\'t see the Sites entry; a direct link shows a 403 page. Anyone who can edit an article can still set its site and read the site list.', 'Decided', 'Roles, from the brief.'],
|
||||
['2', 'Authors: owner and admin manage all authors. Other roles see the list and details read-only, pick authors in the editor, and can create and edit their own author profile.', 'Decided', 'Roles, from the brief.'],
|
||||
['3', 'A site key is set when the site is created and can\'t be edited. The edit form shows it read-only.', 'Decided', 'Used in API paths. PATCH rejects a changed key.'],
|
||||
['4', 'An article may have zero authors. Nothing blocks publishing.', 'Decided', 'Zero authors allowed.'],
|
||||
['5', 'Deleting an author asks who gets the articles, with "Nobody" as the last option.', 'Decided', 'Reassign on delete.'],
|
||||
['6', 'With one site, the editor hides the Site select and the list hides the Site column and filter.', 'Open', 'Hide in the editor too, or only in the list.'],
|
||||
['7', 'Deleting a site with articles requires a destination, preselected as the default site. The default site can\'t be deleted.', 'Open', 'API: DELETE needs reassign_to when article_count is above 0.'],
|
||||
['8', 'A user has at most one author and an author at most one user. Only accepted users without an author are listed. Unlinking keeps the author and its articles.', 'Open', 'API: unique link. Unlink is PATCH with user_id null.'],
|
||||
['9', '"Create my author profile" never fails on a taken slug. The server adds a number and the card says so.', 'Open', 'API: the POST /v1/author/me response carries the final slug.'],
|
||||
['10', 'Article counts on sites and authors include drafts.', 'Open', 'API: counts guard deletion, so they must be complete.'],
|
||||
['11', 'Moving articles between sites changes their canonical host at once. No redirects are created.', 'Open', 'Behaviour. Redirects belong to a later slice.'],
|
||||
['12', 'Limits: bio 280 characters, 5 social links, name 100 characters, locale as a language tag.', 'Open', 'API validation.'],
|
||||
['13', 'The first site is seeded from PUBLIC_URL and named from its host.', 'Open', 'Migration: the seed name.']
|
||||
] }] },
|
||||
{ label: 'Sites and authors: deviations', title: 'Sites and authors: deviations from existing patterns', note: 'Where the design departs from a pattern already on the board, and why.', tables: [{ cols: ['Pattern', 'Existing', 'Here', 'Why'], tpl: 'minmax(0,1fr) minmax(0,1.2fr) minmax(0,1.4fr) minmax(0,1.4fr)', rows: [
|
||||
['Settings children', 'One group, "Media", with Variants and Cache', 'A second group, "Publishing", with Sites', 'Sites is not a media setting'],
|
||||
['Slide-over', 'Variant form and record details only', 'Site and author forms', 'Both have a live preview'],
|
||||
['Delete dialog', 'Text and two buttons', 'A select for the destination, plus a count in the button', 'Articles must not be orphaned'],
|
||||
['Media picker', 'Title "Add an image", inserts into text, has an alt text step', 'Title "Choose an image", button "Use image", no alt text', 'The image is a field value, not content'],
|
||||
['Row menu on a disabled action', 'Actions are hidden when not allowed', 'Delete stays visible, aria-disabled, with an explanation', 'The brief asks for an explanatory tooltip. Touch shows the text'],
|
||||
['Chips', 'No existing chip control', 'A vertical list of rows, not wrapped inline chips', 'Reordering needs one axis and 44 px targets on touch'],
|
||||
['Editor sidebar', 'Static Details list', 'A collapsible section above Details', 'Holds the only new editor fields'],
|
||||
['Role-restricted entries', 'Pages are shown or hidden by role', 'The Sites entry is removed for non-owners, and /settings/sites shows a 403 page', 'No dead entries, and a direct link still gets an answer'],
|
||||
['Counter', 'Title field shows "n / 200"', 'Bio shows "n / 280", red above the limit', 'Same counter, same colours']
|
||||
] }] },
|
||||
{ label: 'Sites and authors: API and errors', title: 'Sites and authors: API and HTTP statuses', note: 'Rows for states.md. Inline errors sit under the named field; dialogs show the notice inside.', tables: [{ cols: ['Status', 'Code', 'Copy', 'Where'], tpl: '70px minmax(0,1fr) minmax(0,2fr) minmax(0,1fr)', rows: [
|
||||
['400', 'invalid_site_url', 'Use https. For example https://blog.example.com. · Remove the path. Use only the host, like https://blog.example.com. · Enter a full URL, like https://blog.example.com.', 'Inline under Base URL'],
|
||||
['409', 'site_key_taken', 'A site with the key "journal" already exists. Choose another key.', 'Inline under Key, with a suggestion'],
|
||||
['409', 'site_has_articles', 'Choose where the articles go. This site has 38 articles.', 'Inside the delete dialog'],
|
||||
['403', 'default_site', 'The default site can\'t be deleted. Make another site the default first.', 'Toast if the menu was stale'],
|
||||
['403', 'owner_only', 'You don\'t have access to Sites · Only the owner can manage sites. Ask the owner of this site if you need a change.', '403 page on /settings/sites'],
|
||||
['403', 'owner_only (action)', 'Only the owner can manage sites · Ask the owner of this site.', 'Error toast if the role changed while the page was open'],
|
||||
['403', 'author_rights', 'Only an owner or admin can change authors · You can still edit your own author profile.', 'Error toast if the role changed while the page was open'],
|
||||
['400', 'key_immutable', 'Used in API paths, so it can\'t change.', 'Not shown: the edit form has no editable key'],
|
||||
['400', 'invalid_locale', 'Use a language tag like en or fr-CH.', 'Inline under Locale'],
|
||||
['404', 'site_not_found', 'That site no longer exists · It was deleted somewhere else, so we removed it from the list.', 'Info toast'],
|
||||
['409', 'author_slug_taken', 'The slug "camille-roche" is already used by another author.', 'Inline under Slug, with a suggestion'],
|
||||
['409', 'author_has_articles', 'Can\'t delete this author · "Camille Roche" is credited on 3 articles. Choose another author to credit instead, or remove Camille Roche from those articles first.', 'Blocked dialog'],
|
||||
['409', 'user_already_linked', 'That user already has an author. Choose another user.', 'Inline under Linked user'],
|
||||
['422', 'bio_too_long', 'Shorten the bio to 280 characters.', 'Inline under Bio'],
|
||||
['422', 'invalid_url', 'Enter a full URL starting with https://.', 'Inline under Website and each social link'],
|
||||
['404', 'author_not_found', 'That author no longer exists · It was deleted somewhere else, so we removed it from the list.', 'Info toast'],
|
||||
['500', '–', 'Couldn\'t save the site. Your changes are still here. Try again in a moment. · Couldn\'t save the author. Your changes are still here. Try again in a moment. · Couldn\'t create the author · The article is unchanged. Try again in a moment.', 'Notice inside the panel or dialog']
|
||||
] }, { cols: ['Method and path', 'Used by', 'Notes'], tpl: 'minmax(0,1.3fr) minmax(0,1fr) minmax(0,1.6fr)', rows: [
|
||||
['GET /v1/site/', 'Sites, Site label, filter', 'Any role that edits articles. Returns article_count per site'],
|
||||
['POST /v1/site/', 'Add site', 'Owner only. name, key, base_url, social_image_id, robots, locale, is_default'],
|
||||
['PATCH /v1/site/{id}', 'Edit site, set as default', 'Owner only. The key can\'t be changed. is_default true moves the flag'],
|
||||
['DELETE /v1/site/{id}?reassign_to={id}', 'Delete site', 'Owner only. reassign_to required when article_count > 0'],
|
||||
['GET /v1/author/?q=&page=&size=', 'Authors, Add author combobox', 'Any role. Total in X-Total-Count, as for articles'],
|
||||
['POST /v1/author/ · PATCH · DELETE ?reassign_to={id|none}', 'Authors, editor dialog', 'Owner and admin. none removes the byline'],
|
||||
['POST /v1/author/me', 'Create my author profile', 'Any role. Name from the display name, linked to the user. A user can also PATCH their own linked author'],
|
||||
['PATCH /v1/article/{id}', 'Editor', 'site_id and author_ids[] in order, any role that edits the article; is_online is untouched']
|
||||
] }] },
|
||||
{ label: 'Sites and authors: components', title: 'Sites and authors: components (Nuxt UI v4)', note: 'New components use existing tokens only.', tables: [{ cols: ['Component', 'Status', 'Nuxt UI', 'Notes'], tpl: 'minmax(0,1fr) 80px minmax(0,1.4fr) minmax(0,1.8fr)', rows: [
|
||||
['SitesTable, AuthorsTable', 'New', 'UTable; below 640 px a list of UCard', 'Same row heights as Users. Defined once as DirectoryList in DirectoryFrame and used by both. Read-only variant has no actions'],
|
||||
['SiteForm, AuthorForm', 'New', 'USlideover + UForm, UFormField, UInput, UTextarea, URadioGroup, USwitch', 'Sheet on mobile. Close with changes opens the discard UModal'],
|
||||
['SlugField', 'New', 'UInput + UButton (icon) + UBadge', 'Defined once in DirectoryFrame. Auto badge, pencil, "Reset to match the name". Locked read-only variant with a lock for the site key after creation'],
|
||||
['SocialLinksRepeater', 'New', 'USelect + UInput + UButton, in UFormField', 'Max 5 rows. Placeholder follows the type'],
|
||||
['MediaField', 'New', 'UButton + UModal (existing picker)', 'Defined once in DirectoryFrame. Used for the social image and the avatar'],
|
||||
['AuthorViewPanel', 'New', 'USlideover, read-only', 'Detail for roles without author rights. Close is the only action'],
|
||||
['AuthorAvatar', 'New', 'UAvatar', 'Initials fallback, square, radius 0'],
|
||||
['AuthorStack', 'New', 'UAvatarGroup max=3', 'Shows "+N"'],
|
||||
['AuthorList', 'New', 'List of UButton, UAvatar, UBadge; sorting with useSortable', 'No Nuxt UI match for sortable rows. Keyboard reordering is custom'],
|
||||
['AuthorSelect', 'New', 'USelectMenu multiple with create-item', 'Footer item "Create author…" opens the dialog'],
|
||||
['SiteSelect', 'New', 'USelectMenu', 'Item slot shows name and host'],
|
||||
['UserSelect', 'New', 'USelectMenu', 'Only users without an author'],
|
||||
['ReassignDialog', 'New', 'UModal + USelectMenu + UAlert', 'Defined once in DirectoryFrame. Used for site and author deletion'],
|
||||
['MetaSection', 'New', 'UCollapsible', 'Desktop sidebar and mobile sheet'],
|
||||
['AuthorProfileCard', 'New', 'UCard + UButton + UAlert', 'Profile screen'],
|
||||
['CreateAuthorHint', 'New', 'UAlert closable', 'Dismissal stored per user'],
|
||||
['Default badge, Linked badge, Guest badge', 'New', 'UBadge', 'Sand fill, info soft fill, outline'],
|
||||
['Row menu with a disabled item', 'Existing + change', 'UDropdownMenu + UTooltip', 'The item stays focusable']
|
||||
] }] },
|
||||
{ label: 'Sites and authors: accessibility', title: 'Sites and authors: keyboard and screen reader', note: 'Applies to the reorderable author list and to the media picker used by both forms.', tables: [{ cols: ['Control', 'Keyboard', 'Screen reader'], tpl: 'minmax(0,0.8fr) minmax(0,1.6fr) minmax(0,1.8fr)', rows: [
|
||||
['Author list, handle', 'Tab reaches each handle. Space or Enter grabs. Up and Down move one place; Home and End move to the first and last place. Space or Enter drops. Escape cancels and restores the order.', 'The handle is a button: "Reorder Inès Duarte, position 1 of 3". The list has aria-describedby text "Drag to reorder. The first author is the primary byline." A polite live region announces: "Jonas Pereira grabbed. Position 2 of 3. Use the up and down arrow keys to move, Space to drop, Escape to cancel." Then "Jonas Pereira moved to position 1 of 3.", "Jonas Pereira dropped at position 1 of 3." or "Reorder cancelled. Jonas Pereira is back at position 2 of 3."'],
|
||||
['Author list, remove', 'Tab, then Enter or Space. Focus moves to the next row\'s handle, or to the Add an author field after the last row.', 'Button "Remove Camille Roche from this article". Live region: "Camille Roche removed. 2 authors."'],
|
||||
['Author list, pointer and touch', 'Pointer: drag the handle after 4 px. Touch: press and hold the 44 px handle for 250 ms, then drag.', 'Same live region messages as the keyboard.'],
|
||||
['Add an author', 'Down arrow or typing opens the list. Up and Down move, Enter adds or removes, Escape closes and returns focus to the field. "Create author…" is the last option.', 'role=combobox, aria-expanded, aria-controls, aria-multiselectable. Selected options have aria-selected. Live region: "Inès Duarte added. 2 authors."'],
|
||||
['Media picker', 'Focus moves into the dialog and is trapped. Tabs use arrow keys. Tiles form one radio group: arrow keys move, Space selects. "Use image" is aria-disabled until a tile is selected. Escape closes and focus returns to "Choose image" or "Change image".', 'Each tile reads "north-wall.jpg, 3.9 MB". After "Use image" a polite message reads "Image selected: north-wall.jpg", and focus lands on "Change image".'],
|
||||
['Slug field', '"Edit slug" moves focus into the input. "Reset to match the name" keeps focus on itself.', 'The input has aria-invalid and aria-describedby for the error. Reset announces "Slug reset to camille-roche".'],
|
||||
['Section header', 'Enter or Space toggles.', 'Button with aria-expanded and aria-controls.'],
|
||||
['Disabled delete', 'Stays in the tab order of the menu.', 'aria-disabled, with aria-describedby pointing to the explanation.']
|
||||
] }] }
|
||||
] }
|
||||
}
|
||||
dirGroups(bo) {
|
||||
const doc = this.dirDoc()
|
||||
const rowsA = ['How we price a bathroom renovation', 'Choosing lime plaster for old stone walls', 'Before and after: the Rue Verte kitchen', 'Winter checklist for timber windows', 'Why we reuse original floorboards', 'Our first passive-house retrofit']
|
||||
const meta = [[true, '12 Mar 2026', '2 hours ago', ['Inès Duarte'], 'Journal'], [false, '9 Sep 2026', 'Yesterday', ['Inès Duarte', 'Camille Roche'], 'Renew'], [true, '28 Aug 2026', '3 days ago', ['Jonas Pereira'], 'Projects'], [false, '2 Sep 2026', '5 days ago', ['Inès Duarte', 'Jonas Pereira', 'Camille Roche', 'Paul Huber', 'Léa Fontaine'], 'Journal'], [true, '14 Jun 2026', '18 Aug 2026', ['Paul Huber'], 'Renew'], [true, '3 Apr 2026', '2 Jul 2026', [], 'Journal']]
|
||||
const rows = meta.map((x, i) => ({ t: rowsA[i], on: x[0], c: x[1], u: x[2], au: x[3], site: x[4], seo: [0, 2, 'hidden', 3, 1, 0][i] }))
|
||||
const edShell = ed => ({ kind: 'editor', nav: 'articles', crumbs: ['Articles', 'How we price a bathroom renovation'], mTitle: 'Edit article', mLead: 'arrow-left', mAction: 'ellipsis', ed: { status: 'draft', save: 'saved', sheet: true, ...ed } })
|
||||
const pfShell = { kind: 'profile', nav: 'profile', crumbs: ['Profile'], mTitle: 'Profile', pf: {} }
|
||||
return doc.groups.map(g => ({ label: g.label, title: g.title, route: g.route, api: g.api, note: g.note, states: g.states.map(st => {
|
||||
const o = st.o
|
||||
if (o.v === 'adminSettings') { const src = bo.flatMap(x => x.states).find(x => x.name === 'Admin view'); const ch = { name: st.name, trigger: st.trigger, role: 'admin', sideOpen: true }; return { ...src, ...ch, m: { ...src.m, ...ch } } }
|
||||
if (o.v === 'app') {
|
||||
const L = { ...o.list }
|
||||
if (!L.empty && !L.loading) L.rows = L.only ? rows.filter(r => r.site === L.only) : rows
|
||||
if (L.needs && !L.empty) L.rows = rows.filter(r => r.seo > 0)
|
||||
const base = { kind: 'articles', nav: 'articles', crumbs: ['Articles'], mTitle: 'Articles', list: L }
|
||||
return { notMedia: true, name: st.name, trigger: st.trigger, ...base, m: { ...base } }
|
||||
}
|
||||
let s = { ...o }
|
||||
if (o.v === 'editor') s.shell = { ...edShell(o.ed), role: o.role }
|
||||
if (o.v === 'profile') s.shell = { ...pfShell, pa: o.pa, role: o.role }
|
||||
const x = { isDir: true, notMedia: false, name: st.name, trigger: st.trigger, ...s }
|
||||
return { ...x, m: { ...x, ...(st.mo || {}) } }
|
||||
}) }))
|
||||
}
|
||||
dirSpecs() { return this.dirDoc().specs.map(sp => ({ label: sp.label, title: sp.title, note: sp.note, tables: sp.tables.map(t => ({ cols: t.cols, tpl: t.tpl, rows: t.rows.map(r => r.map((x, i) => this.cell(x, i, { muted: x === '–' }))) })) })) }
|
||||
dirCopy() { return this.dirDoc().groups.flatMap(g => g.states.filter(s => s.copy).map(s => [g.title + ': ' + s.name, s.copy])) }
|
||||
// DIR-END
|
||||
finish(gs) { return gs.map(g => ({ ...g, states: g.states.map(st => ({ notMedia: !st.isMedia && !st.isAct, ...st, m: { ...st.m } })) })) }
|
||||
renderVals() {
|
||||
const modes = [['system', 'System'], ['light', 'Light'], ['dark', 'Dark']].map(([k, label]) => {
|
||||
@@ -838,7 +1114,7 @@ class Component extends DCLogic {
|
||||
return { label, on, bg: on ? 'var(--ui-primary)' : 'transparent', fg: on ? 'var(--ui-bg)' : 'var(--ui-text-toned)', pick: () => this.setState({ mode: k }) }
|
||||
})
|
||||
const rows = a => a.map(r => ({ a: r[0], b: r[1] }))
|
||||
return { rootRef: this.rootRef, modes, groups: this.groups(), specs: this.varSpecs(), spCopy: rows(this.state.spec.copy), spComps: rows(this.state.spec.comps), spApi: rows(this.state.spec.api) }
|
||||
return { rootRef: this.rootRef, modes, groups: this.groups(), specs: [...this.varSpecs(), ...this.dirSpecs()], dirCopy: this.dirCopy().map(r => ({ a: r[0], b: r[1] })), spCopy: rows(this.state.spec.copy), spComps: rows(this.state.spec.comps), spApi: rows(this.state.spec.api) }
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
+33
-1
@@ -2,6 +2,12 @@
|
||||
|
||||
Every state in the three boards is drawn in light and dark (theme switch) at 1440×900 and 390×844. Counts are in README.md.
|
||||
|
||||
## Clock-sensitive states
|
||||
Only individual states that render a relative time or a countdown are marked "Clock-sensitive" on the board: Articles "Published" (Updated reads "Just now"), Media "Upload: too many requests (429)" and Settings "Too many requests (429)" (countdowns), Users "Renew invite: done", and the Settings update states that show "Last checked today at 09:41" or "yesterday" (Up to date, Check failed, Update available, Update available with notes open, Update done, Plain restart: confirm, Admin view, Role changed, Update already running). Capture and test them with a frozen clock at 13 Oct 2026, 09:41. Frames that merely list dated rows are not marked.
|
||||
|
||||
## Sites and authors: roles
|
||||
Sites: only the owner can create, edit, delete or set the default; other roles have no Sites entry and get a 403 page on a direct link. Anyone who can edit an article can set its site and read the site list. Authors: owner and admin manage; other roles see the list and detail read-only and can create and edit their own author only. The site key is immutable after creation.
|
||||
|
||||
## Copy glossary
|
||||
| Use | Not |
|
||||
|---|---|
|
||||
@@ -23,12 +29,32 @@ Glossary pass 2, changes made: activity log lines "Removed N expired invites" an
|
||||
| Status | Copy |
|
||||
|---|---|
|
||||
| 400 | "That request wasn't valid. Check the fields and try again." |
|
||||
| 401, 403 | Global redirect, no local copy |
|
||||
| 401, 403 | Global redirect, no local copy (403 from an unverified account). Role 403s have local copy: see the rows below |
|
||||
| 404 | "That item no longer exists." |
|
||||
| 409 | "This changed somewhere else. Reload and try again." |
|
||||
| 413 | "That file is too large." |
|
||||
| 429 | "Too many requests. Try again in a few minutes." |
|
||||
| 500, network | "Something went wrong on our side. Nothing was changed. Try again in a moment." |
|
||||
| 400 invalid_site_url | "Use https. For example https://blog.example.com." / "Remove the path. Use only the host, like https://blog.example.com." / "Enter a full URL, like https://blog.example.com." (inline under base url) |
|
||||
| 409 site_key_taken | "A site with the key "journal" already exists. Choose another key." (inline under key, with a suggestion) |
|
||||
| 409 site_has_articles | "Choose where the articles go. This site has 38 articles." (inside the delete dialog) |
|
||||
| 403 "Only the owner can do this." (page) | "You don't have access to Sites" / "Only the owner can manage sites. Ask the owner of this site if you need a change." / "Back to Settings" (403 page on /settings/sites) |
|
||||
| 403 "Only the owner can do this." (action) | "Only the owner can manage sites" / "Ask the owner of this site." (error toast, role changed while the page was open) |
|
||||
| 403 author_rights | "Only an owner or admin can change authors" / "You can still edit your own author profile." (error toast, role changed while the page was open) |
|
||||
| 400 key_immutable | "Used in API paths, so it can't change." (not shown: the edit form has no editable key) |
|
||||
| 400 invalid_locale | "Use a language tag like en or fr-CH." (inline under locale) |
|
||||
| 403 default_site | "The default site can't be deleted. Make another site the default first." (toast if the menu was stale) |
|
||||
| 404 site_not_found | "That site no longer exists" / "It was deleted somewhere else, so we removed it from the list." (info toast) |
|
||||
| 409 author_slug_taken | "The slug "camille-roche" is already used by another author." (inline under slug, with a suggestion) |
|
||||
| 409 author_has_articles | "Can't delete this author" / ""Camille Roche" is credited on 3 articles. Choose another author to credit instead, or remove Camille Roche from those articles first." (server fallback dialog, drawn once) |
|
||||
| 409 user_already_linked | "That user already has an author. Choose another user." (inline under linked user) |
|
||||
| 422 bio_too_long | "Shorten the bio to 280 characters." (inline under bio) |
|
||||
| 422 invalid_url | "Enter a full URL starting with https://." (inline under website and each social link) |
|
||||
| 404 author_not_found | "That author no longer exists" / "It was deleted somewhere else, so we removed it from the list." (info toast) |
|
||||
| 404 site_not_found (sitemap) | GET /v1/site/{key}/sitemap, unknown key. The body is the code `site_not_found`, shown on Integration in the code style (not rewritten as prose). |
|
||||
| 400 (sitemap page or size) | "The request cannot be processed due to a mismatch in the format of the body." (same text as the other routes on Integration) |
|
||||
| 403 owner_only vs article SEO | Integration note under the 403 row: "Site SEO defaults are owner only. Article SEO fields need only the right to edit the article." |
|
||||
| 500 – | "Couldn't save the site. Your changes are still here. Try again in a moment." / "Couldn't save the author. Your changes are still here. Try again in a moment." / "Couldn't create the author" / "The article is unchanged. Try again in a moment." (notice inside the panel or dialog) |
|
||||
|
||||
## Public image 400 bodies
|
||||
`{ "status": 400, "error": "unknown_variant", "message": "Unknown variant", "detail": "hero" }` and `{ "status": 400, "error": "unsupported_parameter", "message": "Unsupported parameter", "detail": "width" }`. The original is not served as a fallback.
|
||||
@@ -36,6 +62,9 @@ Glossary pass 2, changes made: activity log lines "Removed N expired invites" an
|
||||
## Articles and Media pagination
|
||||
Same states and copy on Articles and Media (Media draws them under the grid or list). Loading next page keeps row height, controls disabled, summary "Loading page 7…". Error "Couldn't load page 7. Showing page 6." with Retry. Out of range "That page doesn't exist. Showing the last page." Page size menu offers 5, 25, 50, 100. Invalid `page` or `size` in the URL (size=30, page=abc, page=0) is replaced by the default without a notice; the API 400 never reaches the user.
|
||||
|
||||
## Sites and authors pagination
|
||||
Groups "Sites: pagination" and "Authors: pagination", 10 states each, same pager as Articles and Media, sizes 5, 25, 50, 100 (default 25). First, middle and last page; single page (count line "N sites" or "N authors" only, no pager, no size select); page-size menu; loading ("Loading page N…", skeleton rows, pager kept and disabled); error ("Couldn't load page N. Showing page M." with Retry, rows and page number kept); empty after search (existing empty state, no pager); search resets to page 1; long labels on mobile. Out of range: ?page past the end is replaced by the last page, with "That page doesn't exist. Showing the last page." (not drawn; as Articles). Details in screens/sites.md and screens/authors.md.
|
||||
|
||||
## Editor
|
||||
Counter without limit ("1,204 words · 7,318 characters"; at 120,000 characters "19,845 words · 120,000 characters"), "Saving…", "Saved", "Couldn't save. Your text is kept. Retry". Link states and the toolbar overflow are drawn in the Editor group (11 states).
|
||||
|
||||
@@ -47,3 +76,6 @@ As in screens/settings.md, screens/image-variants.md and screens/activity.md. Sy
|
||||
|
||||
## Per-screen copy
|
||||
screens/<name>.md, section "Copy per state" (generated from the board source).
|
||||
|
||||
## SEO round
|
||||
Frames: Editor: search and sharing (24), Editor: what the frontend gets (6), Sites: SEO defaults (5), Articles: search status (3). Each is drawn desktop and mobile; light and dark follow the theme switch. None is clock-sensitive: dates in the API preview are fixed sample values. Disabled state: all fields at 40% while saving. Validation: slug taken, canonical not absolute, title template without %title%, excerpt over 300. Suggestions never block saving or publishing. Copy per state: screens/editor.md, articles.md, sites.md.
|
||||
@@ -72,6 +72,11 @@ task clean # remove bin/, tmp/ and the built SPA
|
||||
- All Go tests live in [`test/`](../test) (package `test`, black-box). They use in-memory fakes of the domain `Repository` interfaces, so they need no database, SMTP server or network.
|
||||
- HTTP-level tests use `net/http/httptest` against a chi router. Call `validator.InitValidator()` before invoking a handler.
|
||||
- SPA component tests use Vitest + Vue Test Utils (`task test:web`). `task lint:web` runs eslint and a type check.
|
||||
- A few tests open a real SQLite file in a temporary directory (the chunked id lookups, the slug backfill and the `?seo=` measurement). They never touch the real database.
|
||||
- The tests that need a real MySQL, MariaDB or PostgreSQL server skip themselves when `RENEWCMS_TEST_MYSQL_DSN` or `RENEWCMS_TEST_POSTGRES_DSN` is unset. No CI exists, so run them by hand before a release that touches the repositories:
|
||||
- `task test:mysql` runs `mysql:8.4` then `mariadb:11` in Docker, and `task test:postgres` runs `postgres:16` then `postgres:17`. Docker is required; the tasks start and remove the containers. Extra arguments go after `--`, for example `task test:postgres -- -run Postgres.*Chunked -v`.
|
||||
- To use your own server on a scratch database: `RENEWCMS_TEST_MYSQL_DSN='user:pass@tcp(host:3306)/db' go test -tags nofrontend ./test/... -run MySQL -count=1`, or `RENEWCMS_TEST_POSTGRES_DSN='postgres://user:pass@host:5432/db?sslmode=disable' go test -tags nofrontend ./test/... -run Postgres -count=1`.
|
||||
- `TestMySQLChunkedLookups` and `TestPostgresChunkedLookups` check that the batched `IN` lookups of the article repository (500 ids per batch) return the same rows as SQLite.
|
||||
|
||||
## Visual check against the design
|
||||
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
# Performance notes
|
||||
|
||||
## The `?seo=` article filter
|
||||
|
||||
`GET /v1/article/` assesses the SEO status of articles in memory, because the status depends on the body, the site template and the authors. Every request assesses every visible article once, to fill `counts.suggestions`, and `?seo=` reuses that assessment to filter before paging. The cost therefore grows with the number of articles, not with the page size.
|
||||
|
||||
Measured by `TestSeoFilterPerformance` in `test/seo_filter_performance_test.go` (skipped with `-short`): 5,000 articles of about 5 KB each in one site, on a SQLite file in a temporary directory, every article with suggestions, `?seo=suggestions&size=25`, slowest of 3 runs:
|
||||
|
||||
| Version | Time |
|
||||
| --- | --- |
|
||||
| `counts.suggestions` added, assessment done twice | about 430 ms |
|
||||
| assessment shared between the counts and the filter | about 270 ms |
|
||||
|
||||
The target is 300 ms for 5,000 articles. The test also measures the default list (`GET /v1/article/` with no `?seo=`), which pays the same assessment for `counts.suggestions`. Latest run on the development machine, slowest of 3 runs:
|
||||
|
||||
| Request | Time |
|
||||
| --- | --- |
|
||||
| `?seo=suggestions&size=25` | 315 to 338 ms |
|
||||
| default page, no `?seo=` | 307 to 329 ms |
|
||||
|
||||
Both are slightly above the 300 ms target on this machine (they were about 270 ms in the earlier measurement), so the target is logged by the test but not enforced; no cache or index was added. Re-run the test with `go test -tags nofrontend ./test/... -run TestSeoFilterPerformance -v -count=1` after a change to the assessment rules or the article repository. The time depends on the machine; the test only fails above 500 ms.
|
||||
@@ -15,6 +15,43 @@ Body, in this order. Omit a section only when it would be empty, except Upgradin
|
||||
|
||||
Rules: bullets are full sentences ending with a period; user-facing wording, no commit prefixes; sentence-case headings; no horizontal rules, no metadata block, no "Pre-1.0" boilerplate (the prerelease flag says it); every release ships all 6 binaries from `task release`.
|
||||
|
||||
## Next release (draft)
|
||||
|
||||
Articles and sites now store the data a website needs for search and sharing, and every article gets an address that is unique on its site.
|
||||
|
||||
### New
|
||||
|
||||
**Article SEO fields**
|
||||
|
||||
- An article has a slug, an excerpt, a search title and description, a cover image with its alt text, a social title, description and image, a canonical address, a noindex flag and a list of dismissed suggestions.
|
||||
- The slug is generated from the title, is unique per site and can be changed at any time; an empty slug regenerates it from the title.
|
||||
- A site has a site name, a title template and a default description.
|
||||
|
||||
### API
|
||||
|
||||
- `PATCH /v1/article/{id}` also takes the SEO fields. `cover_image_id` and `social_image_id` accept `null`. A slug already used on the target site answers `409` `slug_taken` with the header `X-Slug-Suggestion` holding the first free slug.
|
||||
- `GET /v1/article/{id}`, `POST /v1/article/`, `PATCH /v1/article/{id}`, `PATCH /v1/article/{id}/publish` and `PATCH /v1/article/{id}/unpublish` return the twelve SEO fields; the items of `GET /v1/article/` return `slug` and `excerpt`.
|
||||
- `POST /v1/site/` and `PATCH /v1/site/{id}` take `site_name`, `title_template` and `default_description`; a template without `%title%` is `400` `invalid_title_template`.
|
||||
- Changed: `GET /v1/media/{id}/usage` stays an array, and every item gains `type` and `fields` without losing `id`, `title` and `published`. Authors and sites that use the image are now listed, without a `published` key.
|
||||
- Changed: a cover image, a social image, an author avatar and a site default social image all count in `used_in` and in the `unused` filter. Deleting an image clears the covers and social images that use it, and merging or purging repoints them.
|
||||
|
||||
### New: SEO output
|
||||
|
||||
- `GET /v1/article/{id}/seo` returns the resolved search and sharing data of an article (title with the site template, description, canonical address, robots, Open Graph, Twitter, image, authors and ready JSON-LD), so a frontend can render its meta tags without reimplementing the fallback chain. Drafts answer verified callers only.
|
||||
- `POST /v1/article/{id}/seo/check` evaluates an article without saving, with optional overrides, and reports the suggestions, the status and whether the slug is free.
|
||||
- `GET /v1/article/` items carry `seo_status` and `seo_suggestions`, and the new `seo` parameter filters on the status.
|
||||
- `GET /v1/site/{key}/sitemap` lists the published URLs of a site, paged, with the total in `X-Total-Count`, which is now exposed to browsers through CORS.
|
||||
- `GET /v1/article/` counts gain `suggestions`, the number of visible articles that still have SEO suggestions.
|
||||
- `GET /v1/site/` takes `q`, `page` and `size` and sends the number of matching sites in `X-Total-Count`; without `page` and `size` every site is still returned, as a JSON array.
|
||||
- `GET /v1/author/` also sends its total in `X-Total-Count`.
|
||||
- `GET /v1/media/{id}` reads one image, with the fields of a media list item; a missing image answers `404` and a malformed id `400`.
|
||||
|
||||
### Upgrading
|
||||
|
||||
- The first start after the upgrade adds the new columns, gives every existing article a slug generated from its title (in id order within each site, with `-2`, `-3` on conflicts) and creates the unique `(site_id, slug)` index. Nothing else changes, and a second start changes nothing.
|
||||
- A deleted article now frees its slug.
|
||||
- The slug backfill writes in batches of 500 rows, so a large database is migrated without one long transaction, and a start that was interrupted resumes where it stopped.
|
||||
|
||||
## Published releases
|
||||
|
||||
Each body lives in `docs/releases/<tag>.md`. Publish with `tea releases create --tag <tag> --title "<tag> - <theme>" --note-file docs/releases/<tag>.md --prerelease --asset <file>` after `task release`, with one `--asset` per file: the six binaries, `bin/checksums.txt` and `bin/checksums.txt.sig`. `task release` produces all eight and fails before building when the signing key is missing or wrong (see [deployment.md](deployment.md#release-signing-key-maintainers-once)). Never publish a release without the two checksum files.
|
||||
|
||||
@@ -84,7 +84,8 @@ Feature: Every real action of the back-office is recorded in the activity log fr
|
||||
Scenario: A title change is recorded as a text diff when a title edit exists
|
||||
Given a use case that changes an article's title from "Spring release" to "Spring release 2"
|
||||
Then its event has action "article.edit" and changes [{"field": "title", "kind": "text", "before": "Spring release", "after": "Spring release 2"}]
|
||||
And only the fields title, online and body can ever appear in an article event's changes
|
||||
And only the fields title, online, body and, since features/seo_data_backend.feature, site, authors and the SEO fields can ever appear in an article event's changes
|
||||
And SEO free-text fields (excerpt, seo_title, seo_description, social_title, social_description, cover_image_alt) are recorded as a size delta in characters with kind "body" and never as text, while short values (slug, canonical_url, noindex, cover_image, social_image) are recorded as text before and after
|
||||
|
||||
Scenario: Publishing is recorded with the publish state
|
||||
Given the article 8 "Spring release" is offline
|
||||
|
||||
@@ -189,3 +189,76 @@ Feature: Paginated article listing
|
||||
Given the repository fails on its next call
|
||||
When a client sends GET /v1/article/
|
||||
Then the status is 500 and the body is "Failed to retrieve articles"
|
||||
|
||||
Rule: counts.suggestions
|
||||
|
||||
Background:
|
||||
Given counts holds all, online, draft and suggestions, and the rest of the body shape ({"items","total","page","size","counts"}) is unchanged
|
||||
And suggestions is the number of visible articles whose seo_status is "suggestions"
|
||||
And it ignores q, status, site, seo, sort, page and size, like the other counts
|
||||
And an article whose seo_status is "hidden" or "ready" is not counted
|
||||
And a suggestion code listed in the article's seo_dismissed is never counted
|
||||
And it equals the total of GET /v1/article/?seo=suggestions sent with no other filter by the same caller
|
||||
|
||||
Scenario: counts carries the suggestions count
|
||||
Given 4 online and 2 draft articles of which 3 have suggestions
|
||||
When a verified account sends GET /v1/article/
|
||||
Then counts is {"all": 6, "online": 4, "draft": 2, "suggestions": 3}
|
||||
|
||||
Scenario: It is zero when nothing needs attention
|
||||
Given 5 articles that all have a clean SEO check
|
||||
When a verified account sends GET /v1/article/
|
||||
Then counts.suggestions is 0
|
||||
|
||||
Scenario: It equals the total of the suggestions filter
|
||||
Given 30 articles of which 12 have suggestions
|
||||
When a verified account sends GET /v1/article/?seo=suggestions
|
||||
Then total is 12 and counts.suggestions is 12
|
||||
|
||||
Scenario Outline: It ignores every other query parameter
|
||||
Given 6 articles of which 3 have suggestions, on the sites "renew" and "journal"
|
||||
When a verified account sends GET /v1/article/?<params>
|
||||
Then counts.suggestions is 3
|
||||
|
||||
Examples:
|
||||
| params |
|
||||
| q=tile |
|
||||
| status=draft |
|
||||
| site=journal |
|
||||
| seo=ready |
|
||||
| seo=hidden |
|
||||
| sort=title:asc |
|
||||
| size=5&page=99 |
|
||||
|
||||
Scenario: Hidden articles are not counted
|
||||
Given an article with suggestions that is noindex
|
||||
When a verified account sends GET /v1/article/
|
||||
Then counts.suggestions is 0
|
||||
|
||||
Scenario: Dismissed suggestions are not counted
|
||||
Given an article whose only suggestion is dismissed
|
||||
When a verified account sends GET /v1/article/
|
||||
Then counts.suggestions is 0
|
||||
|
||||
Scenario: A verified caller counts offline articles too
|
||||
Given an online and a draft article, both with suggestions
|
||||
When a verified account sends GET /v1/article/
|
||||
Then counts.suggestions is 2
|
||||
|
||||
Scenario: A public caller counts online articles only
|
||||
Given an online and an offline article, both with suggestions
|
||||
When a caller without a verified account sends GET /v1/article/
|
||||
Then counts is {"all": 1, "online": 1, "draft": 0, "suggestions": 1}
|
||||
|
||||
Scenario: An empty library
|
||||
When a verified account sends GET /v1/article/ with no article stored
|
||||
Then counts is {"all": 0, "online": 0, "draft": 0, "suggestions": 0}
|
||||
|
||||
Scenario: A failure to compute the count fails the request
|
||||
Given the repository fails while the suggestions are evaluated
|
||||
When a verified account sends GET /v1/article/
|
||||
Then the status is 500 and the body is "Failed to retrieve articles"
|
||||
|
||||
Scenario: Existing fields are unchanged
|
||||
Then total, page, size, ordering and every item field are as before
|
||||
And counts.all, counts.online and counts.draft keep their values
|
||||
@@ -30,6 +30,21 @@ Helper: decode the body into {items []map, total, page, size int, counts {all, o
|
||||
18. Use-case tests: the paged list method returns items, total and counts, propagates a repo error (errors.Is on a sentinel), and the unpaged `Filters{}` call used by `purgePlan.go` and `ListMedia.go` still returns every article (existing tests keep passing).
|
||||
19. Existing tests that decode `GET /v1/article/` as an array (`test/public_article_listing_test.go`, `test/article_test.go`, `test/use_case_baseline_test.go`, features/articles_list.qa.md item 1) are amended to the envelope. List them in the diff.
|
||||
|
||||
## counts.suggestions (Go, `test/`, `task test`)
|
||||
|
||||
Build `article.NewHandler(...)` over the real use cases and the extended `mockArticleRepo`, as in the section above. The fixture articles carry bodies that yield suggestions, hidden (noindex) or ready SEO status and a `seo_dismissed` list. Mount on a fresh `chi.NewRouter()` that mirrors `NewArticleRouter` and call `validator.InitValidator()`.
|
||||
|
||||
20. Counts table: 4 online and 2 draft with 3 suggestions gives `counts` exactly `{all:6, online:4, draft:2, suggestions:3}`. Decode into a map and assert the key set is exactly those four.
|
||||
21. Zero case: 5 clean articles gives `suggestions` 0. Empty library gives all four at 0.
|
||||
22. Equality: 30 articles, 12 with suggestions; `GET /?seo=suggestions` gives `total` 12 and `counts.suggestions` 12.
|
||||
23. Independence table: `q=tile`, `status=draft`, `site=journal`, `seo=ready`, `seo=hidden`, `sort=title:asc`, `size=5&page=99` all give 3.
|
||||
24. Exclusions: a noindex article with suggestions and an article whose only suggestion is dismissed are not counted; one with two suggestions of which one is dismissed is counted once.
|
||||
25. Visibility: a verified caller counts an online and a draft article (2); an anonymous caller and an unverified caller count the online one only, with `draft` 0.
|
||||
26. Repository failure while evaluating gives 500 "Failed to retrieve articles" and no partial body.
|
||||
27. Regression: the existing assertions on `total`, `page`, `size`, `counts.all/online/draft` and items stay green without edits.
|
||||
28. Docs, read by hand: `docs/api/articles.md` (example JSON gets `"suggestions"`, and the `counts` bullet says global, visibility-scoped, noindex and dismissed excluded, equal to the unfiltered `seo=suggestions` total); `web/src/data/apiCatalogue.ts` list response fields with its spec and `IntegrationView.spec.ts` counts; `docs/release-notes.md` line.
|
||||
29. Scoped mutation through `task mutate` only: `MUTATE_FILES=ListArticles.go MUTATE_RUN='TestArticle.*Count' MUTATE_WORKERS=2 task mutate -- ./internal/infrastructure/useCases`, plus any other file touched by the change. Re-check LIVED or NOT COVERED suspects without `MUTATE_RUN`. Then `task lint:go` and `task fmt`.
|
||||
|
||||
## Docs (verified by reading the diff)
|
||||
|
||||
- `docs/api/articles.md`: new "Pagination, search, sort and counts" section (parameters including `sort` values, default and id tie-break, envelope, ordering, errors) and a "Breaking change" note, like the existing format note: GET /v1/article/ no longer returns a bare array; read `items`.
|
||||
|
||||
@@ -0,0 +1,928 @@
|
||||
Feature: Authors backend, public bylines that articles credit in order
|
||||
|
||||
As an owner or admin of a RenewCMS installation
|
||||
I want to manage authors and credit them on articles in a chosen order
|
||||
So that readers see who wrote an article, whether or not the writer has an account
|
||||
|
||||
Background:
|
||||
Given the spec of record is docs/design/screens/authors.md, docs/design/screens/editor.md (site and authors), docs/design/screens/profile.md, docs/design/states.md (author rows), docs/design/routes.md and docs/design/sites-authors-slices.md
|
||||
And this slice is backend only: no SPA, no change to docs/design
|
||||
And an Author has id (uint32), name, slug, bio, avatar_id (nullable media id), website (nullable), social_links, user_id (nullable and unique), is_linked and article_count, in snake_case JSON
|
||||
And an article has zero or more authors in a stored order through an ordered article_authors join; the first is the primary byline
|
||||
And zero authors on an article is allowed and never blocks publishing
|
||||
And the routes live under /v1/author, mounted inside the JWT group: GET /, POST /, POST /me, PATCH /{id}, DELETE /{id}?reassign_to={id|none}
|
||||
And GET /v1/author/ accepts a session or an API key from a verified account; every write, POST /me included, is session-only
|
||||
And POST / and DELETE /{id} go through RequireOwnerOrAdmin with its existing body "Only owners and admins can do this."
|
||||
And PATCH /{id} is allowed to owner and admin on any author, and to any verified account on the author linked to itself, and otherwise answers 403 with the body "author_rights"
|
||||
And the only roles defined today are "owner" and "admin", so a role-without-author-rights is exercised with a verified account whose role is any other value
|
||||
And error responses are plain text from http.Error whose body is exactly the code token: author_not_found, author_slug_taken, author_has_articles, user_already_linked, author_already_linked, user_not_found, author_rights, bio_too_long, invalid_url, too_many_links, invalid_slug, invalid_reassign, image_not_found
|
||||
And bio_too_long, invalid_url and too_many_links answer 422; other validate-tag failures answer 400 with the validator error text, a body that cannot be decoded answers 400 with apperr.BodyErrorMessage, and a malformed id answers 400 with apperr.IdUint32ErrorMessage
|
||||
And the name has 1 to 100 characters after trimming, the slug matches ^[a-z0-9]+(-[a-z0-9]+)*$ with 1 to 100 characters, the bio has at most 280 characters counted in runes
|
||||
And website and every social link URL must be https with a host, at most 2048 characters; an empty or null website means none
|
||||
And social_links holds at most 5 items of {"type", "url"} where type is one of x, linkedin, github, mastodon, custom
|
||||
And an author has user_email in its JSON only for owner and admin; it is absent for every other caller
|
||||
And an author inside an article has only id, name, slug, bio, avatar_id, website and social_links
|
||||
And request validation goes through validate tags and validator.Validate.Struct
|
||||
And handlers reach authors only through use cases and domain interfaces, and no comment is added anywhere
|
||||
|
||||
Rule: Reading authors
|
||||
|
||||
Scenario: The list is newest first with article counts
|
||||
Given the authors "Léa Fontaine" (id 1), "Inès Duarte" (id 2) and "Camille Roche" (id 3)
|
||||
And "Inès Duarte" is credited on 9 articles and "Léa Fontaine" on none
|
||||
When a verified account sends GET /v1/author/
|
||||
Then the status is 200
|
||||
And the body is {"items": [...], "total": 3, "page": 1, "size": 25}
|
||||
And the items are "Camille Roche", "Inès Duarte", "Léa Fontaine" in that order
|
||||
And every item carries article_count
|
||||
|
||||
Scenario Outline: Who can read the list
|
||||
Given at least one author exists
|
||||
When GET /v1/author/ is sent with <credentials>
|
||||
Then the status is <status>
|
||||
|
||||
Examples:
|
||||
| credentials | status |
|
||||
| the owner's jwt cookie | 200 |
|
||||
| a verified admin's jwt cookie | 200 |
|
||||
| a verified account with another role | 200 |
|
||||
| a valid API key | 200 |
|
||||
| an unverified account's jwt cookie | 403 |
|
||||
| no credentials | 401 |
|
||||
|
||||
Scenario Outline: Search matches the name or the slug
|
||||
Given the authors "Camille Roche" (slug "camille-roche") and "Zoe Lambert" (slug "zl")
|
||||
When a verified account sends GET /v1/author/?q=<q>
|
||||
Then the items are <names>
|
||||
And total is <total>
|
||||
|
||||
Examples:
|
||||
| q | names | total |
|
||||
| camille | "Camille Roche" | 1 |
|
||||
| ROCHE | "Camille Roche" | 1 |
|
||||
| zl | "Zoe Lambert" | 1 |
|
||||
| zoe | "Zoe Lambert" | 1 |
|
||||
| nobody | none | 0 |
|
||||
|
||||
Scenario Outline: Pagination follows the article list
|
||||
Given 30 authors
|
||||
When a verified account sends GET /v1/author/?<params>
|
||||
Then the status is <status>
|
||||
And <result>
|
||||
|
||||
Examples:
|
||||
| params | status | result |
|
||||
| size=25&page=2 | 200 | 5 items, total 30, page 2, size 25 |
|
||||
| size=5 | 200 | 5 items, total 30, page 1, size 5 |
|
||||
| page=3&size=100 | 200 | 0 items, total 30 |
|
||||
| size=30 | 400 | the body is apperr.BodyErrorMessage |
|
||||
| page=0 | 400 | the body is apperr.BodyErrorMessage |
|
||||
| page=abc | 400 | the body is apperr.BodyErrorMessage |
|
||||
|
||||
Scenario: The account email is shown to owner and admin only
|
||||
Given the author "Inès Duarte" is linked to the user ines.duarte@renew.example
|
||||
When the owner sends GET /v1/author/
|
||||
Then "Inès Duarte" has is_linked true, user_id set and user_email "ines.duarte@renew.example"
|
||||
When a verified account with another role sends GET /v1/author/
|
||||
Then "Inès Duarte" has is_linked true
|
||||
And no "user_email" key appears anywhere in the body
|
||||
And the body does not contain "ines.duarte@renew.example"
|
||||
|
||||
Scenario: A guest author is not linked
|
||||
Given the author "Camille Roche" has no user
|
||||
When a verified account sends GET /v1/author/
|
||||
Then "Camille Roche" has is_linked false, user_id null and no user_email
|
||||
|
||||
Scenario: An author without avatar or website returns nulls
|
||||
When a verified account reads an author with no avatar and no website
|
||||
Then avatar_id is null, website is null, bio is "" and social_links is []
|
||||
|
||||
Rule: Creating an author is owner or admin only
|
||||
|
||||
Scenario Outline: An owner or admin creates an author
|
||||
When <credentials> sends POST /v1/author/ with {"name": "Camille Roche", "slug": "camille-roche", "bio": "Writer.", "website": "https://example.com", "social_links": [{"type": "x", "url": "https://x.com/camille"}]}
|
||||
Then the status is 201
|
||||
And the body is the author with a new id, article_count 0, is_linked false and the given values
|
||||
And the author is stored
|
||||
|
||||
Examples:
|
||||
| credentials |
|
||||
| the owner's jwt cookie |
|
||||
| a verified admin's jwt cookie |
|
||||
|
||||
Scenario: Only the name is required
|
||||
When the owner sends POST /v1/author/ with {"name": "Zoe Lambert"}
|
||||
Then the status is 201
|
||||
And the slug is "zoe-lambert", bio is "", avatar_id, website and user_id are null and social_links is []
|
||||
|
||||
Scenario Outline: The slug is generated from the name
|
||||
When the owner sends POST /v1/author/ with {"name": "<name>"}
|
||||
Then the slug is "<slug>"
|
||||
|
||||
Examples:
|
||||
| name | slug |
|
||||
| Camille Roche | camille-roche |
|
||||
| Inès Duarte | ines-duarte |
|
||||
| Dr. O'Neil Smith | dr-o-neil-smith |
|
||||
| !!! | author |
|
||||
|
||||
Scenario: A generated slug that is taken is refused
|
||||
Given the author with slug "camille-roche" exists
|
||||
When the owner sends POST /v1/author/ with {"name": "Camille Roche"}
|
||||
Then the status is 409
|
||||
And the body is "author_slug_taken"
|
||||
And no author is added
|
||||
|
||||
Scenario: A taken slug is refused
|
||||
Given the author with slug "camille-roche" exists
|
||||
When the owner sends POST /v1/author/ with {"name": "Other", "slug": "camille-roche"}
|
||||
Then the status is 409
|
||||
And the body is "author_slug_taken"
|
||||
And no author is added
|
||||
|
||||
Scenario: The slug is unique even if the repository reports a race
|
||||
Given the repository reports a unique violation on the slug
|
||||
When the owner sends POST /v1/author/ with a free-looking slug
|
||||
Then the status is 409 with body "author_slug_taken"
|
||||
|
||||
Scenario Outline: Fields are validated
|
||||
When the owner sends POST /v1/author/ with <field> <value>
|
||||
Then the status is <status>
|
||||
And the body is "<body>"
|
||||
And no author is added
|
||||
|
||||
Examples:
|
||||
| field | value | status | body |
|
||||
| name | (empty) | 400 | the validator error text |
|
||||
| name | " " | 400 | the validator error text |
|
||||
| name | 101 characters | 400 | the validator error text |
|
||||
| slug | "Camille" | 400 | invalid_slug |
|
||||
| slug | "camille_roche" | 400 | invalid_slug |
|
||||
| slug | "-camille" | 400 | invalid_slug |
|
||||
| slug | 101 characters | 400 | invalid_slug |
|
||||
| bio | 281 characters | 422 | bio_too_long |
|
||||
| website | "http://example.com" | 422 | invalid_url |
|
||||
| website | "example.com" | 422 | invalid_url |
|
||||
| website | "https://" | 422 | invalid_url |
|
||||
| social_links | 6 links | 422 | too_many_links |
|
||||
| social_links | [{"type": "x", "url": "http://x.com/a"}] | 422 | invalid_url |
|
||||
| social_links | [{"type": "facebook", "url": "https://f.com/a"}] | 400 | the validator error text |
|
||||
| avatar_id | 999 (no such image) | 400 | image_not_found |
|
||||
|
||||
Scenario Outline: Boundaries are accepted
|
||||
When the owner sends POST /v1/author/ with <field> <value>
|
||||
Then the status is 201
|
||||
|
||||
Examples:
|
||||
| field | value |
|
||||
| name | 100 characters |
|
||||
| slug | 100 characters |
|
||||
| bio | 280 characters |
|
||||
| bio | 280 multi-byte characters |
|
||||
| social_links | 5 links |
|
||||
| social_links | 2 links of type "custom" |
|
||||
| website | "" |
|
||||
|
||||
Scenario: A malformed body is refused
|
||||
When the owner sends POST /v1/author/ with the body "{not json"
|
||||
Then the status is 400
|
||||
And the body is apperr.BodyErrorMessage
|
||||
And no author is added
|
||||
|
||||
Scenario: The role is checked before the body
|
||||
When an account with another role sends POST /v1/author/ with the body "{not json"
|
||||
Then the status is 403 with body "Only owners and admins can do this."
|
||||
|
||||
Scenario: An author can be created linked to a user
|
||||
Given the user 3 has no author
|
||||
When the owner sends POST /v1/author/ with {"name": "Marta Alves", "user_id": 3}
|
||||
Then the status is 201
|
||||
And the author has user_id 3 and is_linked true
|
||||
|
||||
Scenario Outline: An author cannot be created with an unusable user
|
||||
When the owner sends POST /v1/author/ with {"name": "X", "user_id": <user_id>}
|
||||
Then the status is <status>
|
||||
And the body is "<body>"
|
||||
And no author is added
|
||||
|
||||
Examples:
|
||||
| user_id | status | body |
|
||||
| 999 (no such user) | 404 | user_not_found |
|
||||
| 3 (already has author) | 409 | user_already_linked |
|
||||
|
||||
Rule: The caller creates their own author
|
||||
|
||||
Scenario Outline: The author is named from the display name or the username
|
||||
Given the verified account has display name "<display>" and username "<username>" and no author
|
||||
When it sends POST /v1/author/me
|
||||
Then the status is 201
|
||||
And the author name is "<name>" and the slug is "<slug>"
|
||||
And the author has user_id of the caller and is_linked true
|
||||
And slug_adjusted is false
|
||||
|
||||
Examples:
|
||||
| display | username | name | slug |
|
||||
| Marta Alves | marta | Marta Alves | marta-alves |
|
||||
| (empty) | marta | marta | marta |
|
||||
|
||||
Scenario Outline: Any verified role may do it
|
||||
When <credentials> sends POST /v1/author/me
|
||||
Then the status is 201
|
||||
|
||||
Examples:
|
||||
| credentials |
|
||||
| the owner's jwt cookie |
|
||||
| a verified admin's jwt cookie |
|
||||
| a verified account with another role |
|
||||
|
||||
Scenario: A taken slug is de-duplicated silently
|
||||
Given the author with slug "marta-alves" exists and "marta-alves-2" too
|
||||
When "Marta Alves" sends POST /v1/author/me
|
||||
Then the status is 201
|
||||
And the slug is "marta-alves-3"
|
||||
And slug_adjusted is true
|
||||
And no error is returned
|
||||
|
||||
Scenario: The suffix still fits in the slug limit
|
||||
Given a display name whose slug is 100 characters and that slug is taken
|
||||
When the caller sends POST /v1/author/me
|
||||
Then the status is 201
|
||||
And the slug is at most 100 characters and ends with "-2"
|
||||
And slug_adjusted is true
|
||||
|
||||
Scenario: Only the own-author creation carries slug_adjusted
|
||||
When the owner sends POST /v1/author/ with {"name": "Camille Roche"}
|
||||
Then the 201 body has no slug_adjusted field
|
||||
And GET /v1/author/ items and GET /v1/auth/me author have no slug_adjusted field
|
||||
|
||||
Scenario: A caller who already has an author is refused
|
||||
Given the caller is linked to an author
|
||||
When the caller sends POST /v1/author/me
|
||||
Then the status is 409
|
||||
And the body is "user_already_linked"
|
||||
And no author is added
|
||||
|
||||
Scenario: Two concurrent calls create one author
|
||||
Given the repository reports a unique violation on user_id
|
||||
When the caller sends POST /v1/author/me
|
||||
Then the status is 409 with body "user_already_linked"
|
||||
|
||||
Scenario Outline: The endpoint is session-only and verified-only
|
||||
When POST /v1/author/me is sent with <credentials>
|
||||
Then the status is <status>
|
||||
And no author is added
|
||||
|
||||
Examples:
|
||||
| credentials | status | body |
|
||||
| a valid API key | 403 | This action needs a real session. |
|
||||
| an unverified account's jwt cookie | 403 | the existing verification message |
|
||||
| no credentials | 401 | the existing unauthorized message |
|
||||
|
||||
Rule: Editing an author
|
||||
|
||||
Scenario: The owner edits any author
|
||||
Given the author 2 "Camille Roche" with slug "camille-roche"
|
||||
When the owner sends PATCH /v1/author/2 with {"name": "Camille R.", "slug": "camille-r", "bio": "New.", "website": "https://camille.example", "social_links": [{"type": "github", "url": "https://github.com/camille"}]}
|
||||
Then the status is 200
|
||||
And the body is the author with the new values
|
||||
|
||||
Scenario: Absent fields are untouched
|
||||
Given the author 2 has a bio, a website and an avatar
|
||||
When the owner sends PATCH /v1/author/2 with {"name": "Camille R."}
|
||||
Then only the name changed
|
||||
|
||||
Scenario Outline: Nullable fields are cleared
|
||||
Given the author 2 has an avatar 5, a website and 2 social links
|
||||
When the owner sends PATCH /v1/author/2 with <body>
|
||||
Then the status is 200
|
||||
And <result>
|
||||
|
||||
Examples:
|
||||
| body | result |
|
||||
| {"avatar_id": null} | avatar_id is null |
|
||||
| {"website": null} | website is null |
|
||||
| {"website": ""} | website is null |
|
||||
| {"social_links": []} | social_links is [] |
|
||||
| {"bio": ""} | bio is "" |
|
||||
|
||||
Scenario: The avatar is set to an existing image
|
||||
Given the image 5 exists
|
||||
When the owner sends PATCH /v1/author/2 with {"avatar_id": 5}
|
||||
Then the author 2 has avatar_id 5
|
||||
|
||||
Scenario: Social links are replaced as a whole
|
||||
Given the author 2 has 3 social links
|
||||
When the owner sends PATCH /v1/author/2 with {"social_links": [{"type": "x", "url": "https://x.com/a"}]}
|
||||
Then the author 2 has exactly that one link
|
||||
|
||||
Scenario Outline: Editing is validated like creation
|
||||
When the owner sends PATCH /v1/author/2 with <field> <value>
|
||||
Then the status is <status>
|
||||
And the body is "<body>"
|
||||
And the author 2 is unchanged
|
||||
|
||||
Examples:
|
||||
| field | value | status | body |
|
||||
| name | (empty) | 400 | the validator error text |
|
||||
| slug | "Bad Slug" | 400 | invalid_slug |
|
||||
| bio | 281 characters | 422 | bio_too_long |
|
||||
| website | "http://example.com" | 422 | invalid_url |
|
||||
| social_links | 6 links | 422 | too_many_links |
|
||||
| avatar_id | 999 | 400 | image_not_found |
|
||||
|
||||
Scenario: Keeping the own slug is not a collision
|
||||
When the owner sends PATCH /v1/author/2 with {"slug": "camille-roche", "bio": "x"} and the slug is already that author's
|
||||
Then the status is 200
|
||||
|
||||
Scenario: Taking another author's slug is refused
|
||||
Given the author 3 has slug "zoe-lambert"
|
||||
When the owner sends PATCH /v1/author/2 with {"slug": "zoe-lambert"}
|
||||
Then the status is 409
|
||||
And the body is "author_slug_taken"
|
||||
And the author 2 is unchanged
|
||||
|
||||
Scenario Outline: An empty or unknown update is refused
|
||||
When the owner sends PATCH /v1/author/2 with <body>
|
||||
Then the status is 400
|
||||
And the body is apperr.BodyErrorMessage
|
||||
And the author 2 is unchanged
|
||||
|
||||
Examples:
|
||||
| body |
|
||||
| {} |
|
||||
| {"colour": "x"} |
|
||||
| {"name": null} |
|
||||
|
||||
Scenario: A missing author is not found
|
||||
When the owner sends PATCH /v1/author/999 with {"name": "X"}
|
||||
Then the status is 404
|
||||
And the body is "author_not_found"
|
||||
|
||||
Scenario: A malformed id is refused
|
||||
When the owner sends PATCH /v1/author/abc with {"name": "X"}
|
||||
Then the status is 400
|
||||
And the body is apperr.IdUint32ErrorMessage
|
||||
|
||||
Scenario: A no-op edit records nothing
|
||||
When the owner sends PATCH /v1/author/2 with the values it already has
|
||||
Then the status is 200
|
||||
And no activity event is recorded
|
||||
|
||||
Scenario Outline: A role without author rights edits only its own author
|
||||
Given the verified account with another role is linked to the author 4
|
||||
When it sends PATCH /v1/author/<id> with {"bio": "Updated."}
|
||||
Then the status is <status>
|
||||
And the body is "<body>"
|
||||
|
||||
Examples:
|
||||
| id | status | body |
|
||||
| 4 | 200 | the author |
|
||||
| 2 | 403 | author_rights |
|
||||
| 999 | 404 | author_not_found |
|
||||
|
||||
Scenario Outline: Own author edits include name, slug and avatar
|
||||
Given the verified account with another role is linked to the author 4
|
||||
When it sends PATCH /v1/author/4 with <body>
|
||||
Then the status is 200
|
||||
|
||||
Examples:
|
||||
| body |
|
||||
| {"name": "Marta A."} |
|
||||
| {"slug": "marta-a"} |
|
||||
| {"avatar_id": 5} |
|
||||
| {"social_links": []} |
|
||||
|
||||
Scenario: A role without author rights cannot change the link
|
||||
Given the verified account with another role is linked to the author 4
|
||||
When it sends PATCH /v1/author/4 with {"user_id": null}
|
||||
Then the status is 403
|
||||
And the body is "author_rights"
|
||||
And the author 4 is still linked
|
||||
|
||||
Scenario: An API key cannot edit an author
|
||||
When PATCH /v1/author/2 is sent with a valid API key
|
||||
Then the status is 403 with body "This action needs a real session."
|
||||
|
||||
Rule: Linking and unlinking a user
|
||||
|
||||
Scenario: The owner links a user to a guest author
|
||||
Given the author 2 is a guest and the user 3 has no author
|
||||
When the owner sends PATCH /v1/author/2 with {"user_id": 3}
|
||||
Then the status is 200
|
||||
And the author 2 has user_id 3, is_linked true and user_email of the user 3
|
||||
|
||||
Scenario: A user cannot have two authors
|
||||
Given the user 3 is linked to the author 4
|
||||
When the owner sends PATCH /v1/author/2 with {"user_id": 3}
|
||||
Then the status is 409
|
||||
And the body is "user_already_linked"
|
||||
And the author 2 is unchanged
|
||||
|
||||
Scenario: A linked author must be unlinked before it can be relinked
|
||||
Given the author 2 is linked to the user 3 and the user 5 has no author
|
||||
When the owner sends PATCH /v1/author/2 with {"user_id": 5}
|
||||
Then the status is 409
|
||||
And the body is "author_already_linked"
|
||||
|
||||
Scenario: Linking the user it already has is a no-op
|
||||
Given the author 2 is linked to the user 3
|
||||
When the owner sends PATCH /v1/author/2 with {"user_id": 3}
|
||||
Then the status is 200
|
||||
And no activity event is recorded
|
||||
|
||||
Scenario: An unknown user cannot be linked
|
||||
When the owner sends PATCH /v1/author/2 with {"user_id": 999}
|
||||
Then the status is 404
|
||||
And the body is "user_not_found"
|
||||
|
||||
Scenario: The owner unlinks a user
|
||||
Given the author 2 is linked to the user 3
|
||||
When the owner sends PATCH /v1/author/2 with {"user_id": null}
|
||||
Then the status is 200
|
||||
And the author 2 has user_id null, is_linked false and no user_email
|
||||
And the user 3 can create or be linked to an author again
|
||||
And the author 2 stays credited on its articles
|
||||
|
||||
Scenario: Unlinking a guest author is a no-op
|
||||
When the owner sends PATCH /v1/author/2 with {"user_id": null} on a guest author
|
||||
Then the status is 200
|
||||
And no activity event is recorded
|
||||
|
||||
Scenario: A new article by the unlinked user no longer starts with the author
|
||||
Given the user 3 was unlinked from the author 2
|
||||
When the user 3 creates an article
|
||||
Then the article has no authors
|
||||
|
||||
Rule: Deleting an author
|
||||
|
||||
Scenario: An author without articles is deleted
|
||||
Given the author 2 credits no article
|
||||
When the owner sends DELETE /v1/author/2
|
||||
Then the status is 204
|
||||
And the author 2 no longer exists
|
||||
|
||||
Scenario: An author with articles needs a destination
|
||||
Given the author 2 is credited on 3 articles
|
||||
When the owner sends DELETE /v1/author/2
|
||||
Then the status is 409
|
||||
And the body is "author_has_articles"
|
||||
And the author and the 3 credits are unchanged
|
||||
|
||||
Scenario: The articles are reassigned to another author
|
||||
Given the author 2 is credited on the articles 10, 11 and 12 and the author 3 exists
|
||||
When the owner sends DELETE /v1/author/2?reassign_to=3
|
||||
Then the status is 204
|
||||
And the articles 10, 11 and 12 credit the author 3
|
||||
And the author 2 no longer exists
|
||||
|
||||
Scenario: The reassigned author takes the position of the deleted one
|
||||
Given the article 10 credits the authors 5, 2, 6 in that order
|
||||
When the owner deletes the author 2 with reassign_to=3
|
||||
Then the article 10 credits 5, 3, 6 in that order
|
||||
|
||||
Scenario: A reassignment never duplicates an author on an article
|
||||
Given the article 10 credits the authors 2 then 3
|
||||
When the owner deletes the author 2 with reassign_to=3
|
||||
Then the article 10 credits only the author 3
|
||||
|
||||
Scenario: Nobody removes the byline
|
||||
Given the article 10 credits only the author 2
|
||||
When the owner sends DELETE /v1/author/2?reassign_to=none
|
||||
Then the status is 204
|
||||
And the article 10 has no authors
|
||||
And the article 10 still exists, unchanged otherwise
|
||||
|
||||
Scenario: Only the deleted author is removed from a shared article
|
||||
Given the article 11 credits the authors 5, 2, 6 in that order
|
||||
When the owner sends DELETE /v1/author/2?reassign_to=none
|
||||
Then the article 11 credits 5, 6 in that order
|
||||
|
||||
Scenario: Reassign and delete are all-or-nothing
|
||||
Given the repository fails while deleting the author 2
|
||||
When the owner sends DELETE /v1/author/2?reassign_to=3
|
||||
Then the credits of the author 2 are unchanged
|
||||
And the author 2 still exists
|
||||
|
||||
Scenario: The credits are moved by one repository operation
|
||||
When the owner deletes an author with articles and a valid reassign_to
|
||||
Then the use case calls a single repository operation that moves the credits and deletes the author
|
||||
|
||||
Scenario Outline: An unusable destination
|
||||
Given the author 2 is credited on 3 articles
|
||||
When the owner sends DELETE /v1/author/2?reassign_to=<reassign_to>
|
||||
Then the status is <status>
|
||||
And the body is "<body>"
|
||||
And nothing changed
|
||||
|
||||
Examples:
|
||||
| reassign_to | status | body |
|
||||
| 999 | 404 | author_not_found |
|
||||
| 2 | 400 | invalid_reassign |
|
||||
| abc | 400 | invalid_reassign |
|
||||
| -1 | 400 | invalid_reassign |
|
||||
| (empty) | 400 | invalid_reassign |
|
||||
|
||||
Scenario: A linked author can be deleted and the account is untouched
|
||||
Given the author 2 is linked to the user 3 and credits no article
|
||||
When the owner deletes the author 2
|
||||
Then the user 3 still exists and can create an author again
|
||||
|
||||
Scenario: A missing author is not found
|
||||
When the owner sends DELETE /v1/author/999
|
||||
Then the status is 404
|
||||
And the body is "author_not_found"
|
||||
|
||||
Scenario: An unused reassign_to is ignored
|
||||
Given the author 2 credits no article
|
||||
When the owner sends DELETE /v1/author/2?reassign_to=3
|
||||
Then the status is 204
|
||||
And the author 3 is unchanged
|
||||
|
||||
Scenario Outline: Other roles and keys cannot delete
|
||||
When DELETE /v1/author/2 is sent with <credentials>
|
||||
Then the status is 403
|
||||
And the body is "<body>"
|
||||
And no author changed
|
||||
|
||||
Examples:
|
||||
| credentials | body |
|
||||
| a verified account with another role | Only owners and admins can do this. |
|
||||
| a valid API key | This action needs a real session. |
|
||||
|
||||
Scenario: A role without author rights cannot delete its own author
|
||||
Given the account is linked to the author 4
|
||||
When it sends DELETE /v1/author/4
|
||||
Then the status is 403 with body "Only owners and admins can do this."
|
||||
|
||||
Scenario: An admin can delete
|
||||
When a verified admin sends DELETE /v1/author/2 on an author without articles
|
||||
Then the status is 204
|
||||
|
||||
Rule: Only owner and admin write other people's authors
|
||||
|
||||
Scenario Outline: Refused writes change nothing
|
||||
When <request> is sent with <credentials>
|
||||
Then the status is 403
|
||||
And the body is "<body>"
|
||||
And no author changed
|
||||
|
||||
Examples:
|
||||
| request | credentials | body |
|
||||
| POST /v1/author/ | a verified account with another role | Only owners and admins can do this. |
|
||||
| POST /v1/author/ | a valid API key | This action needs a real session. |
|
||||
| PATCH /v1/author/2 | a verified account with another role | author_rights |
|
||||
|
||||
Rule: Articles credit authors in order
|
||||
|
||||
Scenario: An article is credited with ordered authors
|
||||
Given the authors 5, 6, 7 exist and the article 8 has none
|
||||
When the user sends PATCH /v1/article/8 with {"author_ids": [6, 5, 7]}
|
||||
Then the status is 200
|
||||
And the article body's authors are 6, 5, 7 in that order
|
||||
And the first is the primary byline
|
||||
|
||||
Scenario: The author list is replaced and can be emptied
|
||||
Given the article 8 credits 5, 6
|
||||
When the user sends PATCH /v1/article/8 with {"author_ids": [6]}
|
||||
Then the article 8 credits only 6
|
||||
When the user sends PATCH /v1/article/8 with {"author_ids": []}
|
||||
Then the article 8 has authors []
|
||||
|
||||
Scenario: Reordering changes the positions
|
||||
Given the article 8 credits 5, 6, 7
|
||||
When the user sends PATCH /v1/article/8 with {"author_ids": [7, 5, 6]}
|
||||
Then GET /v1/article/8 lists the authors 7, 5, 6
|
||||
|
||||
Scenario Outline: Any account that can edit the article sets its authors
|
||||
When PATCH /v1/article/8 is sent with {"author_ids": [5]} and <credentials>
|
||||
Then the status is 200
|
||||
|
||||
Examples:
|
||||
| credentials |
|
||||
| the owner's jwt cookie |
|
||||
| a verified admin's jwt cookie |
|
||||
| a verified account with another role |
|
||||
| a valid API key |
|
||||
|
||||
Scenario: The authors and the other fields change together
|
||||
When the user sends PATCH /v1/article/8 with {"body": "New", "site_id": 2, "author_ids": [5]}
|
||||
Then the body, the site_id and the authors are all updated
|
||||
|
||||
Scenario: An update without author_ids keeps the authors
|
||||
Given the article 8 credits 5, 6
|
||||
When the user sends PATCH /v1/article/8 with {"body": "New"}
|
||||
Then the article 8 still credits 5, 6 in that order
|
||||
|
||||
Scenario Outline: An unusable author_ids is refused
|
||||
When the user sends PATCH /v1/article/8 with {"author_ids": <value>}
|
||||
Then the status is <status>
|
||||
And the body is "<body>"
|
||||
And the article is unchanged
|
||||
|
||||
Examples:
|
||||
| value | status | body |
|
||||
| [999] | 404 | author_not_found |
|
||||
| [5, 999] | 404 | author_not_found |
|
||||
| [5, 5] | 400 | apperr.BodyErrorMessage |
|
||||
| null | 400 | apperr.BodyErrorMessage |
|
||||
| "a" | 400 | apperr.BodyErrorMessage |
|
||||
| [-1] | 400 | apperr.BodyErrorMessage |
|
||||
| [0] | 400 | the validator error text |
|
||||
|
||||
Scenario: A refused update changes no authors
|
||||
Given the article 8 credits 5
|
||||
When the user sends PATCH /v1/article/8 with {"body": "New", "author_ids": [999]}
|
||||
Then the status is 404
|
||||
And the article 8 body is unchanged and it still credits 5
|
||||
|
||||
Scenario: An unchanged list records nothing
|
||||
Given the article 8 credits 5, 6
|
||||
When the user sends PATCH /v1/article/8 with {"author_ids": [5, 6]}
|
||||
Then the status is 200
|
||||
And no activity event is recorded
|
||||
|
||||
Scenario: An article without authors can be published
|
||||
Given the article 8 has no authors and is offline
|
||||
When the user sends PATCH /v1/article/8/publish
|
||||
Then the status is 200
|
||||
And the article is online
|
||||
|
||||
Scenario Outline: Article reads carry the ordered authors
|
||||
Given the article 8 credits the authors 6 then 5
|
||||
When <request> is sent
|
||||
Then the article in the response has "authors" listing 6 then 5 with only id, name, slug, bio, avatar_id, website and social_links
|
||||
|
||||
Examples:
|
||||
| request |
|
||||
| GET /v1/article/8 |
|
||||
| GET /v1/article/ (each item of items) |
|
||||
| POST /v1/article |
|
||||
| PATCH /v1/article/8 |
|
||||
| PATCH /v1/article/8/publish |
|
||||
| PATCH /v1/article/8/unpublish |
|
||||
|
||||
Scenario: An article without authors returns an empty list
|
||||
When GET /v1/article/8 is sent on an article with no authors
|
||||
Then "authors" is []
|
||||
|
||||
Scenario: Anonymous readers see the authors of online articles
|
||||
Given the article 9 is online and credits the linked author 5
|
||||
When a caller without credentials sends GET /v1/article/9
|
||||
Then the authors are returned
|
||||
And the body has no user_id, no user_email and no article_count in any author
|
||||
|
||||
Scenario: An offline article is still not found publicly
|
||||
When a caller without a verified account sends GET /v1/article/{offline id}
|
||||
Then the status is 404 with body "Article not found"
|
||||
|
||||
Scenario: A new article defaults to the creator's author
|
||||
Given the caller is linked to the author 5
|
||||
When it sends POST /v1/article with {"title": "Spring release", "body": "Hello"}
|
||||
Then the article is offline
|
||||
And its authors are [5]
|
||||
|
||||
Scenario: A creator without an author creates an article without authors
|
||||
Given the caller has no author
|
||||
When it sends POST /v1/article with {"title": "Spring release", "body": "Hello"}
|
||||
Then its authors are []
|
||||
|
||||
Scenario: Deleting an article removes its credits and keeps the author
|
||||
Given the article 8 credits the author 5, who credits 2 articles
|
||||
When the article 8 is deleted
|
||||
Then the author 5 still exists with article_count 1
|
||||
|
||||
Scenario: article_count counts offline articles too
|
||||
Given the author 5 credits one online and one offline article
|
||||
Then the author 5 has article_count 2
|
||||
|
||||
Scenario: The list filter and counts are unaffected
|
||||
When GET /v1/article/?status=online&q=spring is sent
|
||||
Then the items and counts are as before this slice, with authors on each item
|
||||
|
||||
Rule: The current user carries the linked author
|
||||
|
||||
Scenario: GET /v1/auth/me includes the linked author
|
||||
Given the caller is linked to the author 5
|
||||
When GET /v1/auth/me is sent
|
||||
Then the body has the existing user fields and "author" holding the author 5 (id, name, slug, bio, avatar_id, website, social_links, article_count) with no user_email
|
||||
|
||||
Scenario: A user without an author has author null
|
||||
When GET /v1/auth/me is sent by an account without an author
|
||||
Then "author" is null
|
||||
|
||||
Scenario: The field follows link changes
|
||||
Given the caller was unlinked by an admin
|
||||
When GET /v1/auth/me is sent
|
||||
Then "author" is null
|
||||
|
||||
Scenario: The existing fields are unchanged
|
||||
When GET /v1/auth/me is sent
|
||||
Then the body still has id, username, email, is_verified, created_at, updated_at, display_name and role
|
||||
And no password, token or code is present
|
||||
|
||||
Scenario: An API key reads the same body
|
||||
When GET /v1/auth/me is sent with a valid API key
|
||||
Then "author" is present as for a session
|
||||
|
||||
Rule: Media usage by avatars
|
||||
|
||||
Scenario: An image used as an avatar is counted as used
|
||||
Given the image 5 is the avatar of the author 2 and appears in no article or site
|
||||
When a verified account looks up the usage of the image 5
|
||||
Then used_in counts the author and the image is not "Unused"
|
||||
|
||||
Scenario: The media list counts the author
|
||||
Given the image 5 is used by an article, a site and an author
|
||||
When a verified account sends GET /v1/media/
|
||||
Then the used_in of the image 5 is 3
|
||||
|
||||
Scenario: Deleting the image clears the author's avatar
|
||||
When the owner deletes the image 5
|
||||
Then the status is 204
|
||||
And the author 2 has avatar_id null
|
||||
|
||||
Scenario: Merging copies repoints the author
|
||||
Given the image 6 is a copy of the image 5 and the author 2 uses the image 6
|
||||
When the copies are merged into the image 5
|
||||
Then the author 2 has avatar_id 5
|
||||
And the merge response reports authors_updated 1
|
||||
|
||||
Scenario: Purge repoints authors the same way
|
||||
Given a purge group whose kept image is 5 and whose duplicate 6 is used by the author 2
|
||||
When the purge runs
|
||||
Then the author 2 has avatar_id 5
|
||||
And the purge result reports authors_updated 1
|
||||
|
||||
Scenario: A failed purge group leaves the author pointing at an existing image
|
||||
Given the purge of a group fails midway
|
||||
Then every author avatar_id refers to an image that still exists
|
||||
|
||||
Scenario: The usage lookup stays an array and later gains additive keys
|
||||
When a verified account looks up the usage of an image
|
||||
Then the response is a JSON array whose article items keep id, title and published
|
||||
And features/seo_data_backend.feature adds type and fields to every item and lists authors and sites, without removing any key
|
||||
|
||||
Rule: Every author write is recorded in the activity log
|
||||
|
||||
Scenario Outline: A successful write is recorded once after the change
|
||||
When <actor> performs <request>
|
||||
Then one event exists with action "<action>", category "authors", target {"type": "author", "id": "<id>", "name": "<name>"}, outcome "success", actor <actor> and source "web"
|
||||
And the event was recorded after the change was applied
|
||||
|
||||
Examples:
|
||||
| actor | request | action | id | name |
|
||||
| the owner | POST /v1/author/ for "Camille Roche" | author.create | 2 | Camille Roche |
|
||||
| the caller | POST /v1/author/me for "Marta Alves" | author.create | 3 | Marta Alves |
|
||||
| the owner | PATCH /v1/author/2 renaming it | author.edit | 2 | Camille R. |
|
||||
| the owner | PATCH /v1/author/2 linking the user "marta" | author.edit | 2 | Camille R. |
|
||||
| the owner | DELETE /v1/author/2 | author.delete | 2 | Camille R. |
|
||||
|
||||
Scenario: The change fields are limited and carry no email
|
||||
When the owner edits an author's name, slug, bio, website, social links, avatar and linked user
|
||||
Then the changes use only the fields name, slug, bio, website, social_links, avatar and user
|
||||
And the user change holds usernames, never an email
|
||||
|
||||
Scenario: An own-author edit by a role without author rights is recorded
|
||||
When the account with another role edits its own author
|
||||
Then one event "author.edit" exists with that account as actor
|
||||
|
||||
Scenario Outline: A refused write is recorded as failed with a plain reason
|
||||
When the actor performs <request> which is refused with <code>
|
||||
Then one event exists with action "<action>", outcome "failed" and failure_reason "<reason>"
|
||||
|
||||
Examples:
|
||||
| request | code | action | reason |
|
||||
| POST /v1/author/ with a taken slug | author_slug_taken | author.create | That slug is already used by another author. |
|
||||
| POST /v1/author/me by a linked caller | user_already_linked | author.create | That user already has an author. |
|
||||
| PATCH /v1/author/2 with a taken slug | author_slug_taken | author.edit | That slug is already used by another author. |
|
||||
| PATCH /v1/author/2 linking a linked user | user_already_linked | author.edit | That user already has an author. |
|
||||
| PATCH /v1/author/2 by a non-admin on it | author_rights | author.edit | Only an owner or admin can change this author. |
|
||||
| DELETE /v1/author/2 with articles | author_has_articles | author.delete | The author is still credited on articles. |
|
||||
| DELETE /v1/author/2 reassigned to itself | invalid_reassign | author.delete | The destination author is not valid. |
|
||||
| POST /v1/author/ when the repository fails with "db is locked" | 500 | author.create | Something went wrong on our side. Please try again. |
|
||||
| DELETE /v1/author/2 when the repository fails | 500 | author.delete | Something went wrong on our side. Please try again. |
|
||||
|
||||
Scenario Outline: Nothing is recorded when there is nothing to attribute
|
||||
When <request> is sent
|
||||
Then no activity event is recorded
|
||||
|
||||
Examples:
|
||||
| request |
|
||||
| PATCH /v1/author/999 as the owner |
|
||||
| DELETE /v1/author/999 as the owner |
|
||||
| POST /v1/author/ with an unknown avatar (image_not_found) |
|
||||
| POST /v1/author/ with a bio over 280 characters |
|
||||
| POST /v1/author/ as a role without author rights (403) |
|
||||
| POST /v1/author/ with no credentials (401) |
|
||||
| PATCH /v1/author/abc as the owner |
|
||||
| POST /v1/author/ with a malformed body |
|
||||
|
||||
Scenario: A failing audit repository never changes the response
|
||||
Given the audit repository fails on Append
|
||||
When the owner sends POST /v1/author/ with valid values
|
||||
Then the response equals that of a healthy repository
|
||||
And the author was created
|
||||
|
||||
Scenario: Reads are never recorded
|
||||
When GET /v1/author/ is sent
|
||||
Then no activity event is recorded
|
||||
|
||||
Scenario: An article's authors change is recorded in article.edit
|
||||
Given the article 8 "Spring release" credits "Inès Duarte" and "Marta Alves"
|
||||
When the user sends PATCH /v1/article/8 with {"author_ids": [Marta, Inès, Zoe]}
|
||||
Then one event "article.edit" exists with changes [{"field": "authors", "from": "Inès Duarte, Marta Alves", "to": "Marta Alves, Inès Duarte, Zoe Lambert"}]
|
||||
|
||||
Scenario: Deleting an author with reassignment records only the author event
|
||||
When the owner deletes the author 2 with reassign_to=3 on 3 articles
|
||||
Then exactly one event "author.delete" exists
|
||||
And no "article.edit" event exists
|
||||
|
||||
Scenario: The activity API lists author events
|
||||
Given author events were recorded
|
||||
When a verified account sends GET /v1/activity/?category=authors
|
||||
Then the author events are returned with category "authors" and no other category
|
||||
|
||||
Rule: Persistence and migration
|
||||
|
||||
Scenario: The new tables are migrated
|
||||
When database.Migrate runs on an empty database
|
||||
Then the authors and article_authors tables exist
|
||||
And the authors table has unique indexes on slug and on user_id, where many NULL user_id values are allowed
|
||||
And article_authors has a unique pair (article_id, author_id) and a position
|
||||
|
||||
Scenario: Existing articles get no authors
|
||||
Given a database from before this slice holding 4 articles
|
||||
When database.Migrate runs
|
||||
Then all 4 articles have no authors and no author is created
|
||||
|
||||
Scenario: It works on every database driver
|
||||
When the repository contract suite runs
|
||||
Then the author repository behaves the same on SQLite, MySQL and PostgreSQL
|
||||
And the SQLite schema test accounts for the new tables
|
||||
|
||||
Scenario: Order is stable
|
||||
Given the article 8 credits 7, 5, 6
|
||||
When it is read back from the repository
|
||||
Then the authors come back as 7, 5, 6
|
||||
|
||||
Rule: Total in X-Total-Count
|
||||
|
||||
Background:
|
||||
Given GET /v1/author/ keeps its {"items","total","page","size"} body and also sends total in the X-Total-Count header on every 200
|
||||
And the header equals the body total
|
||||
And X-Total-Count is already in the CORS ExposedHeaders
|
||||
And a refused request sends no X-Total-Count
|
||||
|
||||
Scenario: The total is also sent as a header
|
||||
Given 30 authors
|
||||
When a verified account sends GET /v1/author/?size=5
|
||||
Then the body total is 30 and the header X-Total-Count is "30"
|
||||
|
||||
Scenario: The header follows the search
|
||||
Given 30 authors of which 7 match "mar"
|
||||
When a verified account sends GET /v1/author/?q=mar
|
||||
Then X-Total-Count is "7" and the body total is 7
|
||||
|
||||
Scenario: A page past the end keeps the total in the header
|
||||
Given 30 authors
|
||||
When a verified account sends GET /v1/author/?page=3&size=100
|
||||
Then items is [], the body total is 30 and X-Total-Count is "30"
|
||||
|
||||
Scenario: No match
|
||||
When a verified account sends GET /v1/author/?q=nobody
|
||||
Then items is [], the body total is 0 and X-Total-Count is "0"
|
||||
|
||||
Scenario Outline: Every reader gets the header
|
||||
When GET /v1/author/ is sent with <credentials>
|
||||
Then the status is 200 and X-Total-Count equals the body total
|
||||
|
||||
Examples:
|
||||
| credentials |
|
||||
| the owner's jwt cookie |
|
||||
| a verified admin's jwt cookie |
|
||||
| a verified account with another role |
|
||||
| a valid API key |
|
||||
|
||||
Scenario Outline: Refused requests send no header
|
||||
When GET /v1/author/?<params> is sent with <credentials>
|
||||
Then the status is <status> and no X-Total-Count is sent
|
||||
|
||||
Examples:
|
||||
| params | credentials | status |
|
||||
| size=30 | a verified account | 400 |
|
||||
| page=0 | a verified account | 400 |
|
||||
| page=abc | a verified account | 400 |
|
||||
| | an unverified account's jwt cookie | 403 |
|
||||
| | no credentials | 401 |
|
||||
|
||||
Scenario: CORS exposes the header
|
||||
Given CORS_ALLOWED_ORIGINS includes "https://app.example.com"
|
||||
When a preflighted GET /v1/author/ comes from that origin
|
||||
Then Access-Control-Expose-Headers lists X-Total-Count
|
||||
|
||||
Rule: Documentation
|
||||
|
||||
Scenario: The docs describe the new surface
|
||||
Then docs/api.md names X-Total-Count on the GET /v1/author/ row
|
||||
And docs/api.md documents the /v1/author routes with auth and roles, the error tokens, the author shape, article author_ids and authors, the author field of /v1/auth/me and the authors_updated media field
|
||||
And docs/architecture.md mentions the author aggregate, its repository and its use cases
|
||||
@@ -0,0 +1,118 @@
|
||||
# QA procedure: Authors backend
|
||||
|
||||
Spec: `features/authors_backend.feature`. Go tests only, in `test/` (package `test`), run with `task test`. No live server, no real SMTP, no real SQLite file outside the temp-dir repository-contract harness. Call `validator.InitValidator()` before any handler call. Every error assertion compares the plain-text body to the exact code token or constant named in the spec.
|
||||
|
||||
## Setup
|
||||
|
||||
- New files `test/author_*_test.go`. Fakes have unique names: `mockAuthorRepo` (authors, slug and user_id uniqueness, article counts, ordered article credits, the reassign-and-delete as one recorded operation, failure and unique-violation injection), `mockAuthorUserRepo` (users with ids, usernames, display names, emails and roles), `mockAuthorImageRepo` (images, avatar usage, merge and purge repointing), and an extended `mockArticleRepo` (ordered author credits, create with default author, delete removes credits). A fake audit repository with fail and panic switches is reused.
|
||||
- Routers mirror `api/router.go`: a new `NewAuthorRouter`, plus the article, auth (`/me`), media and activity routers. Protected routes sit behind `jwtauth.Verifier` + `jwtauth.Authenticator` with a test `jwtauth.New("HS256", ...)`. Requests carry signed `jwt` cookies with the `user_id` claim for: an owner, an admin, a verified account whose role is `"editor"` (a value other than owner or admin, because no third role exists yet), and an unverified account. An API-key request uses the key authentication path.
|
||||
- Helper builders create authors, link users and credit articles directly in the fakes; assertions read the fakes, never the JSON alone.
|
||||
|
||||
## A. Reading
|
||||
|
||||
1. Newest-first list with `total`, `page`, `size` and `article_count`.
|
||||
2. Credentials table: owner, admin, "editor" and API key give 200; unverified gives 403; none gives 401.
|
||||
3. `q` table: name, slug, case-insensitive, no match gives total 0.
|
||||
4. Pagination table: page 2 of 30, size 5, out-of-range page gives empty items, `size=30`, `page=0`, `page=abc` give 400 `apperr.BodyErrorMessage`.
|
||||
5. Email visibility: owner and admin see `user_email`; "editor" gets a body without any `user_email` key or the email string (substring check on the raw body).
|
||||
6. Guest author: `is_linked` false, `user_id` null. Null and empty defaults for avatar, website, bio, links.
|
||||
|
||||
## B. Creating
|
||||
|
||||
7. Owner and admin create: 201, full body, stored, `article_count` 0, `is_linked` false.
|
||||
8. Only the name given: generated slug, defaults.
|
||||
9. Slug generation table (accents folded, punctuation runs, `!!!` gives `author`).
|
||||
10. Generated and explicit taken slug: 409 `author_slug_taken`, nothing stored. Repository unique-violation injection gives the same 409.
|
||||
11. Validation table (name, slug, bio, website, links, link type, avatar) with exact status and token; 422 rows assert the token; boundary table (100-character name and slug, 280 characters and 280 multi-byte characters, 5 links, two custom links, empty website).
|
||||
12. Malformed JSON gives 400 `apperr.BodyErrorMessage`; "editor" with malformed JSON still gets 403 "Only owners and admins can do this.".
|
||||
13. `user_id` on create: success, 404 `user_not_found`, 409 `user_already_linked`.
|
||||
|
||||
## C. Own author (`POST /me`)
|
||||
|
||||
14. Naming table: display name, then username fallback; `user_id` is the caller's; `is_linked` true.
|
||||
15. Owner, admin and "editor" all get 201.
|
||||
16. Slug de-duplication: `marta-alves-2` taken, result `-3`; the 100-character slug case stays within 100 and ends with `-2`.
|
||||
17. Already linked: 409 `user_already_linked`, nothing added; unique-violation injection on `user_id` gives the same 409.
|
||||
18. API key gives 403 "This action needs a real session."; unverified gives the existing 403; none gives 401.
|
||||
|
||||
## D. Editing
|
||||
|
||||
19. Full edit by owner; partial edit keeps absent fields; nullable clear table (avatar, website null and "", links [], bio "").
|
||||
20. Avatar set; social links replaced as a whole.
|
||||
21. Validation table like creation; own slug re-sent is 200; another author's slug is 409; unchanged author after each refusal.
|
||||
22. `{}`, unknown-only and `{"name": null}` give 400 `apperr.BodyErrorMessage`; missing author 404 `author_not_found`; `abc` id gives `apperr.IdUint32ErrorMessage`.
|
||||
23. No-op edit: 200 and no audit event.
|
||||
24. "editor" table: own author 200 (also name, slug, avatar, links); another author 403 `author_rights`; missing id 404; `user_id` in the body of its own author 403 `author_rights` and still linked; API key gives 403 "This action needs a real session."
|
||||
|
||||
## E. Linking and unlinking
|
||||
|
||||
25. Link a guest author: 200, `user_email` visible to the owner.
|
||||
26. Table: linked user gives 409 `user_already_linked`; already-linked author gives 409 `author_already_linked`; same user is a 200 with no event; unknown user gives 404 `user_not_found`.
|
||||
27. Unlink: 200, `is_linked` false, no `user_email`; the user can create an author again; the author keeps its article credits; unlinking a guest is a no-op with no event.
|
||||
28. After unlinking, an article created by that user has no authors.
|
||||
|
||||
## F. Deleting
|
||||
|
||||
29. No articles: 204. With articles and no `reassign_to`: 409 `author_has_articles`, unchanged.
|
||||
30. Reassign: credits move, author gone; position is preserved (5, 2, 6 becomes 5, 3, 6); no duplicate when the target already credits the article (2, 3 becomes 3).
|
||||
31. `none`: only that author is removed from shared articles, order of the rest is kept; articles with only that author end with none and still exist.
|
||||
32. Single repository operation (the fake records one call). Failure injected in it leaves credits and author unchanged.
|
||||
33. `reassign_to` table: 999 gives 404 `author_not_found`; own id, `abc`, `-1`, empty give 400 `invalid_reassign`. Unused valid `reassign_to` on an author without articles gives 204 and leaves the destination untouched. Missing author gives 404.
|
||||
34. Linked author deleted: user still exists and can create again.
|
||||
35. Refusals: "editor" gives 403 "Only owners and admins can do this." including on its own author; API key gives 403 "This action needs a real session."; admin gives 204.
|
||||
|
||||
## G. Articles
|
||||
|
||||
36. `author_ids` PATCH sets, replaces, empties and reorders; reads (GET one, GET list, POST, PATCH, publish, unpublish) carry `authors` in order with only the seven public fields; empty is `[]`.
|
||||
37. Callers table: owner, admin, "editor", API key all give 200.
|
||||
38. Combined PATCH with `body` and `site_id`; omission keeps the authors; a refused `author_ids` (404) leaves body and credits unchanged.
|
||||
39. Unusable table: `[999]`, `[5,999]` 404 `author_not_found`; `[5,5]`, `null`, `"a"`, `[-1]` give 400 `apperr.BodyErrorMessage`; `[0]` gives the validator error text. The article is unchanged in every case.
|
||||
40. Unchanged list is 200 with no event. Publishing an article with no authors succeeds.
|
||||
41. Anonymous read of an online article includes `authors` but no `user_id`, `user_email` or `article_count` (substring check); an offline article is 404 "Article not found".
|
||||
42. Creation default: creator with a linked author gets `[author]`; creator without one gets `[]`; the article is offline.
|
||||
43. Deleting an article removes its credits and keeps the author, `article_count` drops; `article_count` counts offline articles.
|
||||
44. List filters (`status`, `q`, `site`) and `counts` are unchanged apart from `authors` on each item.
|
||||
|
||||
## H. Current user
|
||||
|
||||
45. `/v1/auth/me` returns `author` for a linked caller (seven public fields plus `article_count`, no `user_email`) and null otherwise, null again after an unlink; existing fields are unchanged and no secret appears; API key request returns the same shape.
|
||||
|
||||
## I. Media
|
||||
|
||||
46. Usage lookup counts an avatar, stays a JSON array whose article items keep id, title and published (additive keys are specified in seo_data_backend), image not "Unused". Media list `used_in` sums article, site and author usage.
|
||||
47. Deleting the image (204) nulls `avatar_id`.
|
||||
48. Merge repoints authors and reports `authors_updated`; purge does the same; a failed purge group leaves every `avatar_id` pointing at an existing image.
|
||||
|
||||
## J. Activity log
|
||||
|
||||
49. Success table: one event per write with action, category "authors", target type "author", actor, source "web", recorded after the change (including `/me`).
|
||||
50. Change fields are limited to name, slug, bio, website, social_links, avatar, user; the user change shows usernames and no email (substring check on the stored event).
|
||||
51. Failed table with the plain reasons; unknown ids, 403, 401, 422 and other validation refusals and malformed requests record nothing; reads record nothing.
|
||||
52. Failing and panicking audit repository leave the response and the change as with a healthy one.
|
||||
53. `article.edit` with an authors change holds `{"field":"authors","from":"Inès Duarte, Marta Alves","to":"Marta Alves, Inès Duarte, Zoe Lambert"}`; delete with reassignment records one `author.delete` and no `article.edit`.
|
||||
54. `GET /v1/activity/?category=authors` returns only author events for a verified session (an API key gets the route's existing session refusal). Failure reasons use the style of `auditFailures.go`: the author sentinels map to the plain sentences of the feature and any other error gives `GenericFailureReason`.
|
||||
|
||||
## K. Persistence and migration
|
||||
|
||||
55. Repository-contract harness (temp-dir SQLite; MySQL and Postgres opt-in through the existing env switches): author repository contract (CRUD, slug and user uniqueness with many NULL users, search, newest-first pagination, ordered credits and stable read-back, unique (article, author) pair, transactional reassign-and-delete incl. the no-duplicate and position rules). `database.Migrate` creates both tables and leaves existing articles without authors; `test/sqlite_schema_unchanged_test.go` is updated for the new tables.
|
||||
|
||||
## L. Quality gates
|
||||
|
||||
56. Layering guard: use cases import no persistence, mailer, models, gorm, net/http or chi; the domain author package imports no GORM or HTTP; handlers import no persistence; validation uses validate tags and `validator.Validate.Struct`; no comments added.
|
||||
57. Scoped mutation run through `task mutate` only, for example `MUTATE_FILES=<author and article use case files> MUTATE_RUN='TestAuthor' MUTATE_WORKERS=2 task mutate -- <use case package path>`; report LIVED and NOT COVERED mutants; re-check filtered suspects without `MUTATE_RUN`. Also run `task lint:go` and `task fmt`.
|
||||
58. Docs, checked by reading the files: docs/api.md documents the five /v1/author routes (GET, POST, POST /me, PATCH, DELETE) with auth and roles, error tokens, the author and article-author shapes, `author_ids`, the `/auth/me` `author` field and `authors_updated`; docs/architecture.md names the author aggregate, repository and use cases.
|
||||
|
||||
## M. X-Total-Count (Go, `test/`, `task test`)
|
||||
|
||||
59. On the same `mockAuthorRepo` and router as item 4, assert `X-Total-Count` equals the decoded body `total` for: size=5 of 30, `q=mar` with 7 matches, `page=3&size=100` (items empty, total 30), `q=nobody` (0), and for owner, admin, "editor" and API key. Assert the header is absent for `size=30`, `page=0`, `page=abc`, unverified (403) and none (401). The body assertions of item 4 stay unchanged.
|
||||
60. On the SQLite contract harness, the author list total (and so the header) follows `q` and does not depend on `page`/`size`; `task test:mysql` and `task test:postgres` run the same case.
|
||||
61. CORS preflight from an allowed origin exposes `X-Total-Count`.
|
||||
62. Scoped `task mutate` on the author list use case and handler files only. `docs/api.md` author row and `web/src/data/apiCatalogue.ts` (`X-Total-Count` response header on `GET /v1/author/`) with its spec, read by hand. No comment added.
|
||||
|
||||
## Manual
|
||||
|
||||
- MySQL and Postgres: run the contract suite with the opt-in env vars against real servers.
|
||||
- Real boot with an old database copy: both new tables appear, articles keep working with no authors, second boot changes nothing.
|
||||
- Docker with the `/data` volume: same boot check.
|
||||
- Read the activity log screen and the CSV export: author events show names, failure reasons and no emails.
|
||||
- Not covered here: the SPA (later slices).
|
||||
@@ -0,0 +1,538 @@
|
||||
Feature: Editor: search and sharing, suggestions and "What the frontend gets"
|
||||
|
||||
As a RenewCMS user who can edit articles
|
||||
I want to fill in an article's search and sharing data, see suggestions and previews, and see what the frontend receives
|
||||
So that the API returns good SEO data for every article without blocking me from saving or publishing
|
||||
|
||||
Background:
|
||||
Given the screen is EditorView (/article/:id/edit) inside DashboardShell, per docs/design/routes.md
|
||||
And the visual spec of record is docs/design/screens/editor.md (groups "Editor: search and sharing" with 24 states and "Editor: what the frontend gets" with 6 states), docs/design/seo-slices.md, docs/design/components.md (SearchSharingSection, SeoPanel, SoftCounter, SearchPreview, SocialCardPreview, SuggestionList, ApiPreviewDialog, SlugField, MediaField) and docs/design/states.md ("SEO round"). Exact copy is read from those files and is not repeated here unless a scenario needs it
|
||||
And the board frames of docs/design/source/RenewCMS Screens Back-office.dc.html, AppFrame.dc.html and DirectoryFrame.dc.html are the layout tiebreaker
|
||||
And this slice is SPA only and reuses the API of features/seo_data_backend.feature and features/seo_output_backend.feature without change
|
||||
And the SPA calls, with relative URLs through useApi only: GET /v1/article/{id} and PATCH /v1/article/{id} (SEO fields slug, excerpt, seo_title, seo_description, cover_image_id, cover_image_alt, social_title, social_description, social_image_id, canonical_url, noindex), POST /v1/article/{id}/seo/check, GET /v1/article/{id}/seo, GET /v1/site/ and the media routes of the shared picker
|
||||
And POST /v1/article/{id}/seo/check takes the optional SEO fields (and body) of PATCH as overrides and answers {status, suggestions: [{code, field, params}], slug: {available, suggestion}} with status "ready", "suggestions" or "hidden"
|
||||
And the SPA never re-implements a suggestion rule. It renders the suggestions, the order and the status the check returns. The copy of each code lives in the SPA and has a French entry
|
||||
And the suggestion codes are title_long, title_empty, desc_short, desc_long, cover_alt, cover_none, slug_long, no_au, no_h, body_alt and short
|
||||
And a suggestion's field maps to a link label: seo_title "meta title", seo_description "meta description", cover_image_alt and cover_image_id "cover image", slug "URL slug", author_ids "authors", body "body"
|
||||
And the soft ranges of the counters are meta title 30 to 60 and description 70 to 160 (docs/design), and the social title has no counter. They colour a counter and never block
|
||||
And suggestions never disable Save, "Save and publish" or Publish
|
||||
And the sample article is 12, "How we price a bathroom renovation", online on the site Renew (renew.example, id 1), slug "how-we-price-a-bathroom-renovation", with no SEO field set, and the author "Inès Duarte"
|
||||
And the sample cover media is "north-wall.jpg" (the site social image) and the sample panel values are those of the board frames "Panel: filled in" and "Panel: outside the soft ranges"
|
||||
And every visible string goes through t(...) with the English text as the key and a French entry in web/src/i18n/messages.ts
|
||||
And the screen uses Nuxt UI components and design tokens only, with no raw colors, and no comment is added anywhere
|
||||
And a scenario tagged @not-in-design uses copy or behaviour that docs/design does not define: it takes the proposal of this feature, has a French entry, and is listed in the .qa.md to be fed back to the design
|
||||
|
||||
Rule: The "Search and sharing" section sits under "Site and authors", collapsed by default
|
||||
|
||||
Scenario: Position, in the sidebar and in the Details sheet
|
||||
Given article 12 is loaded and nothing is remembered for this browser
|
||||
When the user opens /article/12/edit on desktop
|
||||
Then the details sidebar shows a collapsed "Search and sharing" section directly under "Site and authors"
|
||||
And on mobile (390 px) the section is not visible until the Details sheet is opened, and inside the sheet it sits under "Site and authors"
|
||||
|
||||
Scenario Outline: The one-line summary follows the check
|
||||
Given the section is collapsed
|
||||
And POST /v1/article/12/seo/check answers <check>
|
||||
Then the summary line reads "<summary>" in <colour>
|
||||
|
||||
Examples:
|
||||
| check | summary | colour |
|
||||
| pending | Checking… | the muted colour |
|
||||
| status "ready", no suggestions | Ready | the muted colour |
|
||||
| status "suggestions", 1 suggestion | 1 suggestion | the warning colour |
|
||||
| status "suggestions", 2 suggestions | 2 suggestions | the warning colour |
|
||||
| status "hidden", 2 suggestions | Hidden from search | the muted colour |
|
||||
|
||||
Scenario: The existing Editor states show the section
|
||||
Then every editor state that has the details sidebar shows the collapsed section with "Ready"
|
||||
And the Loading state shows the section header with a skeleton summary, as for "Site and authors"
|
||||
And the Not found state shows no section
|
||||
|
||||
Scenario: The choice is remembered per browser, with its own key
|
||||
Given the section is collapsed by default
|
||||
When the user opens it and later opens another article in the same browser
|
||||
Then it is open there too
|
||||
When the user collapses it and reloads
|
||||
Then it is collapsed
|
||||
And the choice is kept in localStorage under its own key, independent of the "Site and authors" key, and nothing is sent to the API
|
||||
And the sidebar and the Details sheet share that key
|
||||
|
||||
Scenario Outline: A storage that throws never breaks the editor
|
||||
Given localStorage.<call> throws a SecurityError
|
||||
When the user opens the editor and toggles the section
|
||||
Then the editor renders, the section opens and closes for this page view, and no error reaches the user
|
||||
And reading falls back to "collapsed" and writing is silently skipped
|
||||
|
||||
Examples:
|
||||
| call |
|
||||
| getItem |
|
||||
| setItem |
|
||||
|
||||
Scenario: The section opens by itself when asked from elsewhere
|
||||
When the user activates "Edit search and sharing", "What the frontend gets" or a suggestion link
|
||||
Then the panel or the dialog opens whatever the stored choice is, and the stored choice is not changed
|
||||
|
||||
Rule: The open section: address, suggestions and actions
|
||||
|
||||
Scenario: Open and ready
|
||||
Given the section is open and the check answers status "ready"
|
||||
Then it shows "Address" with "renew.example/how-we-price-a-bathroom-renovation" (the host of the site's base_url, without the scheme, then the slug)
|
||||
And "All good" with "Nothing to suggest for this article."
|
||||
And the actions "Edit search and sharing" and "What the frontend gets"
|
||||
|
||||
Scenario: Open with suggestions, at most three
|
||||
Given the check answers title_long (74 characters), cover_alt, no_h and short, in that order
|
||||
Then exactly three suggestions are shown, in the order of the response, each with its message and a "Go to <field>" link: "Go to meta title", "Go to cover image", "Go to body"
|
||||
And a "+1 more in Search and sharing" action follows
|
||||
When the user activates "+1 more in Search and sharing"
|
||||
Then the panel opens with the suggestion list in view
|
||||
And with three suggestions or fewer no "+N more" action is shown
|
||||
|
||||
Scenario Outline: A suggestion link goes to its field
|
||||
Given the check answers a suggestion whose field is "<field>"
|
||||
When the user activates its "Go to <label>" link
|
||||
Then <result>
|
||||
|
||||
Examples:
|
||||
| field | label | result |
|
||||
| seo_title | meta title | the panel opens with focus on the meta title input |
|
||||
| seo_description | meta description | the panel opens with focus on the meta description |
|
||||
| cover_image_alt | cover image | the panel opens with focus on the alt text input |
|
||||
| cover_image_id | cover image | the panel opens with focus on the cover "Choose image" button |
|
||||
| slug | URL slug | the panel opens with focus on the slug field |
|
||||
| body | body | focus moves to the article body in the editor |
|
||||
| author_ids | authors | the "Site and authors" section opens and focus moves to its list |
|
||||
|
||||
Scenario Outline: Copy of the other codes, as the board draws it
|
||||
Given the check answers the code "<code>" with params <params>
|
||||
Then the message reads "<message>" and has a French entry
|
||||
|
||||
Examples:
|
||||
| code | params | message |
|
||||
| title_empty | {} | No meta title yet. The article title is used instead. |
|
||||
| desc_long | {"length": 170, "max": 160} | The description is 170 characters. Search engines may cut it off after about 160. |
|
||||
| cover_none | {} | No cover image. The site's social image is used. |
|
||||
| slug_long | {"length": 80, "max": 75} | The slug is 80 characters. Shorter addresses are easier to share. |
|
||||
| no_au | {} | This article has no authors, so the structured data has no author. |
|
||||
| body_alt | {"count": 2} | 2 images in the body have no alt text. |
|
||||
| short | {"length": 40, "min": 300} | The article is under 300 words. That is fine for a short note. |
|
||||
|
||||
Scenario Outline: The messages the design does draw use the params of the response
|
||||
Given the check answers the code "<code>" with params <params>
|
||||
Then the message reads "<message>"
|
||||
|
||||
Examples:
|
||||
| code | params | message |
|
||||
| title_long | {"length": 74, "max": 60} | The meta title is 74 characters. Search engines may cut it off after about 60. |
|
||||
| desc_short | {"length": 41, "min": 70} | The description is 41 characters. About 70 to 160 reads best in results. |
|
||||
| cover_alt | {} | The cover image has no alt text. Add a short description of it. |
|
||||
| no_h | {} | The body has no headings. H2 headings help readers scan the article. |
|
||||
|
||||
Scenario: Checking, with the rest of the section usable
|
||||
Given POST /v1/article/12/seo/check is pending
|
||||
Then the section shows "Checking this article…"
|
||||
And the address, "Edit search and sharing" and "What the frontend gets" stay usable
|
||||
|
||||
Scenario: Hidden from search
|
||||
Given the article has noindex true
|
||||
When the section is open
|
||||
Then it shows "Hidden from search engines. This only sets a flag in the API."
|
||||
|
||||
Scenario: Another site
|
||||
Given the article is on the site Journal (journal.renew.example)
|
||||
Then the address reads "journal.renew.example/how-we-price-a-bathroom-renovation"
|
||||
|
||||
@not-in-design
|
||||
Scenario Outline: The check could not run
|
||||
Given POST /v1/article/12/seo/check fails with <failure>
|
||||
Then the summary line is not shown as Ready and the section shows "Couldn't check this article." with "Try again"
|
||||
And no toast is shown and the article is unchanged
|
||||
When the user activates "Try again"
|
||||
Then the check is requested again
|
||||
|
||||
Examples:
|
||||
| failure |
|
||||
| status 500 |
|
||||
| a network error |
|
||||
|
||||
Scenario Outline: A session problem during the check follows the existing rules
|
||||
When POST /v1/article/12/seo/check answers <status>
|
||||
Then <result>
|
||||
|
||||
Examples:
|
||||
| status | result |
|
||||
| 401 | the user lands on /login?redirect=/article/12/edit&reason=expired, the draft is kept |
|
||||
| 404 | the "Not found" editor state is shown |
|
||||
|
||||
Rule: Suggestions and the slug check come from the server, after a pause in typing
|
||||
|
||||
Scenario: The first check runs when the editor loads
|
||||
When GET /v1/article/12 answers 200
|
||||
Then exactly one POST /v1/article/12/seo/check is sent with the body {}
|
||||
And no check is sent while GET /v1/article/12 is pending or fails
|
||||
|
||||
Scenario: Only changed fields are sent to the check
|
||||
Given the user changed the meta title to a 74-character text and nothing else
|
||||
When the check runs
|
||||
Then the POST body is {"seo_title": "<the 74 characters>"} and holds no other field
|
||||
|
||||
Scenario: An unsaved body edit is part of the check
|
||||
Given the user edited the body in the editor
|
||||
When the check runs
|
||||
Then the POST body holds "body" with the edited html, so no_h, body_alt and short reflect what is on screen
|
||||
|
||||
Scenario Outline: The check waits for a pause in typing
|
||||
Given the user types in <field>
|
||||
When the user keeps typing with less than the debounce delay between keystrokes
|
||||
Then no check is sent
|
||||
When the user pauses for the debounce delay
|
||||
Then exactly one POST /v1/article/12/seo/check is sent with the latest value
|
||||
And the suggestions refresh and the summary line follows
|
||||
|
||||
Examples:
|
||||
| field |
|
||||
| meta title |
|
||||
| meta description |
|
||||
| excerpt |
|
||||
| alt text |
|
||||
| social title |
|
||||
| canonical URL |
|
||||
| slug |
|
||||
|
||||
Scenario: A late answer never overwrites a newer one
|
||||
Given check A was sent, then check B after a further edit
|
||||
When B answers first and A answers later
|
||||
Then the suggestions and the status are those of B
|
||||
And when only A is still pending, the previous request is aborted
|
||||
|
||||
Scenario: Discrete changes check immediately
|
||||
When the user toggles "Hide from search engines", picks or removes a cover or a social image, or chooses "Use <slug>-2"
|
||||
Then one check is sent without waiting for the debounce delay
|
||||
|
||||
Scenario: Nothing is saved by a check
|
||||
Then no PATCH is sent by any check and the status stays unchanged
|
||||
|
||||
Scenario: The panel check state
|
||||
Given the panel is open and a check is pending
|
||||
Then the suggestions area shows "Checking this article…" and the fields stay usable
|
||||
|
||||
Rule: The panel (desktop slide-over, mobile 92% sheet)
|
||||
|
||||
Scenario: Opening
|
||||
When the user activates "Edit search and sharing" on desktop
|
||||
Then a slide-over 960 px wide opens with the title "Search and sharing", the fields, the previews, "Cancel" and "Save changes"
|
||||
And on mobile a sheet covering 92% of the height opens over the Details sheet, with the suggestions first, then the fields, then the two previews
|
||||
And a check is sent on open
|
||||
|
||||
Scenario: Defaults, every value is a fallback and says so
|
||||
Given the article has no SEO field set
|
||||
Then the panel shows "URL slug" with the Auto badge and "Generated from the title until you edit it."
|
||||
And "Meta title" with the chip "Using article title" and "Recommended 30 to 60 characters. This is a guide, not a limit."
|
||||
And "Meta description" with the chip "Using first sentence of the body" and "Recommended 70 to 160 characters."
|
||||
And "Excerpt" with "A short summary. It is also sent as the article teaser."
|
||||
And "Cover image" with "Using the site social image (north-wall.jpg)."
|
||||
And "Social sharing" collapsed with "Optional" and "Uses the meta values"
|
||||
And "Advanced" collapsed with "Canonical URL: automatic"
|
||||
And "Hide from search engines" off with "Sets noindex in the API. It doesn't change who can read the article."
|
||||
And "Search result", "Social card" and "Suggestions" blocks, "What the frontend gets", "Cancel" and "Save changes"
|
||||
|
||||
@not-in-design
|
||||
Scenario Outline: The other fallback chips
|
||||
Given <state>
|
||||
Then the chip reads "<chip>" and has a French entry
|
||||
|
||||
Examples:
|
||||
| state | chip |
|
||||
| no meta description but an excerpt | Using the excerpt |
|
||||
| no meta description, no excerpt, no body text | Using the site default description |
|
||||
| no cover and no site social image | No image |
|
||||
|
||||
Scenario: Filled in
|
||||
Given the article has its own meta title, description, excerpt, cover with alt text and the check answers no suggestion
|
||||
Then the fallback chips are gone and the suggestion block shows "All good" with "Nothing to suggest for this article."
|
||||
|
||||
Scenario Outline: Soft counters are a guide
|
||||
Given the user types <n> characters in <field>
|
||||
Then the counter reads "<n> / <max>" in the mono face and is <colour>
|
||||
And Save changes stays enabled and nothing is blocked
|
||||
|
||||
Examples:
|
||||
| field | n | max | colour |
|
||||
| meta title | 29 | 60 | amber (--ui-warning) |
|
||||
| meta title | 30 | 60 | neutral |
|
||||
| meta title | 60 | 60 | neutral |
|
||||
| meta title | 74 | 60 | amber (--ui-warning) |
|
||||
| meta description | 41 | 160 | amber (--ui-warning) |
|
||||
| meta description | 70 | 160 | neutral |
|
||||
| meta description | 160 | 160 | neutral |
|
||||
| meta description | 161 | 160 | amber (--ui-warning) |
|
||||
|
||||
Scenario: Outside the soft ranges
|
||||
Given the user typed the 74-character meta title and the 33-character description of the board
|
||||
Then both counters are amber and never red
|
||||
And the suggestion block shows the title_long and desc_short messages once the check answers
|
||||
And the search result preview shows the title cut off with "Cut off here, the way a search engine would."
|
||||
|
||||
Scenario: The API length limits are not reachable
|
||||
Given the API refuses seo_title above 120, seo_description above 320, cover_image_alt above 200, social_title above 120 and social_description above 320 characters
|
||||
Then each input stops accepting characters at its limit, so the API 400 for those fields is never produced by typing
|
||||
|
||||
Scenario: Excerpt over 300
|
||||
When the user types a 301-character excerpt
|
||||
Then the excerpt shows an inline error and "Save changes" is disabled until it is 300 or fewer
|
||||
And no request is sent for it
|
||||
|
||||
Scenario: Slug edited, Auto and Reset
|
||||
Given the slug is in Auto mode
|
||||
When the user activates the pencil
|
||||
Then the Auto badge is gone, the field is editable and "Reset to match the title" appears
|
||||
When the user activates "Reset to match the title"
|
||||
Then the field shows the slug generated from the title with the Auto badge, and the slug is sent as "" on save so that the API regenerates it
|
||||
And a check with {"slug": ""} confirms its availability
|
||||
|
||||
Scenario: Cover and alt text
|
||||
When the user activates "Choose image" in "Cover image"
|
||||
Then the shared Media picker opens titled "Choose a cover image" with "The cover for this article." and the action "Use image"
|
||||
When the user picks "north-wall.jpg"
|
||||
Then the cover shows its thumbnail and name, an "Alt text" field appears with "Needed before the cover counts as ready. Sent as image alt in the API." and the placeholder "Describe the image for people who can't see it"
|
||||
And a cover without alt text raises cover_alt as a suggestion, never as an error
|
||||
When the user removes the cover
|
||||
Then the "Using the site social image (north-wall.jpg)." line returns and cover_image_id is sent as null on save
|
||||
|
||||
Scenario: Social sharing
|
||||
When the user opens "Social sharing"
|
||||
Then "Social title" shows "Using meta title", "Social description" shows "Using meta description" and "Social image" shows "Using the cover image."
|
||||
When the user fills a social title, a description and picks a social image
|
||||
Then the three "Using …" chips disappear, "Customised" is shown and the social card shows the overrides
|
||||
|
||||
Scenario Outline: Advanced, canonical URL
|
||||
Given "Advanced" is open
|
||||
When the canonical URL field holds "<value>" and loses focus
|
||||
Then <result>
|
||||
|
||||
Examples:
|
||||
| value | result |
|
||||
| renew.example/costs | the field shows "Enter a full address starting with https://" and the field is invalid |
|
||||
| http://renew.example/a | the field shows "Enter a full address starting with https://" |
|
||||
| https://renew.example/a | no error is shown |
|
||||
| " https://renew.example/a" | the field shows "Enter a full address starting with https://" (the value is never trimmed) |
|
||||
| | no error is shown and "Canonical URL: automatic" is shown when collapsed |
|
||||
|
||||
Scenario: Canonical refused by the API
|
||||
When PATCH /v1/article/12 answers 422 "invalid_url"
|
||||
Then "Advanced" opens, the canonical field shows "Enter a full address starting with https://" and the values are kept
|
||||
|
||||
Scenario: Hide from search engines
|
||||
When the user turns the switch on
|
||||
Then the helper "Sets noindex in the API. It doesn't change who can read the article." is shown and noindex true is sent on save
|
||||
And the next check answers status "hidden"
|
||||
|
||||
Scenario Outline: The search result preview
|
||||
Given the meta title is "How we price a bathroom renovation: surveys, plumbing, tiling and finishes" and the site title template is "%title% | %site%"
|
||||
When the Search result toggle is on "<device>"
|
||||
Then the title shown is cut at <title> characters (the template included) with an ellipsis and the description at <desc> characters
|
||||
And the width of the preview changes with the device
|
||||
|
||||
Examples:
|
||||
| device | title | desc |
|
||||
| Desktop | 60 | 160 |
|
||||
| Mobile | 70 | 120 |
|
||||
|
||||
Scenario: The previews follow the typing, with the fallbacks
|
||||
Given the user clears the meta title
|
||||
Then the preview shows the article title with the site's title_template applied
|
||||
And the social card shows 1.91:1 image, the host, the title and a 2-line description, with fallback chips
|
||||
|
||||
Scenario: Keyboard
|
||||
Then Tab visits the fields in the order drawn, Escape closes the panel as "Cancel" does, and focus returns to "Edit search and sharing"
|
||||
|
||||
Rule: Slug availability
|
||||
|
||||
Scenario: Checked on blur
|
||||
Given the user typed "bathroom-costs" in the slug field
|
||||
When the field loses focus
|
||||
Then one POST /v1/article/12/seo/check is sent with {"slug": "bathroom-costs"}
|
||||
When it answers slug {"available": false, "suggestion": "bathroom-costs-2"}
|
||||
Then the field shows 'The slug "bathroom-costs" is already used on Renew.' and the action "Use bathroom-costs-2"
|
||||
|
||||
Scenario: Use the suggestion
|
||||
Given the slug-taken state is shown
|
||||
When the user activates "Use bathroom-costs-2"
|
||||
Then the slug field holds "bathroom-costs-2" in manual mode, the error and the action disappear and a check confirms it
|
||||
|
||||
Scenario: Slug taken on save
|
||||
Given the user saved with the slug "bathroom-costs"
|
||||
When PATCH /v1/article/12 answers 409 "slug_taken"
|
||||
Then the panel stays open with the slug-taken state, the action "Use <suggestion>" is offered (the suggestion comes from a follow-up check, as the 409 headers are not readable through useApi) and the other values stay
|
||||
And nothing of the edit is applied to the article and the status stays "Unsaved changes"
|
||||
|
||||
Scenario: A slug the article already owns is available
|
||||
Given the check answers slug {"available": true, "suggestion": null}
|
||||
Then no error and no action are shown
|
||||
|
||||
Rule: Saving, publishing and leaving treat SEO edits like any other edit
|
||||
|
||||
Scenario: Save changes commits the panel to the draft and saves
|
||||
Given the user changed the meta title in the panel and nothing else
|
||||
When the user activates "Save changes"
|
||||
Then exactly one PATCH /v1/article/12 is sent containing seo_title only
|
||||
And fields that did not change are not sent, and the unchanged body, site_id and author_ids are not sent
|
||||
|
||||
Scenario: Saving state
|
||||
Given "Save changes" was activated
|
||||
Then while the request runs every field of the panel is disabled with its text colour unchanged, the status reads "Saving…" and the page behind stays as it was
|
||||
|
||||
Scenario: Saved
|
||||
When the PATCH answers 200
|
||||
Then the panel closes, the editor status reads "Saved", the summary and the suggestions refresh with a new check
|
||||
And a success toast shows "Search and sharing saved" with "Your search and sharing settings are up to date."
|
||||
|
||||
Scenario Outline: Save failed
|
||||
When the PATCH fails with <failure>
|
||||
Then the panel stays open with the notice "Couldn't save search and sharing. Your changes are still here. Try again in a moment."
|
||||
And the values are kept, the fields are enabled again and the editor shows its "Save failed" state with Retry
|
||||
|
||||
Examples:
|
||||
| failure |
|
||||
| status 500 |
|
||||
| a network error |
|
||||
|
||||
Scenario: A body or site edit pending in the editor is saved too
|
||||
Given the user edited the body in the editor and then changed the meta title in the panel
|
||||
When the user activates "Save changes"
|
||||
Then one PATCH is sent containing body and seo_title
|
||||
|
||||
Scenario: The editor Save button treats SEO edits like any other edit
|
||||
Given the panel was closed after "Save changes" failed, with the draft holding seo_title
|
||||
Then the editor status reads "Unsaved changes", Save is enabled and "Publish" reads "Save and publish"
|
||||
When the user activates Save, presses Ctrl or Cmd S, or activates "Save and publish"
|
||||
Then the PATCH holds seo_title and the publish request follows for "Save and publish"
|
||||
|
||||
Scenario: Save and publish saves a dirty draft first
|
||||
Given the draft is dirty
|
||||
When the user activates "Save and publish"
|
||||
Then the PATCH is sent first and the publish request follows only if it succeeded
|
||||
And with a clean draft only the publish request is sent
|
||||
|
||||
Scenario: Leaving with unsaved SEO edits
|
||||
Given the draft holds an unsaved SEO value
|
||||
When the user navigates away
|
||||
Then the "Leave without saving?" dialog is shown
|
||||
|
||||
Scenario: Session expiry keeps the SEO draft
|
||||
Given the draft holds unsaved SEO values
|
||||
When PATCH answers 401
|
||||
Then the draft, SEO values included, is mirrored to sessionStorage and the user lands on /login?redirect=/article/12/edit
|
||||
And after logging in the editor restores the draft, shows "Unsaved changes" and the panel fields show the restored values
|
||||
|
||||
Scenario: A storage that throws never loses the editor
|
||||
Given sessionStorage throws on every call
|
||||
Then saving, leaving and the mirror still work with the values in memory
|
||||
|
||||
Scenario: Suggestions never block
|
||||
Given the check answers suggestions or the status "hidden"
|
||||
Then Save, "Save and publish", Publish and Ctrl/Cmd S stay enabled when the draft is dirty and no request is delayed or refused because of them
|
||||
|
||||
Scenario: Cancel
|
||||
Given the user typed in the panel
|
||||
When the user activates "Cancel"
|
||||
Then the panel closes and the values typed in it are discarded without changing the editor status
|
||||
And no request is sent
|
||||
|
||||
Scenario: Offline
|
||||
Given the connection dropped
|
||||
Then the check and the dialog GET fail as in "The check could not run" and "Error", and writing continues
|
||||
|
||||
Scenario Outline: Roles
|
||||
Given the session role is "<role>"
|
||||
Then the section, the panel and the dialog are available
|
||||
|
||||
Examples:
|
||||
| role |
|
||||
| owner |
|
||||
| admin |
|
||||
| verified |
|
||||
|
||||
Rule: "What the frontend gets" (ApiPreviewDialog)
|
||||
|
||||
Scenario: Opening from the section and from the panel
|
||||
When the user activates "What the frontend gets" in the section or in the panel
|
||||
Then GET /v1/article/12/seo is requested once on each opening
|
||||
And on desktop a 720 px dialog opens, on mobile a bottom sheet
|
||||
|
||||
Scenario: Formatted
|
||||
Then the dialog shows "What the frontend gets", "The SEO data returned by GET /v1/article/12/seo, read only. RenewCMS doesn't render pages or add meta tags: your frontend does.", the tabs "Formatted" and "Raw JSON", "Copy JSON" and "Close"
|
||||
And Formatted lists the keys title, description, canonical_url, robots, og, twitter, image, authors, published_at, modified_at and json_ld as a compact key and value list
|
||||
And each value that came from a fallback (per the fallbacks map) carries a chip
|
||||
|
||||
@not-in-design
|
||||
Scenario Outline: Fallback chips in the dialog
|
||||
Given fallbacks.<key> is "<source>"
|
||||
Then the chip next to <key> reads "<chip>" and has a French entry
|
||||
|
||||
Examples:
|
||||
| key | source | chip |
|
||||
| title | title | Using article title |
|
||||
| description | body | Using first sentence of the body |
|
||||
| description | excerpt | Using the excerpt |
|
||||
| description | site | Using the site default description |
|
||||
| image | cover | Using the cover image |
|
||||
| image | site | Using the site social image |
|
||||
| canonical | site | Using the site address and the slug |
|
||||
| title | seo_title | no chip |
|
||||
| image | none | No image |
|
||||
|
||||
Scenario: Raw JSON
|
||||
When the user activates "Raw JSON"
|
||||
Then the response is shown exactly as the API returned it, as pretty-printed JSON in the mono face
|
||||
|
||||
Scenario: Copy JSON
|
||||
Given the response is loaded
|
||||
When the user activates "Copy JSON"
|
||||
Then the raw object is written to the clipboard as pretty-printed JSON
|
||||
And the button reads "Copied" for 2 seconds and "Copied" is announced in a live region
|
||||
And after 2 seconds it reads "Copy JSON" again
|
||||
|
||||
@not-in-design
|
||||
Scenario: The clipboard is refused
|
||||
Given navigator.clipboard is unavailable or rejects
|
||||
When the user activates "Copy JSON"
|
||||
Then the button keeps reading "Copy JSON", no "Copied" is announced and no error reaches the user
|
||||
|
||||
Scenario: Draft article
|
||||
Given article 12 is a draft
|
||||
Then the dialog shows "This article is a draft. The API returns this data only to signed-in callers until it is published." above the data
|
||||
And the data is shown, since the owner may read drafts
|
||||
|
||||
Scenario: Loading
|
||||
Given GET /v1/article/12/seo is pending
|
||||
Then the dialog shows a loading state and "Copy JSON" is disabled
|
||||
|
||||
Scenario Outline: Error with retry
|
||||
When GET /v1/article/12/seo fails with <failure>
|
||||
Then the dialog shows "Couldn't load the SEO data", "GET /v1/article/12/seo failed. Your article is unchanged. Try again in a moment." and "Try again"
|
||||
And the article, the draft and the status are unchanged
|
||||
When the user activates "Try again"
|
||||
Then GET /v1/article/12/seo is requested again
|
||||
|
||||
Examples:
|
||||
| failure |
|
||||
| status 500 |
|
||||
| a network error |
|
||||
|
||||
Scenario: The dialog is read only
|
||||
Then it sends no PATCH and no POST, and "Close" or Escape closes it and returns focus to its opener
|
||||
|
||||
Rule: Layering, copy and visual conformance
|
||||
|
||||
Scenario: Every call goes through useApi
|
||||
Then no component calls fetch directly and every URL is relative
|
||||
|
||||
Scenario: French
|
||||
Given the language is "fr"
|
||||
Then every new string, including the messages of the 11 suggestion codes, the "Go to <field>" labels, the chips and the @not-in-design copy, is the French message
|
||||
And a missing French entry fails the i18n spec
|
||||
|
||||
Scenario: Visual conformance
|
||||
Then `task visual:check -- editor` passes every Editor frame, existing ones and the 30 new ones (24 + 6), at 1440x900 and 390x844, in light and dark
|
||||
And no per-state exception is used without the user's approval
|
||||
@@ -0,0 +1,65 @@
|
||||
# QA: Editor, search and sharing
|
||||
|
||||
SPA slice only. No Go change: the API of `features/seo_data_backend.feature` and `features/seo_output_backend.feature` already exists. A wrong contract is reported as a backend defect.
|
||||
|
||||
Roles: the domain defines only `owner` and `admin`. "verified" is a verified account without either role.
|
||||
|
||||
## Automated SPA (Vitest + Vue Test Utils, `task test:web`)
|
||||
|
||||
Mock `useApi`'s `request` per case for GET and PATCH /v1/article/{id}, POST /v1/article/{id}/seo/check, GET /v1/article/{id}/seo, GET /v1/site/ and the media routes of the picker. Mount EditorView inside DashboardShell with a resolved session and a test router. Mock matchMedia for desktop and mobile. Use fakes for localStorage and sessionStorage. Use Vitest fake timers for the debounce delay and the 2 s "Copied", and do not freeze the system date. The clipboard is a stub on navigator.clipboard. Report the web tests as run or NOT RUN, never as passing when not run. Names below are suggestions; one spec file per numbered group, under `web/src/views/__tests__/` (`EditorSeo*.spec.ts`).
|
||||
|
||||
Regression: every existing Editor spec (EditorView, EditorMetaSection, EditorAuthorList, EditorAddAuthor, EditorImageUpload, EditorMediaPicker, EditorVariants, ArticleEditor*, EditorStatusBar) now sees a POST /v1/article/{id}/seo/check on load. Give them a default mock (`{status: "ready", suggestions: [], slug: {available: true, suggestion: null}}`) rather than loosening unmocked-call checks, and show they still pass.
|
||||
|
||||
1. Section: position under "Site and authors", collapsed default, summary Examples (pending, ready, 1 and 2 suggestions, hidden) with the colour class, Loading skeleton summary, no section on 404, mobile sheet placement.
|
||||
2. Memory, with the storage fallback (see "Red/green proof"): own key distinct from `renewcms-meta-section-open`, shared by sidebar and sheet, wins over nothing else, both `getItem` and `setItem` throwing SecurityError, no API call. Opening via "Edit search and sharing", "What the frontend gets" or a suggestion link does not change the stored choice.
|
||||
3. Open section: address from the site's base_url host plus the slug, other site, ready block, up to three suggestions in response order with "Go to <field>" links, "+N more", checking text, hidden line, check failure with "Try again", 401 and 404 on the check.
|
||||
4. Suggestion copy: each of the 11 codes renders its message from params (the four drawn in the design with the exact copy, seven @not-in-design) and has a French entry; the link label Examples and their focus targets (seo_title, seo_description, cover_image_alt, cover_image_id, slug, body, author_ids).
|
||||
5. Check scheduling: exactly one check on load with `{}`; only changed fields in the body; unsaved body included; debounce Examples with fake timers (rapid typing sends nothing, a pause sends one with the latest value) for every text field; discrete changes check immediately; a late answer never overwrites a newer one (resolve out of order) and the stale request is aborted; no PATCH from any check; no client-side rule (a test that feeds a 74-character title and a check answer without `title_long` still shows no `title_long` message).
|
||||
6. Panel: opening on desktop and mobile with the right container, defaults with every chip, other chips (@not-in-design), filled in, soft counter Examples at 29, 30, 60, 61 (title) and 69, 70, 160, 161 (description) with the amber class and no error colour, maxlength at the API limits, excerpt 300 vs 301 with Save changes disabled, slug Auto/pencil/Reset (sends `""`), cover picker with "Use image", alt text appearing with a cover, cover removal sending null, social customised, canonical Examples (on blur and the 422 `invalid_url` reopening Advanced), noindex switch, preview truncation Examples (60 and 160 desktop, 70 and 120 mobile, template included), previews follow typing and fallbacks, Escape/Cancel discards, focus return.
|
||||
7. Slug availability: check on blur with `{"slug": …}`, taken state and `Use <slug>-2`, the suggestion applied and re-checked, 409 `slug_taken` on save keeps the panel open and offers the suggestion through a follow-up check, nothing applied, an owned slug shows no error.
|
||||
8. Save integration: "Save changes" sends one PATCH with `seo_title` only; body pending is sent along; unchanged fields are not sent (assert the exact JSON); Saving disables fields; Saved closes the panel, refreshes the check and shows the toast; 500 and network failure keep the panel, the notice and the values; editor Save, Ctrl/Cmd S and "Save and publish" after a failed panel save; the leave dialog with an unsaved SEO value; the 401 mirror to sessionStorage and the restored draft with the panel fields; sessionStorage throwing; suggestions never disable Save or Publish; Cancel sends nothing; offline; the three roles.
|
||||
9. ApiPreviewDialog: one GET per opening from both openers, desktop dialog and mobile sheet, Formatted keys and the chip Examples, Raw JSON equals the response, Copy JSON writes the pretty-printed raw object, "Copied" for 2 s (fake timers) and the live-region announcement, a rejected or missing clipboard, draft note when `is_online` is false, loading with Copy disabled, error with "Try again" for 500 and a network error, read-only (no PATCH, no POST), Escape/Close focus return.
|
||||
10. i18n: every new `t()` key has a French entry (extend the i18n spec); one French walk through the section, the panel and the dialog.
|
||||
11. API types: `Article` carries the SEO fields and `Site` carries `site_name`, `title_template`, `default_description` and `default_robots`; `useArticleDraft` mirrors the SEO fields in sessionStorage and sends only changed ones (unit test of `savePayload` through `save()`).
|
||||
|
||||
### Red/green proof for the storage fallback (required in the qa report)
|
||||
|
||||
`metaSectionMemory.ts` already wraps its storage calls in try/catch. For the new key, the spec "A storage that throws never breaks the editor" (both `getItem` and `setItem`) must be shown failing without the fix:
|
||||
1. Write the spec with a localStorage whose `getItem` and `setItem` throw `SecurityError`.
|
||||
2. Temporarily remove the try/catch from the new read/write helpers (or call localStorage directly), run `task test:web -- EditorSeoMemory`, and record the red run (the editor throws or the toggle does nothing).
|
||||
3. Restore the helpers, run again, and record the green run.
|
||||
4. Report both outputs. The temporary revert is not committed.
|
||||
|
||||
## Visual (`task visual:check -- editor`, desktop and mobile, light and dark)
|
||||
|
||||
Setups go in `web/visual/states.ts`, one setup per state, with mocked /v1 and the board's own sample data (article 12 "How we price a bathroom renovation", Renew, "Inès Duarte", media "north-wall.jpg" and "kitchen-after.webp", values from the frames). Hard gate: every capture within 10 %, with no per-state exception. Reference frames: `AppFrame.dc.html` (sidebar section), `DirectoryFrame.dc.html` (SeoPanel, SlugField, MediaField, picker) and the board `RenewCMS Screens Back-office.dc.html`.
|
||||
|
||||
- Existing Editor frames with the sidebar: the collapsed section with "Ready" under "Site and authors". Their setups need a default POST check mock. Loading shows the skeleton summary. Not found has none.
|
||||
- Editor: search and sharing (24): Collapsed ready, suggestions, hidden; Open ready, suggestions (4 codes: title_long, cover_alt, no_h, short), checking, hidden, other site (`site: 1` = Journal); Panel defaults (codes: cover_none), filled in, outside the soft ranges, slug edited, slug taken, cover without alt, choose cover, social sharing open (with scrollY 560 on desktop), social customised, advanced with invalid canonical (scrollY 640), hidden from search (scrollY 700), mobile search preview, checking, saving, save failed; Saved (toast).
|
||||
- Editor: what the frontend gets (6): Formatted, Raw JSON, Copied, Draft article, Loading, Error.
|
||||
- States that wait on a timer (the debounce, the 2 s "Copied") are set up by their end state; none depends on the date or time, so none is `skip: clock-sensitive`.
|
||||
- Re-run Articles, Sites, Authors, Profile, Settings and Home: report any capture that moves above 10 %. Any failure needs the user's decision (an `approvedBy` exception or a design update).
|
||||
|
||||
## Exit conditions
|
||||
|
||||
- All existing Editor frames and the 30 new frames pass `task visual:check -- editor` with no per-state exception.
|
||||
- Vitest specs reported honestly, run or NOT RUN, with the red/green proof attached.
|
||||
- `task lint` and `bun lint` clean; no comment added.
|
||||
|
||||
## Copy and behaviour not in the design (feed back to docs/design later)
|
||||
|
||||
Each has a French entry in `web/src/i18n/messages.ts`.
|
||||
|
||||
1. The codes now use the board copy: title_empty, desc_long, cover_none, slug_long, no_au, body_alt, short.
|
||||
2. The other fallback chips (excerpt, site default description, no image) and the chips of the dialog.
|
||||
3. The check failure text "Couldn't check this article." with "Try again" (no state in the design).
|
||||
4. The "Go to authors" and "Go to URL slug" labels, and where "Go to body" and "Go to authors" move focus.
|
||||
5. The clipboard-refused behaviour (no copy, no state).
|
||||
6. The excerpt-over-300 inline error text, and the "Save changes" disabled rule.
|
||||
|
||||
## Manual checks screenshots cannot cover
|
||||
|
||||
- Keyboard: tab order through the section, the panel (fields, Advanced, switch, previews, buttons) and the dialog; Escape; focus returns to the opener; focus lands on the field named by "Go to …"; "Copied" read by a screen reader.
|
||||
- Hover, focus ring and motion: slide-over and sheet transitions, the amber counter, the chip styles.
|
||||
- Real `task dev`: edit a title, description and cover, watch the check update after a pause, take a slug used by another article (409 flow and "Use …-2"), Save, then open "What the frontend gets" and compare it with `curl` on GET /v1/article/{id}/seo; hide from search and see "Hidden from search"; clipboard on a real browser over http://localhost.
|
||||
- Storage: block site data in the browser and check that the editor still works and the section still toggles.
|
||||
@@ -0,0 +1,784 @@
|
||||
Feature: SEO data backend, article and site search fields, unique slugs and media usage
|
||||
|
||||
As an editor or the owner of a RenewCMS installation
|
||||
I want to store search and sharing data on articles and sites, with a slug that is unique per site
|
||||
So that a frontend can later resolve titles, descriptions, images and addresses from RenewCMS
|
||||
|
||||
Background:
|
||||
Given the spec of record is docs/design/seo-slices.md (slice 1), docs/design/change-list.md ("SEO round"), docs/design/screens/editor.md, docs/design/screens/sites.md and docs/design/states.md
|
||||
And this slice is backend only: no SPA, no change to docs/design, and no resolver, check endpoint, sitemap or list seo filter
|
||||
And an article gains these snake_case fields: slug, excerpt, seo_title, seo_description, cover_image_id, cover_image_alt, social_title, social_description, social_image_id, canonical_url, noindex, seo_dismissed
|
||||
And in article JSON the text fields are "" when empty, cover_image_id and social_image_id are null when unset, noindex is false by default and seo_dismissed is [] by default
|
||||
And every article read (GET /v1/article/{id}, POST /v1/article, PATCH /v1/article/{id}, PATCH /v1/article/{id}/publish, PATCH /v1/article/{id}/unpublish) carries all twelve fields
|
||||
And each item of GET /v1/article/ carries excerpt and slug, and none of the other ten new fields
|
||||
And the SEO fields join body, site_id and author_ids as the known fields of PATCH /v1/article/{id}
|
||||
And a PATCH with no known field, an unknown field only, or a null value on any field other than cover_image_id and social_image_id answers 400 with apperr.BodyErrorMessage, as before
|
||||
And limits are counted in runes: excerpt 300, seo_title 120, seo_description 320, cover_image_alt 200, social_title 120, social_description 320, canonical_url 2048
|
||||
And the slug matches ^[a-z0-9]+(-[a-z0-9]+)*$ with 1 to 100 characters, the rule of authors
|
||||
And canonical_url is empty or an absolute https URL with a host
|
||||
And seo_dismissed is a list of the 11 suggestion codes title_long, title_empty, desc_short, desc_long, cover_alt, cover_none, slug_long, no_au, no_h, body_alt, short; an unknown code answers 400; duplicates are collapsed with the order kept
|
||||
And a slug is unique per site (site_id, slug), never globally
|
||||
And one slug rule applies at creation, in PATCH regeneration and in the migration: lowercase, accents folded, every run of other characters becomes one hyphen, hyphens trimmed, cut to 100 characters with no trailing hyphen, and a result with no letter or digit becomes "article"
|
||||
And when that slug is taken on the site, creation and the migration add -2, -3 and so on, truncating the base so the result fits 100 characters
|
||||
And a slug conflict on PATCH follows the authors slug conflict: status 409 with the plain-text body "slug_taken" from http.Error, and additionally the response header X-Slug-Suggestion holds the first free "<slug>-N" from 2 on the article's target site, fitting 100 characters
|
||||
And other error responses are plain text from http.Error whose body is the existing token or the validator error text: invalid_slug (400, as for authors), invalid_url (422, as for authors), image_not_found (400, as for authors and sites), site_not_found (404), and the new invalid_title_template (400)
|
||||
And a missing article answers 404 "Article not found" and an offline article still reads as not found publicly
|
||||
And a site gains site_name, title_template and default_description; site JSON keeps default_social_image_id and default_robots
|
||||
And POST /v1/site/ and PATCH /v1/site/{id} stay owner only through RequireOwner: a non-owner session gets 403 "Only the owner can do this." and an API key gets 403 "This action needs a real session."
|
||||
And request validation goes through validate tags and validator.Validate.Struct
|
||||
And handlers reach articles, sites and media only through use cases and domain interfaces, and no comment is added anywhere
|
||||
|
||||
Rule: Article SEO fields are edited through PATCH /v1/article/{id}
|
||||
|
||||
Scenario: All SEO fields are set at once
|
||||
Given the article 8 "Spring release" is on the site 1 and the images 5 and 6 exist
|
||||
When the user sends PATCH /v1/article/8 with {"slug": "spring-2026", "excerpt": "Short teaser.", "seo_title": "Spring release notes", "seo_description": "Everything new this spring.", "cover_image_id": 5, "cover_image_alt": "A field of tulips", "social_title": "Spring is here", "social_description": "Read the notes.", "social_image_id": 6, "canonical_url": "https://www.example.com/spring", "noindex": true, "seo_dismissed": ["cover_alt", "short"]}
|
||||
Then the status is 200
|
||||
And the body carries those values and the unchanged title, body, site_id and authors
|
||||
And the article is stored with those values
|
||||
|
||||
Scenario: Absent fields are untouched
|
||||
Given the article 8 has an excerpt, a cover image and a canonical_url
|
||||
When the user sends PATCH /v1/article/8 with {"seo_title": "New title"}
|
||||
Then only seo_title changed
|
||||
|
||||
Scenario Outline: Text fields and the flag are cleared with empty values
|
||||
Given the article 8 has every SEO field set
|
||||
When the user sends PATCH /v1/article/8 with <body>
|
||||
Then the status is 200
|
||||
And <result>
|
||||
|
||||
Examples:
|
||||
| body | result |
|
||||
| {"excerpt": ""} | excerpt is "" |
|
||||
| {"seo_title": ""} | seo_title is "" |
|
||||
| {"seo_description": ""} | seo_description is "" |
|
||||
| {"cover_image_alt": ""} | cover_image_alt is "" |
|
||||
| {"social_title": ""} | social_title is "" |
|
||||
| {"social_description": ""} | social_description is "" |
|
||||
| {"canonical_url": ""} | canonical_url is "" |
|
||||
| {"noindex": false} | noindex is false |
|
||||
| {"seo_dismissed": []} | seo_dismissed is [] |
|
||||
| {"cover_image_id": null} | cover_image_id is null |
|
||||
| {"social_image_id": null} | social_image_id is null |
|
||||
|
||||
Scenario Outline: Boundaries are accepted
|
||||
When the user sends PATCH /v1/article/8 with <field> <value>
|
||||
Then the status is 200
|
||||
|
||||
Examples:
|
||||
| field | value |
|
||||
| excerpt | 300 characters |
|
||||
| excerpt | 300 multi-byte characters |
|
||||
| seo_title | 120 characters |
|
||||
| seo_description | 320 characters |
|
||||
| cover_image_alt | 200 characters |
|
||||
| social_title | 120 characters |
|
||||
| social_description | 320 characters |
|
||||
| slug | 100 characters |
|
||||
| canonical_url | "https://example.com/a?b=1#c" |
|
||||
| canonical_url | 2048 characters, https |
|
||||
|
||||
Scenario Outline: Fields are validated
|
||||
When the user sends PATCH /v1/article/8 with <field> <value>
|
||||
Then the status is <status>
|
||||
And the body is "<body>"
|
||||
And the article is unchanged
|
||||
|
||||
Examples:
|
||||
| field | value | status | body |
|
||||
| excerpt | 301 characters | 400 | the validator error text |
|
||||
| seo_title | 121 characters | 400 | the validator error text |
|
||||
| seo_description | 321 characters | 400 | the validator error text |
|
||||
| cover_image_alt | 201 characters | 400 | the validator error text |
|
||||
| social_title | 121 characters | 400 | the validator error text |
|
||||
| social_description | 321 characters | 400 | the validator error text |
|
||||
| canonical_url | 2049 characters, https | 400 | the validator error text |
|
||||
| slug | "Spring" | 400 | invalid_slug |
|
||||
| slug | "spring_2026" | 400 | invalid_slug |
|
||||
| slug | "-spring" | 400 | invalid_slug |
|
||||
| slug | "spring--2026" | 400 | invalid_slug |
|
||||
| slug | 101 characters | 400 | invalid_slug |
|
||||
| canonical_url | "http://example.com/a" | 422 | invalid_url |
|
||||
| canonical_url | "/relative" | 422 | invalid_url |
|
||||
| canonical_url | "example.com" | 422 | invalid_url |
|
||||
| canonical_url | "https://" | 422 | invalid_url |
|
||||
| seo_dismissed | ["nope"] | 400 | the validator error text |
|
||||
| cover_image_id | 999 (no such image) | 400 | image_not_found |
|
||||
| social_image_id | 999 (no such image) | 400 | image_not_found |
|
||||
| cover_image_id | 0 | 400 | the validator error text |
|
||||
|
||||
Scenario Outline: A wrong type or null on other fields is refused
|
||||
When the user sends PATCH /v1/article/8 with <body>
|
||||
Then the status is 400
|
||||
And the body is apperr.BodyErrorMessage
|
||||
And the article is unchanged
|
||||
|
||||
Examples:
|
||||
| body |
|
||||
| {} |
|
||||
| {"colour": "x"} |
|
||||
| {"slug": null} |
|
||||
| {"excerpt": null} |
|
||||
| {"noindex": null} |
|
||||
| {"seo_dismissed": null} |
|
||||
| {"noindex": "yes"} |
|
||||
| {"excerpt": 5} |
|
||||
| {"cover_image_id": "a"} |
|
||||
| {"seo_dismissed": "x"} |
|
||||
|
||||
Scenario: Duplicate dismissed codes are collapsed
|
||||
When the user sends PATCH /v1/article/8 with {"seo_dismissed": ["short", "cover_alt", "short"]}
|
||||
Then seo_dismissed is ["short", "cover_alt"]
|
||||
|
||||
Scenario: Every known dismissed code is accepted
|
||||
When the user sends PATCH /v1/article/8 with all 11 codes in seo_dismissed
|
||||
Then the status is 200
|
||||
|
||||
Scenario: A refused update changes nothing else
|
||||
When the user sends PATCH /v1/article/8 with {"body": "New", "excerpt": "ok", "canonical_url": "http://x.example"}
|
||||
Then the status is 422 with body "invalid_url"
|
||||
And the body and the excerpt of the article 8 are unchanged
|
||||
|
||||
Scenario: SEO fields and the other fields change together
|
||||
When the user sends PATCH /v1/article/8 with {"body": "New", "site_id": 2, "author_ids": [5], "excerpt": "Teaser"}
|
||||
Then the body, the site_id, the authors and the excerpt are all updated
|
||||
|
||||
Scenario: An update without SEO fields keeps them
|
||||
Given the article 8 has every SEO field set
|
||||
When the user sends PATCH /v1/article/8 with {"body": "New"}
|
||||
Then every SEO field is unchanged
|
||||
|
||||
Scenario Outline: Any account that can edit the article edits its SEO fields
|
||||
When PATCH /v1/article/8 is sent with {"excerpt": "Teaser"} and <credentials>
|
||||
Then the status is 200
|
||||
|
||||
Examples:
|
||||
| credentials |
|
||||
| the owner's jwt cookie |
|
||||
| a verified admin's jwt cookie |
|
||||
| a verified account with another role |
|
||||
| a valid API key |
|
||||
|
||||
Scenario Outline: Without a verified account the article is not edited
|
||||
When PATCH /v1/article/8 is sent with {"excerpt": "Teaser"} and <credentials>
|
||||
Then the status is <status>
|
||||
And the article is unchanged
|
||||
|
||||
Examples:
|
||||
| credentials | status |
|
||||
| an unverified account's jwt cookie | 403 |
|
||||
| no credentials | 401 |
|
||||
|
||||
Scenario: A missing article is not found
|
||||
When the user sends PATCH /v1/article/999 with {"excerpt": "x"}
|
||||
Then the status is 404 with body "Article not found"
|
||||
|
||||
Scenario: A malformed id is refused
|
||||
When the user sends PATCH /v1/article/abc with {"excerpt": "x"}
|
||||
Then the status is 400 with body apperr.IdUint32ErrorMessage
|
||||
|
||||
Scenario: noindex is only a flag
|
||||
Given the article 8 is online
|
||||
When the user sends PATCH /v1/article/8 with {"noindex": true}
|
||||
Then the article is still online
|
||||
And an anonymous GET /v1/article/8 still returns it with "noindex": true
|
||||
|
||||
Scenario: The cover alt is independent of the cover
|
||||
When the user sends PATCH /v1/article/8 with {"cover_image_alt": "A field"} on an article without cover
|
||||
Then the status is 200
|
||||
And cover_image_id is null and cover_image_alt is "A field"
|
||||
|
||||
Rule: Article reads carry the SEO fields
|
||||
|
||||
Scenario Outline: Single-article reads carry all twelve fields
|
||||
Given the article 8 has every SEO field set
|
||||
When <request> is sent
|
||||
Then the article in the response has slug, excerpt, seo_title, seo_description, cover_image_id, cover_image_alt, social_title, social_description, social_image_id, canonical_url, noindex and seo_dismissed with the stored values
|
||||
|
||||
Examples:
|
||||
| request |
|
||||
| GET /v1/article/8 |
|
||||
| PATCH /v1/article/8 |
|
||||
| PATCH /v1/article/8/publish |
|
||||
| PATCH /v1/article/8/unpublish |
|
||||
|
||||
Scenario: A new article has the defaults
|
||||
When the user sends POST /v1/article with {"title": "Spring release", "body": "Hello"}
|
||||
Then the status is 201
|
||||
And the article has slug "spring-release", excerpt "", seo_title "", seo_description "", cover_image_id null, cover_image_alt "", social_title "", social_description "", social_image_id null, canonical_url "", noindex false and seo_dismissed []
|
||||
|
||||
Scenario: The list carries the excerpt and the slug
|
||||
Given the article 8 has the excerpt "Short teaser." and the slug "spring-release"
|
||||
When a verified account sends GET /v1/article/
|
||||
Then each item of items has "excerpt" and "slug"
|
||||
And the article 8 item has excerpt "Short teaser." and slug "spring-release"
|
||||
And no item has seo_title, seo_description, cover_image_id, cover_image_alt, social_title, social_description, social_image_id, canonical_url, noindex or seo_dismissed
|
||||
And the status, total, page, size and counts are as before this slice
|
||||
|
||||
Scenario: Anonymous readers see the SEO fields of online articles
|
||||
Given the article 9 is online with SEO fields set
|
||||
When a caller without credentials sends GET /v1/article/9
|
||||
Then the SEO fields are returned
|
||||
|
||||
Scenario: An offline article is still not found publicly
|
||||
When a caller without a verified account sends GET /v1/article/{offline id}
|
||||
Then the status is 404 with body "Article not found"
|
||||
|
||||
Scenario: The list for anonymous callers shows online articles only
|
||||
Given one online and one offline article
|
||||
When a caller without a verified account sends GET /v1/article/
|
||||
Then only the online article is listed, with its excerpt and slug
|
||||
|
||||
Rule: The slug is unique per site and generated at creation
|
||||
|
||||
Scenario Outline: The slug is generated from the title at creation
|
||||
When the user sends POST /v1/article with {"title": "<title>", "body": "x"}
|
||||
Then the slug is "<slug>"
|
||||
|
||||
Examples:
|
||||
| title | slug |
|
||||
| Spring release | spring-release |
|
||||
| Été à Paris | ete-a-paris |
|
||||
| Dr. O'Neil Smith | dr-o-neil-smith |
|
||||
| !!! | article |
|
||||
|
||||
Scenario: A long title gives a slug of at most 100 characters
|
||||
When the user sends POST /v1/article with a title whose slug would exceed 100 characters
|
||||
Then the slug has at most 100 characters and does not end with "-"
|
||||
|
||||
Scenario: A generated slug that is taken on the site is de-duplicated silently
|
||||
Given the site 1 has the articles with slugs "spring-release" and "spring-release-2"
|
||||
When the user sends POST /v1/article with {"title": "Spring release", "body": "x"}
|
||||
Then the status is 201
|
||||
And the slug is "spring-release-3"
|
||||
|
||||
Scenario: A title without letters or digits is de-duplicated too
|
||||
Given the site 1 has an article with slug "article"
|
||||
When the user sends POST /v1/article with {"title": "!!!", "body": "x"}
|
||||
Then the slug is "article-2"
|
||||
|
||||
Scenario: The suffix still fits the slug limit at creation
|
||||
Given a title whose slug is 100 characters and that slug is taken on the site
|
||||
When the user creates the article
|
||||
Then the slug is at most 100 characters and ends with "-2"
|
||||
|
||||
Scenario: The same title on another site keeps the plain slug
|
||||
Given the default site 1 has an article with slug "spring-release"
|
||||
And the site 2 has no such slug
|
||||
When the article is created on the site 2
|
||||
Then the slug is "spring-release"
|
||||
|
||||
Scenario: A new article is created on the default site, so uniqueness uses that site
|
||||
Given the default site 2 has an article with slug "spring-release"
|
||||
When the user creates "Spring release" without a site
|
||||
Then the slug is "spring-release-2"
|
||||
|
||||
Scenario: The same slug is allowed on two sites
|
||||
Given the article 8 on the site 1 has slug "spring"
|
||||
And the article 9 is on the site 2
|
||||
When the user sends PATCH /v1/article/9 with {"slug": "spring"}
|
||||
Then the status is 200
|
||||
|
||||
Scenario: The slug is editable at any time
|
||||
Given the article 8 is online with slug "spring-release"
|
||||
When the user sends PATCH /v1/article/8 with {"slug": "spring-2026"}
|
||||
Then the status is 200
|
||||
And the slug is "spring-2026" and the article is still online
|
||||
|
||||
Scenario: Keeping the own slug is not a collision
|
||||
When the user sends PATCH /v1/article/8 with {"slug": "spring-release", "excerpt": "x"} and the slug is already that article's
|
||||
Then the status is 200
|
||||
|
||||
Scenario Outline: A taken slug is refused with a suggestion
|
||||
Given the site 1 holds the articles 8 and 9 and the slugs <taken> are used by other articles
|
||||
When the user sends PATCH /v1/article/8 with {"slug": "spring"}
|
||||
Then the status is 409
|
||||
And the body is "slug_taken"
|
||||
And the header X-Slug-Suggestion is "<suggestion>"
|
||||
And the article 8 is unchanged
|
||||
|
||||
Examples:
|
||||
| taken | suggestion |
|
||||
| "spring" | spring-2 |
|
||||
| "spring", "spring-2" | spring-3 |
|
||||
| "spring", "spring-2", "spring-3" | spring-4 |
|
||||
|
||||
Scenario: The suggestion fits the slug limit
|
||||
Given another article has a 100-character slug and the article 8 asks for it
|
||||
Then the 409 suggestion is at most 100 characters and ends with "-2"
|
||||
|
||||
Scenario: The suggestion ignores the article itself
|
||||
Given the article 8 has slug "spring-2" and the article 9 has "spring"
|
||||
When the user sends PATCH /v1/article/8 with {"slug": "spring"}
|
||||
Then the status is 409 with suggestion "spring-2"
|
||||
|
||||
Scenario: The repository can report a race
|
||||
Given the repository reports a unique violation on (site_id, slug)
|
||||
When the user sends PATCH /v1/article/8 with a free-looking slug
|
||||
Then the status is 409 with body "slug_taken" and a suggestion header "<slug>-2"
|
||||
And the article is unchanged
|
||||
|
||||
Scenario: An empty slug regenerates it from the title
|
||||
Given the article 8 "Spring release" has slug "custom-address"
|
||||
When the user sends PATCH /v1/article/8 with {"slug": ""}
|
||||
Then the status is 200
|
||||
And the slug is "spring-release"
|
||||
|
||||
Scenario: Regeneration follows the creation rule
|
||||
Given the article 8 titled "!!!" has slug "custom"
|
||||
When the user sends PATCH /v1/article/8 with {"slug": ""}
|
||||
Then the slug is "article"
|
||||
|
||||
Scenario: Regenerating to the slug it already has is a no-op
|
||||
Given the article 8 "Spring release" already has slug "spring-release"
|
||||
When the user sends PATCH /v1/article/8 with {"slug": ""}
|
||||
Then the status is 200 and no activity event is recorded
|
||||
|
||||
Scenario: Regeneration that collides is refused, never silently suffixed
|
||||
Given the article 9 on the same site has slug "spring-release" and the article 8 "Spring release" has slug "custom"
|
||||
When the user sends PATCH /v1/article/8 with {"slug": ""}
|
||||
Then the status is 409
|
||||
And the body is "slug_taken"
|
||||
And the header X-Slug-Suggestion is "spring-release-2"
|
||||
And the slug of the article 8 is still "custom"
|
||||
|
||||
Scenario: Regeneration combined with a move uses the target site
|
||||
Given the article 8 "Spring release" is on the site 1 and the site 2 holds another article with slug "spring-release"
|
||||
When the user sends PATCH /v1/article/8 with {"site_id": 2, "slug": ""}
|
||||
Then the status is 409 with suggestion "spring-release-2"
|
||||
|
||||
Scenario: Moving to another site re-checks the slug on the target
|
||||
Given the article 8 on the site 1 has slug "spring" and the site 2 has an article with slug "spring"
|
||||
When the user sends PATCH /v1/article/8 with {"site_id": 2}
|
||||
Then the status is 409
|
||||
And the body is "slug_taken" with the header X-Slug-Suggestion "spring-2"
|
||||
And the article 8 is still on the site 1 with slug "spring"
|
||||
|
||||
Scenario: Moving to a site where the slug is free keeps the slug
|
||||
When the user sends PATCH /v1/article/8 with {"site_id": 2} and the slug is free on the site 2
|
||||
Then the status is 200
|
||||
And the slug is unchanged
|
||||
|
||||
Scenario: Moving and changing the slug together checks the new slug on the target
|
||||
Given the site 2 has an article with slug "spring" and none with "autumn"
|
||||
When the user sends PATCH /v1/article/8 with {"site_id": 2, "slug": "autumn"}
|
||||
Then the status is 200
|
||||
When the user sends PATCH /v1/article/9 with {"site_id": 2, "slug": "spring"} on another article
|
||||
Then the status is 409 with suggestion "spring-2"
|
||||
|
||||
Scenario: A refused move changes no SEO field
|
||||
When the user sends PATCH /v1/article/8 with {"site_id": 2, "excerpt": "new"} and the slug collides on the site 2
|
||||
Then the status is 409
|
||||
And the excerpt, the site_id and every other field of the article 8 are unchanged
|
||||
|
||||
Scenario: A freed slug can be reused
|
||||
Given the article 9 has slug "spring" and is deleted
|
||||
When the user sends PATCH /v1/article/8 with {"slug": "spring"}
|
||||
Then the status is 200
|
||||
|
||||
Scenario: Publishing and unpublishing never change the slug
|
||||
When the article 8 is published then unpublished
|
||||
Then its slug is unchanged
|
||||
|
||||
Scenario: Slug uniqueness is enforced by the database
|
||||
When the repository contract suite runs
|
||||
Then a second article with the same (site_id, slug) is refused by every driver
|
||||
|
||||
Rule: Site SEO fields are edited by the owner only
|
||||
|
||||
Scenario: The owner sets the site SEO fields
|
||||
Given the site 2 "Shop"
|
||||
When the owner sends PATCH /v1/site/2 with {"site_name": "Renew Shop", "title_template": "%title% - %site%", "default_description": "A shop about renewal."}
|
||||
Then the status is 200
|
||||
And the body is the site with those three values and its other fields unchanged
|
||||
|
||||
Scenario: A site created without the new fields has the defaults
|
||||
When the owner sends POST /v1/site/ with {"name": "Shop", "key": "shop", "base_url": "https://shop.example.com"}
|
||||
Then the site has site_name "", title_template "%title% | %site%" and default_description ""
|
||||
|
||||
Scenario: A site is created with the new fields
|
||||
When the owner sends POST /v1/site/ with {"name": "Shop", "key": "shop", "base_url": "https://shop.example.com", "site_name": "Renew Shop", "title_template": "%title% - %site%", "default_description": "A shop about renewal."}
|
||||
Then the status is 201
|
||||
And the body carries those three values
|
||||
And the site is stored with them
|
||||
|
||||
Scenario Outline: Creation validates the new fields like editing
|
||||
When the owner sends POST /v1/site/ with a valid site and <field> <value>
|
||||
Then the status is <status>
|
||||
And the body is "<body>"
|
||||
And no site is added when the status is not 201
|
||||
|
||||
Examples:
|
||||
| field | value | status | body |
|
||||
| title_template | "%title%" | 201 | |
|
||||
| title_template | "just text" | 400 | invalid_title_template |
|
||||
| title_template | "%site%" | 400 | invalid_title_template |
|
||||
| title_template | "" | 400 | invalid_title_template |
|
||||
| title_template | 201 characters | 400 | the validator error text |
|
||||
| default_description | 320 characters | 201 | |
|
||||
| default_description | 321 characters | 400 | the validator error text |
|
||||
| site_name | 100 characters | 201 | |
|
||||
| site_name | 101 characters | 400 | the validator error text |
|
||||
|
||||
Scenario: The list carries the new fields
|
||||
When a verified account sends GET /v1/site/
|
||||
Then every site has site_name, title_template and default_description
|
||||
|
||||
Scenario: Absent fields are untouched
|
||||
Given the site 2 has a custom title_template and default_description
|
||||
When the owner sends PATCH /v1/site/2 with {"site_name": "Renew"}
|
||||
Then only site_name changed
|
||||
|
||||
Scenario Outline: The template must contain %title%
|
||||
When the owner sends PATCH /v1/site/2 with {"title_template": <template>}
|
||||
Then the status is <status>
|
||||
And the body is "<body>"
|
||||
|
||||
Examples:
|
||||
| template | status | body |
|
||||
| "%title%" | 200 | |
|
||||
| "%title% \| %site%" | 200 | |
|
||||
| "%site% - %title%" | 200 | |
|
||||
| "News: %title%" | 200 | |
|
||||
| "%site%" | 400 | invalid_title_template |
|
||||
| "just text" | 400 | invalid_title_template |
|
||||
| "%TITLE%" | 400 | invalid_title_template |
|
||||
| "" | 400 | invalid_title_template |
|
||||
| 201 characters | 400 | the validator error text |
|
||||
|
||||
Scenario Outline: Other site SEO fields are validated
|
||||
When the owner sends PATCH /v1/site/2 with <field> <value>
|
||||
Then the status is <status>
|
||||
And the body is "<body>"
|
||||
|
||||
Examples:
|
||||
| field | value | status | body |
|
||||
| default_description | 321 characters | 400 | the validator error text |
|
||||
| default_description | 320 characters | 200 | |
|
||||
| default_description | "" | 200 | |
|
||||
| site_name | 101 characters | 400 | the validator error text |
|
||||
| site_name | "" | 200 | |
|
||||
|
||||
Scenario: A refused site update changes no other field
|
||||
When the owner sends PATCH /v1/site/2 with {"name": "Boutique", "title_template": "nope"}
|
||||
Then the status is 400 with body "invalid_title_template"
|
||||
And the name of the site 2 is unchanged
|
||||
|
||||
Scenario: The existing site fields keep their names
|
||||
When the owner sends PATCH /v1/site/2 with {"default_social_image_id": 5, "default_robots": "noindex"}
|
||||
Then the status is 200 and the site carries default_social_image_id 5 and default_robots "noindex"
|
||||
|
||||
Scenario Outline: Other roles and keys are refused
|
||||
When <request> is sent with <credentials>
|
||||
Then the status is 403
|
||||
And the body is "<body>"
|
||||
And no site changed
|
||||
|
||||
Examples:
|
||||
| request | credentials | body |
|
||||
| PATCH /v1/site/2 | a verified admin's jwt cookie | Only the owner can do this. |
|
||||
| PATCH /v1/site/2 | a verified account with another role | Only the owner can do this. |
|
||||
| PATCH /v1/site/2 | a valid API key | This action needs a real session. |
|
||||
| POST /v1/site/ | a verified admin's jwt cookie | Only the owner can do this. |
|
||||
| POST /v1/site/ | a valid API key | This action needs a real session. |
|
||||
|
||||
Scenario: No credentials is unauthorised
|
||||
When PATCH /v1/site/2 is sent with no credentials
|
||||
Then the status is 401
|
||||
|
||||
Scenario: The role is checked before the body
|
||||
When an admin sends PATCH /v1/site/2 with the body "{not json"
|
||||
Then the status is 403 with body "Only the owner can do this."
|
||||
|
||||
Scenario: A no-op site edit records nothing
|
||||
When the owner sends PATCH /v1/site/2 with the SEO values it already has
|
||||
Then the status is 200
|
||||
And no activity event is recorded
|
||||
|
||||
Rule: Existing articles are backfilled with a unique slug
|
||||
|
||||
Scenario: Every existing article gets a slug from its title
|
||||
Given a database from before this slice holding the articles "Spring release" (id 1) and "Autumn notes" (id 2) on the site 1
|
||||
When database.Migrate runs
|
||||
Then the articles have slugs "spring-release" and "autumn-notes"
|
||||
|
||||
Scenario: Conflicts get suffixes in id order within a site
|
||||
Given the site 1 holds the articles 1, 2 and 3 all titled "News"
|
||||
When database.Migrate runs
|
||||
Then their slugs are "news", "news-2" and "news-3" in id order
|
||||
|
||||
Scenario: A suffix skips slugs that exist
|
||||
Given the site 1 holds the articles 1 "News", 2 "News 2" and 3 "News"
|
||||
When database.Migrate runs
|
||||
Then every slug of the site 1 is distinct and the article 1 has "news"
|
||||
|
||||
Scenario: Slugs are unique per site, not globally
|
||||
Given the article 1 on the site 1 and the article 2 on the site 2 are both titled "News"
|
||||
When database.Migrate runs
|
||||
Then both slugs are "news"
|
||||
|
||||
Scenario Outline: A title with no letter or digit becomes article, suffixed on conflict
|
||||
Given the site 1 holds the articles 5 titled "<first>", 6 titled "<second>" and 7 titled "<third>"
|
||||
When database.Migrate runs
|
||||
Then their slugs are "article", "article-2" and "article-3" in id order
|
||||
And no slug is of the form "article-<id>" unless it comes from the suffix rule
|
||||
|
||||
Examples:
|
||||
| first | second | third |
|
||||
| !!! | ??? | ... |
|
||||
|
||||
Scenario: Long titles stay within 100 characters
|
||||
Given two articles on the same site whose titles give a slug longer than 100 characters
|
||||
When database.Migrate runs
|
||||
Then both slugs have at most 100 characters, are distinct and match the slug rule
|
||||
|
||||
Scenario: The migration is idempotent
|
||||
Given the migration already ran
|
||||
When database.Migrate runs again
|
||||
Then no slug changes
|
||||
|
||||
Scenario: An edited slug survives a restart
|
||||
Given the owner changed the slug of the article 1 to "custom"
|
||||
When database.Migrate runs again
|
||||
Then the article 1 keeps "custom"
|
||||
|
||||
Scenario: New site columns get defaults
|
||||
Given a database holding the sites from before this slice
|
||||
When database.Migrate runs
|
||||
Then every site has site_name "", title_template "%title% | %site%" and default_description ""
|
||||
|
||||
Scenario: Existing articles get neutral SEO defaults
|
||||
When database.Migrate runs on articles from before this slice
|
||||
Then excerpt, seo_title, seo_description, cover_image_alt, social_title, social_description and canonical_url are "", the image ids are null, noindex is false and seo_dismissed is []
|
||||
|
||||
Scenario: A database with a partially backfilled table completes
|
||||
Given some articles have a slug and some are empty
|
||||
When database.Migrate runs
|
||||
Then the empty ones get unique slugs and the existing ones are unchanged
|
||||
|
||||
Scenario: The migration creates the per-site unique index
|
||||
When database.Migrate runs
|
||||
Then a unique index on (site_id, slug) exists on articles
|
||||
|
||||
Scenario: It works on every database driver
|
||||
When the repository contract suite runs
|
||||
Then the article and site repositories behave the same on SQLite, MySQL and PostgreSQL
|
||||
And the SQLite schema test accounts for the new columns and the index
|
||||
|
||||
Rule: Cover, social and site images count as media usages
|
||||
|
||||
Scenario: A cover or social image counts as used
|
||||
Given the image 5 is the cover of the article 8 and appears in no article body, author or site
|
||||
When a verified account looks up the usage of the image 5
|
||||
Then the usage lists the article 8 and the image is not "Unused"
|
||||
|
||||
Scenario Outline: Each reference kind counts
|
||||
Given the image 5 is referenced only as <reference>
|
||||
When a verified account sends GET /v1/media/?filter=unused
|
||||
Then the image 5 is <listed>
|
||||
|
||||
Examples:
|
||||
| reference | listed |
|
||||
| the cover of an article | not in the list |
|
||||
| the social image of an article | not in the list |
|
||||
| the default social image of a site | not in the list |
|
||||
| the avatar of an author | not in the list |
|
||||
| a file name in an article body | not in the list |
|
||||
| nothing | in the list |
|
||||
|
||||
Scenario: An article that uses the image twice counts once
|
||||
Given the image 5 is both in the body and the cover of the article 8
|
||||
Then used_in of the image 5 is 1 for that article
|
||||
|
||||
Scenario: The media list sums every kind
|
||||
Given the image 5 is the cover of an article, the social image of another, in a third article body, the default social image of a site and the avatar of an author
|
||||
When a verified account sends GET /v1/media/
|
||||
Then the used_in of the image 5 is 5
|
||||
|
||||
Scenario: Usage lists articles, authors and sites
|
||||
Given the image 5 is in the body of the article 3, the cover of the article 8, the avatar of the author 2 and the default social image of the site 1
|
||||
When a verified account sends GET /v1/media/5/usage
|
||||
Then the status is 200
|
||||
And the body is a JSON array of 4 items: {"type": "article", "id": 3, "title": "...", "published": ..., "fields": ["body"]}, {"type": "article", "id": 8, "title": "...", "published": ..., "fields": ["cover"]}, {"type": "author", "id": 2, "title": "<author name>", "fields": ["avatar"]} and {"type": "site", "id": 1, "title": "<site name>", "fields": ["default_social_image"]}
|
||||
And author and site items carry no published key
|
||||
|
||||
Scenario: The change is additive for existing consumers
|
||||
Given the image 5 is in the body of the article 3
|
||||
When a verified account sends GET /v1/media/5/usage
|
||||
Then the item still has id, title and published with the same values as before this slice
|
||||
And the only new keys are type and fields
|
||||
|
||||
Scenario: An article using an image in several places is one item with all fields
|
||||
Given the image 5 is the cover, the social image and in the body of the article 8
|
||||
When a verified account sends GET /v1/media/5/usage
|
||||
Then there is one item for the article 8 with fields ["body", "cover", "social"]
|
||||
|
||||
Scenario: An unused image has an empty usage array
|
||||
When a verified account sends GET /v1/media/9/usage on an unused image
|
||||
Then the status is 200 and the body is []
|
||||
|
||||
Scenario: An unknown image is not found
|
||||
When a verified account sends GET /v1/media/999/usage
|
||||
Then the status is 404 with the existing image-not-found body
|
||||
|
||||
Scenario: Offline articles are listed with published false
|
||||
Given the image 5 is the cover of an offline article
|
||||
When a verified account looks up the usage of the image 5
|
||||
Then the item has "published": false
|
||||
|
||||
Scenario: Deleting an image in use clears the references and is never refused
|
||||
Given the image 5 is the cover of the article 8 and the social image of the article 9, with cover_image_alt "A field"
|
||||
When the owner deletes the image 5
|
||||
Then the status is 204
|
||||
And the article 8 has cover_image_id null and the article 9 has social_image_id null
|
||||
And the cover_image_alt of the article 8 is unchanged
|
||||
And the article bodies are untouched
|
||||
And the avatar and site references to the image 5 are cleared as before
|
||||
|
||||
Scenario: A failed delete leaves every reference in place
|
||||
Given the repository fails while removing the image 5
|
||||
When the owner deletes the image 5
|
||||
Then the cover, social, avatar and site references to the image 5 are all unchanged
|
||||
|
||||
Scenario: Merging copies repoints article cover and social images
|
||||
Given the image 6 is a copy of the image 5 and the article 8 has the cover 6 and the article 9 the social image 6
|
||||
When the copies are merged into the image 5
|
||||
Then the article 8 has cover_image_id 5 and the article 9 has social_image_id 5
|
||||
And the merge response counts both articles in articles_updated
|
||||
And updated_article_ids lists both
|
||||
|
||||
Scenario: An article rewritten in body and cover counts once
|
||||
Given the article 8 has the copy 6 in its body and as its cover
|
||||
When the copies are merged into the image 5
|
||||
Then articles_updated is 1 and the article 8 has the image 5 in both places
|
||||
|
||||
Scenario: Purge repoints articles the same way
|
||||
Given a purge group whose kept image is 5 and whose duplicate 6 is the cover of the article 8
|
||||
When the purge runs
|
||||
Then the article 8 has cover_image_id 5
|
||||
And the purge result counts it in articles_updated
|
||||
|
||||
Scenario: A failed purge group leaves covers pointing at existing images
|
||||
Given the purge of a group fails midway
|
||||
Then every article cover_image_id and social_image_id refers to an image that still exists
|
||||
|
||||
Scenario: Authors and sites keep being repointed
|
||||
Given the duplicate 6 is used by the author 2 and the site 1
|
||||
When the copies are merged into the image 5
|
||||
Then authors_updated is 1 and sites_updated is 1
|
||||
|
||||
Scenario: Cover and social usage counts in the purge preview
|
||||
Given a duplicate group whose only usage is as article covers
|
||||
When the purge preview runs
|
||||
Then the kept image is the one in use, and used_in includes cover and social usages
|
||||
|
||||
Rule: SEO edits are recorded in the activity log without leaking the body
|
||||
|
||||
Scenario Outline: A short-value SEO edit is recorded once after the change
|
||||
Given the article 8 "Spring release" has <before>
|
||||
When the user sends PATCH /v1/article/8 with <body>
|
||||
Then one event exists with action "article.edit", category "articles", target {"type": "article", "id": "8", "name": "Spring release"}, outcome "success" and source "web"
|
||||
And its changes are [{"field": "<field>", "kind": "text", "before": "<from>", "after": "<to>"}]
|
||||
And the event was recorded after the change was applied
|
||||
|
||||
Examples:
|
||||
| before | body | field | from | to |
|
||||
| slug "spring" | {"slug": "spring-2026"} | slug | spring | spring-2026 |
|
||||
| canonical_url "" | {"canonical_url": "https://www.example.com/a"} | canonical_url | (empty) | https://www.example.com/a |
|
||||
| noindex false | {"noindex": true} | noindex | false | true |
|
||||
| cover_image_id null | {"cover_image_id": 5} | cover_image | (empty) | the file name of the image 5 |
|
||||
| social_image_id 5 | {"social_image_id": null} | social_image | the file name of the image 5 | (empty) |
|
||||
|
||||
Scenario: A regenerated slug is recorded like an edited one
|
||||
Given the article 8 "Spring release" has slug "custom"
|
||||
When the user sends PATCH /v1/article/8 with {"slug": ""}
|
||||
Then one event "article.edit" exists with changes [{"field": "slug", "kind": "text", "before": "custom", "after": "spring-release"}]
|
||||
|
||||
Scenario Outline: Free-text SEO fields are recorded as a size change, never as text
|
||||
Given the article 8 has <field> of <before> characters
|
||||
When the user sends PATCH /v1/article/8 with <field> of <after> characters
|
||||
Then one event "article.edit" exists with changes [{"field": "<field>", "kind": "body", "delta": <delta>}]
|
||||
And no stored field and no /v1/activity response contains any text of either value
|
||||
|
||||
Examples:
|
||||
| field | before | after | delta |
|
||||
| excerpt | 0 | 120 | 120 |
|
||||
| seo_title | 40 | 55 | 15 |
|
||||
| seo_description | 160 | 100 | -60 |
|
||||
| social_title | 0 | 30 | 30 |
|
||||
| cover_image_alt | 0 | 16 | 16 |
|
||||
|
||||
Scenario: Same-length free text with different content is still a change
|
||||
Given the article 8 has seo_title "AAAAA"
|
||||
When the user sends PATCH /v1/article/8 with {"seo_title": "BBBBB"}
|
||||
Then one event "article.edit" exists with the change on seo_title and delta 0
|
||||
And no event or response contains "AAAAA" or "BBBBB"
|
||||
|
||||
Scenario: A body and SEO edit together record both
|
||||
When the user sends PATCH /v1/article/8 with {"body": "New body text", "slug": "new"}
|
||||
Then one event "article.edit" exists with changes for body (kind "body", delta) and slug (kind "text")
|
||||
And the event holds no text of the body
|
||||
|
||||
Scenario: Dismissing suggestions is not an edit
|
||||
When the user sends PATCH /v1/article/8 with {"seo_dismissed": ["short"]}
|
||||
Then the status is 200
|
||||
And no activity event is recorded
|
||||
|
||||
Scenario: A no-op SEO edit records nothing
|
||||
When the user sends PATCH /v1/article/8 with the SEO values it already has
|
||||
Then the status is 200
|
||||
And no activity event is recorded
|
||||
|
||||
Scenario: A refused slug is recorded as failed with a plain reason
|
||||
When the user sends PATCH /v1/article/8 with a taken slug
|
||||
Then one event exists with action "article.edit", outcome "failed" and failure_reason "That slug is already used by another article on this site."
|
||||
|
||||
Scenario Outline: Nothing is recorded when there is nothing to attribute
|
||||
When <request> is sent
|
||||
Then no activity event is recorded
|
||||
|
||||
Examples:
|
||||
| request |
|
||||
| PATCH /v1/article/999 with an SEO field |
|
||||
| PATCH /v1/article/abc with an SEO field |
|
||||
| PATCH /v1/article/8 with {"slug": "Bad Slug"} |
|
||||
| PATCH /v1/article/8 with a 301-character excerpt |
|
||||
| PATCH /v1/article/8 with an unknown cover image |
|
||||
| PATCH /v1/article/8 with no credentials (401) |
|
||||
|
||||
Scenario: A failing audit repository never changes the response
|
||||
Given the audit repository fails on Append
|
||||
When the user sends PATCH /v1/article/8 with {"slug": "new"}
|
||||
Then the response equals that of a healthy repository
|
||||
And the slug was changed
|
||||
|
||||
Scenario Outline: A site SEO edit is recorded
|
||||
When the owner sends PATCH /v1/site/2 with <body>
|
||||
Then one event "site.edit" exists with category "sites" and changes [{"field": "<field>", "kind": "text", "before": "<from>", "after": "<to>"}]
|
||||
|
||||
Examples:
|
||||
| body | field | from | to |
|
||||
| {"site_name": "Renew"} | site_name | (empty) | Renew |
|
||||
| {"title_template": "%title% - %site%"} | title_template | %title% \| %site% | %title% - %site% |
|
||||
| {"default_description": "A shop."} | default_description | (empty) | A shop. |
|
||||
|
||||
Scenario: The activity API lists the SEO events
|
||||
Given article and site SEO events were recorded
|
||||
When a verified account sends GET /v1/activity/?category=articles
|
||||
Then the article.edit events are returned
|
||||
|
||||
Rule: Layering and documentation
|
||||
|
||||
Scenario: Layering is respected
|
||||
Then use cases import no persistence, mailer, models, gorm, net/http or chi
|
||||
And the article and site domain packages import no GORM or HTTP
|
||||
And handlers import no persistence
|
||||
And only api/dependecyInjection.go builds the repositories and use cases, including the widened GetMediaUsageUseCase
|
||||
|
||||
Scenario: The docs describe the new surface
|
||||
Then docs/api.md documents the new article and site fields, the 409 slug_taken response with its X-Slug-Suggestion header, the empty-slug regeneration, the new error tokens, the widened GET /v1/media/{id}/usage items and the new used_in sources
|
||||
And docs/api/articles.md documents the twelve article fields, their limits and the per-site slug rule
|
||||
And docs/architecture.md mentions the per-site slug uniqueness, the backfill and the media usage sources
|
||||
And docs/release-notes.md announces the change, including the additive usage response keys
|
||||
And web/src/data/apiCatalogue.ts lists the new PATCH request fields and its spec checks them
|
||||
@@ -0,0 +1,91 @@
|
||||
# QA procedure: SEO data backend (slice 1 of 4)
|
||||
|
||||
Spec: `features/seo_data_backend.feature`. Go tests only, in `test/` (package `test`), run with `task test`. No live server, no real SMTP, no real SQLite file outside the temp-dir repository-contract harness. Call `validator.InitValidator()` before any handler call. Error assertions compare the plain-text body to the exact token or constant named in the spec. The 409 `slug_taken` assertion checks the plain-text body `slug_taken` and the `X-Slug-Suggestion` header.
|
||||
|
||||
## Divergences from docs/design
|
||||
|
||||
`docs/design` is read-only; the SPA slices (3 and 4) align to the code, not to these design words.
|
||||
|
||||
- **Site image and robots names:** the API uses `default_social_image_id` and `default_robots` (existing site contract). The design writes `social_image_id` for the site and, in places, `robots`. The SPA uses the code names.
|
||||
- **Non-owner site writes:** the API answers 403 with the existing text "Only the owner can do this." (`apperr.OwnerRequiredErrorMessage`). The design mentions a 403 `owner_only` token, which does not exist.
|
||||
- **Empty-slug fallback:** one rule everywhere. A title with no letter or digit becomes `article`, then `article-2`, `article-3` on conflict, in the API and in the migration. `docs/design/seo-slices.md` (decision 5) says `article-<id>` for the migration; that wording is not followed.
|
||||
- **Slug conflict transport:** the conflict follows the authors slug conflict (plain text `slug_taken`, 409); the suggestion travels in the `X-Slug-Suggestion` response header, not in a JSON body. The `slug.suggestion` of the slice 2 check endpoint is separate.
|
||||
- **Empty slug:** `slug: ""` regenerates the slug from the title (the SPA "Reset to match the title" sends `""`); 409 only if the regenerated slug belongs to another article on the site.
|
||||
- **Status codes:** `invalid_url` is 422 (authors); `invalid_slug`, `invalid_title_template` and `image_not_found` are 400.
|
||||
- **Usage response:** `GET /media/{id}/usage` stays an array; items gain `type` and `fields`; authors and sites are listed; non-article items have no `published`.
|
||||
|
||||
## Setup
|
||||
|
||||
- New files `test/seo_data_*_test.go`. Fakes have unique names: `mockSeoArticleRepo` (articles with per-site unique slug, unique-violation injection on (site_id, slug), `FindByBodyContaining`, cover and social references, repoint helpers), `mockSeoSiteRepo`, `mockSeoAuthorRepo`, `mockSeoImageRepo` (images, delete, merge and purge repointing, failure injection), and a fake audit repository with fail and panic switches (reuse).
|
||||
- Routers mirror `api/router.go`: article, site, media (including `/{id}/usage`) and activity routers. Protected routes sit behind `jwtauth.Verifier` + `jwtauth.Authenticator` with a test `jwtauth.New("HS256", ...)`. Signed `jwt` cookies with the `user_id` claim for: owner, admin, a verified account whose role is `"editor"`, an unverified account. An API-key request uses the key authentication path.
|
||||
- Helpers create articles, sites, images, authors and references directly in the fakes. Assertions read the fakes, never only the JSON.
|
||||
|
||||
## A. Article PATCH, SEO fields
|
||||
|
||||
1. Set all twelve fields: 200, body and stored values equal, unrelated fields unchanged.
|
||||
2. Absent fields untouched; clear table (`""`, `false`, `[]`, `null` on the two image ids).
|
||||
3. Boundary table: 300, 120, 320, 200, 120, 320, slug 100, canonical 2048; ASCII and multi-byte counted in runes; a canonical URL with query and fragment.
|
||||
4. Validation table with exact status and token: over-limit fields give 400 validator text; slug cases (`Spring`, `spring_2026`, `-spring`, `spring--2026`, 101 chars) give 400 `invalid_slug`; canonical non-https, relative, no host give 422 `invalid_url`; unknown dismissed code gives 400 validator text; unknown image ids give 400 `image_not_found`; image id `0` gives the validator text. Article unchanged each time.
|
||||
5. Null and wrong-type table (`{}`, unknown, `null` on slug, excerpt, noindex and `seo_dismissed`, wrong types) give 400 `apperr.BodyErrorMessage`; `null` on the two image ids gives 200.
|
||||
6. Duplicate dismissed codes collapse, order kept; all 11 codes accepted. A refused update changes no other field. Combined PATCH of body, site, authors and SEO.
|
||||
7. Callers: owner, admin, "editor" and API key give 200; unverified gives 403; none gives 401. Missing article gives 404 "Article not found"; `abc` gives `apperr.IdUint32ErrorMessage`.
|
||||
8. `noindex` leaves `is_online` unchanged. `cover_image_alt` is accepted without a cover.
|
||||
|
||||
## B. Article reads
|
||||
|
||||
9. GET one, PATCH, publish and unpublish carry the twelve fields with stored values; POST returns the generated slug and the other defaults.
|
||||
10. List items carry `excerpt` and `slug` and none of the other ten new fields (key absence check); `total`, `page`, `size` and `counts` unchanged. Anonymous and unverified readers get online articles only, and an offline article is 404 "Article not found".
|
||||
|
||||
## C. Slug
|
||||
|
||||
11. Generation table (accents, punctuation runs, `!!!` gives `article`, 100-character cap with no trailing hyphen).
|
||||
12. Creation de-duplication: `spring-release` and `-2` taken gives `-3`; `article` taken gives `article-2`; suffix fits 100; same title on another site keeps the plain slug; default-site uniqueness.
|
||||
13. Same slug on two sites via PATCH is 200. Editable when online. Own slug re-sent is 200.
|
||||
14. 409 table: `spring`, `spring-2`, `spring-3` taken give header suggestions `spring-2`, `-3`, `-4`; body is exactly `slug_taken`; 100-character suggestion fits; the suggestion ignores the article itself; repository unique-violation injection gives the same 409; the article is unchanged.
|
||||
15. Empty slug: regenerates from the title (200); follows the creation rule (`!!!` gives `article`); already equal is a 200 with no event; collision gives 409 `slug_taken` with the suggestion header and leaves the slug unchanged (never silently suffixed); combined with a move uses the target site.
|
||||
16. Move table: collision on the target gives 409 with suggestion and leaves site and slug unchanged; free slug moves with the slug kept; move plus new slug checks the new slug on the target; a refused move changes no other field.
|
||||
17. Delete frees the slug. Publish and unpublish keep it.
|
||||
|
||||
## D. Site POST and PATCH
|
||||
|
||||
18. Owner sets the three fields on PATCH (200, others unchanged); absent fields untouched; `GET /v1/site/` and POST responses carry them; defaults `""`, `"%title% | %site%"`, `""` when omitted on POST.
|
||||
19. POST with the three fields: 201 and stored; creation validation table equals the PATCH tables.
|
||||
20. Template table: valid templates give 200; `%site%`, `just text`, `%TITLE%`, empty give 400 `invalid_title_template`; 201 characters gives the validator text. Description 320 and `""` give 200, 321 gives the validator text; site_name 100 gives 200, 101 gives the validator text, `""` gives 200.
|
||||
21. A refused PATCH leaves the other fields unchanged. `default_social_image_id` and `default_robots` still work.
|
||||
22. Refusal table: admin and "editor" get 403 "Only the owner can do this." on PATCH and POST; API key gets 403 "This action needs a real session."; none gives 401; malformed JSON from an admin still gets the 403. A no-op edit is 200 with no event.
|
||||
|
||||
## E. Migration
|
||||
|
||||
23. Repository-contract harness (temp-dir SQLite; MySQL and Postgres opt-in through the existing env switches). `database.Migrate` backfill table: distinct titles; collisions in id order (`news`, `news-2`, `news-3`); suffix skipping existing slugs; per-site scope; titles `!!!`, `???`, `...` on one site give `article`, `article-2`, `article-3`; long titles stay within 100 and are distinct.
|
||||
24. Idempotence: a second run changes nothing; an edited slug survives; a partially backfilled table completes without touching existing slugs.
|
||||
25. New site columns default (`""`, `"%title% | %site%"`, `""`, no backfill of `site_name`); neutral article defaults; the unique index on (site_id, slug) exists and a duplicate insert is refused on every driver. `test/sqlite_schema_unchanged_test.go` is updated for the new columns and index.
|
||||
26. Contract suites for the article and site repositories cover every new column, round-trip of `seo_dismissed`, null image ids and the per-site uniqueness.
|
||||
|
||||
## F. Media usage
|
||||
|
||||
27. Usage lookup: the item table for body, cover, social, avatar and site image, each with its `type`, `id`, `title` and `fields`; one item per article with merged `fields`; `published` present for articles (true or false) and absent for authors and sites; the article item keeps `id`, `title` and `published` with their previous values and the only new keys are `type` and `fields` (additive check); empty array when unused; unknown image gives the existing 404.
|
||||
28. `used_in` and the `unused` filter count cover, social, site and avatar once per article, author and site; an article using the image in body and cover counts once.
|
||||
29. Delete: never refused; references are nulled, `cover_image_alt` and article bodies are untouched, avatars and sites cleared as before, and a failed removal rolls back every reference.
|
||||
30. Merge: articles' cover and social ids repointed; `articles_updated` counts each article once even if body and cover both changed; `updated_article_ids` lists them; `authors_updated` and `sites_updated` still correct. Purge does the same, a failed group leaves every reference on an existing image, and the preview treats cover and social as usage.
|
||||
|
||||
## G. Activity
|
||||
|
||||
31. Short-value table: slug (including a regenerated one), canonical_url, noindex, cover_image and social_image give one `article.edit` with `kind: "text"` and `before`/`after`, recorded after the change.
|
||||
32. Free-text table (excerpt, seo_title, seo_description, social_title, cover_image_alt, and social_description) gives `kind: "body"` and `delta` in characters; the stored event and the `/v1/activity/` response contain none of the old or new text (substring check), including the same-length edit. Body plus SEO edit records both with no body text.
|
||||
33. `seo_dismissed`-only and no-op edits record nothing. A taken slug records a failed event with the plain reason. No event for 404, malformed id, validation refusals, 401. A failing and a panicking audit repository change neither response nor data.
|
||||
34. Site edits record `site.edit` with before and after for `site_name`, `title_template` and `default_description`. `GET /v1/activity/?category=articles` returns the events. `activity-log-producers.feature` carries the matching rule.
|
||||
|
||||
## H. Quality gates
|
||||
|
||||
35. Layering guard: use cases import no persistence, mailer, models, gorm, net/http or chi; the article and site domain packages import no GORM or HTTP; handlers import no persistence; `api/dependecyInjection.go` wires the widened `GetMediaUsageUseCase`; validation goes through validate tags and `validator.Validate.Struct`; no comments added.
|
||||
36. Scoped mutation run through `task mutate` only, on the new and changed use cases (article create and update, site create and update, media usage, delete, merge, purge and list, and the slug helper). Example: `MUTATE_FILES=<those file names> MUTATE_RUN='TestSeoData' MUTATE_WORKERS=2 task mutate -- <use case package path>`. Report LIVED and NOT COVERED mutants and re-check filtered suspects without `MUTATE_RUN`. Also run `task lint:go` and `task fmt`.
|
||||
37. Web: `web/src/data/__tests__/apiCatalogue.spec.ts` is updated for the new article and site request fields and runs under `task test:web`. Report NOT RUN if the runner is not installed.
|
||||
38. Docs, checked by reading: `docs/api.md`, `docs/api/articles.md`, `docs/architecture.md`, `docs/release-notes.md` as listed in the feature.
|
||||
|
||||
## Manual
|
||||
|
||||
- MySQL and Postgres: run the contract suites with the opt-in env vars against real servers.
|
||||
- Real boot on a copy of a pre-slice database: all articles get distinct slugs per site, nothing else changes, the second boot changes nothing.
|
||||
- Docker with the `/data` volume: same boot check.
|
||||
- Read the activity log screen and the CSV export: SEO events show field names and no free text.
|
||||
- Not covered here: the SPA (slices 3 and 4) and the resolver, check endpoint and sitemap (slice 2).
|
||||
@@ -0,0 +1,676 @@
|
||||
Feature: SEO output backend, resolved SEO object, non-persisting check, list status and sitemap
|
||||
|
||||
As a frontend developer or the RenewCMS back-office editor
|
||||
I want the resolved SEO data of an article, a non-persisting check, an SEO status on the article list and a sitemap per site
|
||||
So that a frontend can render meta tags and a sitemap without reimplementing the fallback chain
|
||||
|
||||
Background:
|
||||
Given the spec of record is docs/design/seo-slices.md (slice 2), docs/design/change-list.md ("SEO round"), docs/design/screens/editor.md, docs/design/screens/articles.md and docs/design/screens/integration.md
|
||||
And this slice is backend only: no SPA screen and no change to docs/design
|
||||
And it reuses the article and site SEO fields of features/seo_data_backend.feature and adds no column and no migration
|
||||
And RenewCMS renders no page and injects no meta tag: it only returns data
|
||||
And one rule set (a single use-case-level function over the article, its site, its authors and its body) feeds the list seo_status and seo_suggestions, the check endpoint and the suggestion-related parts of the resolver
|
||||
And the suggestion codes are title_long, title_empty, desc_short, desc_long, cover_alt, cover_none, slug_long, no_au, no_h, body_alt and short
|
||||
And the soft ranges are: meta title 30 to 60 characters, description 70 to 160, slug "very long" above 75; they only produce suggestions and never block saving or publishing
|
||||
And codes listed in the article's seo_dismissed are never reported and never counted
|
||||
And the status of an article is "hidden" when noindex is true, otherwise "suggestions" when at least one non-dismissed suggestion remains, otherwise "ready"
|
||||
And a caller is "verified" when the jwt cookie (or an API key) resolves to a user with is_verified true, and "public" otherwise, exactly as for GET /v1/article/{id}
|
||||
And the fallback chain is: title = seo_title, then the article title, with the site title_template applied last; description = seo_description, then excerpt, then the first sentence of the body, then the site default_description; image = social_image_id, then cover_image_id, then the site default_social_image_id; canonical = canonical_url, then site base_url + "/" + slug; robots = "noindex, nofollow" when noindex is true, otherwise from the site default_robots; og and twitter title and description = social_title and social_description, then the resolved values
|
||||
And the sample site 1 is key "renew", base_url "https://www.renew.example", site_name "Renew", title_template "%title% | %site%", default_description "Renovation notes from the Renew team.", default_robots "index", locale "en" and default_social_image_id 7 (path /static/uploadedImages/7.png)
|
||||
And the sample article 12 is online on the site 1, titled "How we price a bathroom renovation", slug "how-we-price-a-bathroom-renovation", created 2026-09-01T08:00:00Z, updated 2026-09-10T09:30:00Z, with no SEO field set and the body "<p>We price by the square metre. Tiles cost extra.</p>"
|
||||
And error responses are plain text from http.Error: 404 "Article not found" (apperr.ArticleNotFoundErrorMessage), 404 "site_not_found" (apperr.SiteNotFoundErrorMessage), 400 apperr.IdUint32ErrorMessage for a malformed id, 400 apperr.BodyErrorMessage for a malformed body or paging parameter
|
||||
And request validation goes through validate tags and validator.Validate.Struct
|
||||
And handlers reach articles, sites, authors and images only through use cases and domain interfaces, and no comment is added anywhere
|
||||
|
||||
Rule: GET /v1/article/{id}/seo returns the resolved object
|
||||
|
||||
Scenario: The object has the documented shape
|
||||
When an anonymous caller sends GET /v1/article/12/seo
|
||||
Then the status is 200
|
||||
And the body has exactly the keys title, description, canonical_url, robots, og, twitter, image, authors, published_at, modified_at, fallbacks and json_ld
|
||||
And og has exactly the keys type, title, description, image, image_alt, url, site_name and locale
|
||||
And twitter has exactly the keys card, title, description, image and image_alt
|
||||
And image has exactly the keys url, alt and source
|
||||
And fallbacks has exactly the keys title, description, image and canonical
|
||||
And the body has no body, no id and no seo_dismissed key
|
||||
|
||||
Scenario: A bare article resolves every output through the fallbacks
|
||||
When an anonymous caller sends GET /v1/article/12/seo
|
||||
Then title is "How we price a bathroom renovation | Renew"
|
||||
And description is "We price by the square metre."
|
||||
And canonical_url is "https://www.renew.example/how-we-price-a-bathroom-renovation"
|
||||
And robots is "index, follow"
|
||||
And image is {"url": "https://www.renew.example/static/uploadedImages/7.png", "alt": "", "source": "site"}
|
||||
And og is {"type": "article", "title": "How we price a bathroom renovation | Renew", "description": "We price by the square metre.", "image": "https://www.renew.example/static/uploadedImages/7.png", "image_alt": "", "url": "https://www.renew.example/how-we-price-a-bathroom-renovation", "site_name": "Renew", "locale": "en"}
|
||||
And twitter is {"card": "summary_large_image", "title": "How we price a bathroom renovation | Renew", "description": "We price by the square metre.", "image": "https://www.renew.example/static/uploadedImages/7.png", "image_alt": ""}
|
||||
And fallbacks is {"title": "title", "description": "body", "image": "site", "canonical": "site"}
|
||||
And published_at is "2026-09-01T08:00:00Z" and modified_at is "2026-09-10T09:30:00Z"
|
||||
|
||||
Scenario Outline: The title chain and the template
|
||||
Given the article 12 has seo_title "<seo_title>" and the site title_template is "<template>"
|
||||
When an anonymous caller sends GET /v1/article/12/seo
|
||||
Then title is "<title>"
|
||||
And fallbacks.title is "<source>"
|
||||
|
||||
Examples:
|
||||
| seo_title | template | title | source |
|
||||
| | %title% \| %site% | How we price a bathroom renovation \| Renew | title |
|
||||
| Bathroom costs | %title% \| %site% | Bathroom costs \| Renew | seo_title |
|
||||
| Bathroom costs | %site% - %title% | Renew - Bathroom costs | seo_title |
|
||||
| Bathroom costs | %title% | Bathroom costs | seo_title |
|
||||
| Bathroom costs | News: %title% | News: Bathroom costs | seo_title |
|
||||
|
||||
Scenario Outline: An empty site_name leaves nothing in place of %site% and the title is trimmed
|
||||
Given the site 1 has site_name "" and title_template "<template>"
|
||||
And the article 12 has seo_title "Bathroom costs"
|
||||
When an anonymous caller sends GET /v1/article/12/seo
|
||||
Then title is "<title>"
|
||||
|
||||
Examples:
|
||||
| template | title |
|
||||
| %title% \| %site% | Bathroom costs \| |
|
||||
| %site% %title% | Bathroom costs |
|
||||
| %title% | Bathroom costs |
|
||||
|
||||
Scenario Outline: The description chain
|
||||
Given the article 12 has seo_description "<seo_description>", excerpt "<excerpt>", the body "<body>" and the site default_description "<default>"
|
||||
When an anonymous caller sends GET /v1/article/12/seo
|
||||
Then description is "<description>"
|
||||
And fallbacks.description is "<source>"
|
||||
|
||||
Examples:
|
||||
| seo_description | excerpt | body | default | description | source |
|
||||
| Own words. | A teaser. | <p>First one. Second.</p> | Site. | Own words. | seo_description |
|
||||
| | A teaser. | <p>First one. Second.</p> | Site. | A teaser. | excerpt |
|
||||
| | | <p>First one. Second.</p> | Site. | First one. | body |
|
||||
| | | <p>No terminator here</p> | Site. | No terminator here | body |
|
||||
| | | <h2>Title</h2><p>What? Yes.</p> | Site. | Title What? | body |
|
||||
| | | | Site. | Site. | site |
|
||||
| | | | | | none |
|
||||
|
||||
Scenario Outline: The image chain
|
||||
Given the article 12 has social_image_id <social>, cover_image_id <cover> and cover_image_alt "<alt>", and the images 5, 6 and 7 exist
|
||||
When an anonymous caller sends GET /v1/article/12/seo
|
||||
Then image.url ends with "<path>", image.alt is "<image_alt>" and image.source is "<source>"
|
||||
And og.image equals image.url and twitter.image equals image.url
|
||||
And fallbacks.image is "<source>"
|
||||
|
||||
Examples:
|
||||
| social | cover | alt | path | image_alt | source |
|
||||
| 6 | 5 | A field | /static/uploadedImages/6.png | | social |
|
||||
| null | 5 | A field | /static/uploadedImages/5.png | A field | cover |
|
||||
| null | null | | /static/uploadedImages/7.png | | site |
|
||||
|
||||
Scenario: No image anywhere
|
||||
Given the article 12 has no cover and no social image and the site has no default social image
|
||||
When an anonymous caller sends GET /v1/article/12/seo
|
||||
Then image is {"url": "", "alt": "", "source": "none"}
|
||||
And og.image and twitter.image are ""
|
||||
And twitter.card is "summary"
|
||||
And fallbacks.image is "none"
|
||||
|
||||
Scenario Outline: Canonical and robots
|
||||
Given the article 12 has canonical_url "<canonical>" and noindex <noindex>, and the site default_robots is "<robots>"
|
||||
When an anonymous caller sends GET /v1/article/12/seo
|
||||
Then canonical_url is "<resolved>" and og.url is "<resolved>"
|
||||
And fallbacks.canonical is "<source>"
|
||||
And robots is "<result>"
|
||||
|
||||
Examples:
|
||||
| canonical | noindex | robots | resolved | source | result |
|
||||
| | false | index | https://www.renew.example/how-we-price-a-bathroom-renovation | site | index, follow |
|
||||
| | false | noindex | https://www.renew.example/how-we-price-a-bathroom-renovation | site | noindex, nofollow |
|
||||
| https://other.example/a | false | index | https://other.example/a | canonical_url | index, follow |
|
||||
| | true | index | https://www.renew.example/how-we-price-a-bathroom-renovation | site | noindex, nofollow |
|
||||
|
||||
Scenario: Social overrides apply to og and twitter only
|
||||
Given the article 12 has social_title "Shared title", social_description "Shared text", seo_title "Meta title" and seo_description "Meta text"
|
||||
When an anonymous caller sends GET /v1/article/12/seo
|
||||
Then title is "Meta title | Renew" and description is "Meta text"
|
||||
And og.title and twitter.title are "Shared title" and og.description and twitter.description are "Shared text"
|
||||
|
||||
Scenario: Social fields fall back to the resolved values independently
|
||||
Given the article 12 has social_title "Shared title" and no social_description
|
||||
When an anonymous caller sends GET /v1/article/12/seo
|
||||
Then og.title is "Shared title" and og.description is the resolved description
|
||||
|
||||
Scenario: Authors carry the profile URL and only the social links in same_as
|
||||
Given the article 12 credits the author 2 "Marta Alves" with website "https://marta.example" and links [{"type": "github", "url": "https://github.com/marta"}, {"type": "x", "url": "https://x.com/marta"}]
|
||||
And the author 3 "Zoe Lambert" with no website and no links, credited after her
|
||||
When an anonymous caller sends GET /v1/article/12/seo
|
||||
Then authors is [{"name": "Marta Alves", "url": "https://marta.example", "same_as": ["https://github.com/marta", "https://x.com/marta"]}, {"name": "Zoe Lambert", "url": "", "same_as": []}]
|
||||
And the website "https://marta.example" is not in any same_as
|
||||
|
||||
Scenario: An article without authors has an empty authors array
|
||||
When an anonymous caller sends GET /v1/article/12/seo
|
||||
Then authors is [] and json_ld has no author key
|
||||
|
||||
Scenario: json_ld is a ready Article object
|
||||
Given the article 12 credits the author 2 "Marta Alves" as above and has the cover 5 with alt "A field"
|
||||
When an anonymous caller sends GET /v1/article/12/seo
|
||||
Then json_ld is {"@context": "https://schema.org", "@type": "Article", "headline": "How we price a bathroom renovation", "description": "We price by the square metre.", "image": ["https://www.renew.example/static/uploadedImages/5.png"], "author": [{"@type": "Person", "name": "Marta Alves", "url": "https://marta.example", "sameAs": ["https://github.com/marta", "https://x.com/marta"]}], "datePublished": "2026-09-01T08:00:00Z", "dateModified": "2026-09-10T09:30:00Z", "mainEntityOfPage": {"@type": "WebPage", "@id": "https://www.renew.example/how-we-price-a-bathroom-renovation"}}
|
||||
|
||||
Scenario: The headline uses the meta title without the site template
|
||||
Given the article 12 has seo_title "Bathroom costs"
|
||||
When an anonymous caller sends GET /v1/article/12/seo
|
||||
Then json_ld.headline is "Bathroom costs" and title is "Bathroom costs | Renew"
|
||||
|
||||
Scenario: The object never carries the body
|
||||
Given the body of the article 12 contains "square metre"
|
||||
When an anonymous caller sends GET /v1/article/12/seo
|
||||
Then no value of the response is the full body and the raw response contains no "<p>"
|
||||
|
||||
Scenario Outline: No format parameter is honoured
|
||||
When an anonymous caller sends GET /v1/article/12/seo<query>
|
||||
Then the status is 200
|
||||
And the body equals the response without any query
|
||||
|
||||
Examples:
|
||||
| query |
|
||||
| ?format=html |
|
||||
| ?format=json |
|
||||
| ?format=pdf |
|
||||
|
||||
Scenario: Another site uses its own base URL, template and robots
|
||||
Given the article 12 moves to the site 2 with base_url "https://journal.renew.example", title_template "%title%" and default_robots "noindex"
|
||||
When an anonymous caller sends GET /v1/article/12/seo
|
||||
Then canonical_url starts with "https://journal.renew.example/" and robots is "noindex, nofollow" and title has no site suffix
|
||||
|
||||
Rule: Drafts answer authenticated callers who can read the article
|
||||
|
||||
Scenario: An online article is public
|
||||
When a caller without credentials sends GET /v1/article/12/seo
|
||||
Then the status is 200
|
||||
|
||||
Scenario Outline: A draft is visible to verified callers only
|
||||
Given the article 13 is a draft
|
||||
When GET /v1/article/13/seo is sent with <credentials>
|
||||
Then the status is <status>
|
||||
And the body is <body>
|
||||
|
||||
Examples:
|
||||
| credentials | status | body |
|
||||
| the owner's jwt cookie | 200 | the resolved object |
|
||||
| a verified admin's jwt cookie | 200 | the resolved object |
|
||||
| a verified account with another role | 200 | the resolved object |
|
||||
| a valid API key | 200 | the resolved object |
|
||||
| no credentials | 404 | "Article not found" |
|
||||
| an unverified account's jwt cookie | 404 | "Article not found" |
|
||||
| a malformed jwt cookie | 404 | "Article not found" |
|
||||
|
||||
Scenario: A draft has no publication date
|
||||
When the owner sends GET /v1/article/13/seo on a draft
|
||||
Then published_at is null and modified_at is the article's updated_at
|
||||
And json_ld has no datePublished
|
||||
|
||||
Scenario: Unpublishing hides the object from the public again
|
||||
Given the article 12 is online
|
||||
When it is unpublished and an anonymous caller sends GET /v1/article/12/seo
|
||||
Then the status is 404 with body "Article not found"
|
||||
|
||||
Scenario: A missing article is not found
|
||||
When any caller sends GET /v1/article/999/seo
|
||||
Then the status is 404 with body "Article not found"
|
||||
|
||||
Scenario: A malformed id is refused
|
||||
When any caller sends GET /v1/article/abc/seo
|
||||
Then the status is 400 with body apperr.IdUint32ErrorMessage
|
||||
|
||||
Scenario: The read is idempotent and writes nothing
|
||||
When the same request is sent twice
|
||||
Then both responses are identical and no repository write and no activity event happen
|
||||
|
||||
Scenario: A repository failure answers 500
|
||||
Given the article repository fails on its next call
|
||||
When a caller sends GET /v1/article/12/seo
|
||||
Then the status is 500
|
||||
|
||||
Rule: POST /v1/article/{id}/seo/check evaluates without saving
|
||||
|
||||
Scenario: The check answers the documented shape
|
||||
Given the article 12 has the default state of the background
|
||||
When the owner sends POST /v1/article/12/seo/check with {}
|
||||
Then the status is 200
|
||||
And the body has exactly the keys status, suggestions and slug
|
||||
And every suggestion has exactly the keys code, field and params
|
||||
And slug has exactly the keys available and suggestion
|
||||
|
||||
Scenario Outline: Each code fires on its condition
|
||||
Given the article 12 is configured so that <condition>
|
||||
When the owner sends POST /v1/article/12/seo/check with {}
|
||||
Then suggestions contains the code "<code>" with field "<field>" and params <params>
|
||||
|
||||
Examples:
|
||||
| condition | code | field | params |
|
||||
| the seo_title is 74 characters | title_long | seo_title | {"length": 74, "max": 60} |
|
||||
| the resolved title is empty after trimming | title_empty | seo_title | {} |
|
||||
| the resolved description is 41 characters | desc_short | seo_description | {"length": 41, "min": 70} |
|
||||
| the resolved description is 170 characters | desc_long | seo_description | {"length": 170, "max": 160} |
|
||||
| the cover is set and cover_image_alt is "" | cover_alt | cover_image_alt | {} |
|
||||
| cover_image_id is null | cover_none | cover_image_id | {} |
|
||||
| the slug is 76 characters | slug_long | slug | {"length": 76, "max": 75} |
|
||||
| no author is credited | no_au | author_ids | {} |
|
||||
| the body has 1000 characters of text and no h2 to h6 | no_h | body | {} |
|
||||
| the body has 3 images and one has an empty alt | body_alt | body | {"count": 1} |
|
||||
| the body has 40 characters of text | short | body | {"length": 40, "min": 300} |
|
||||
|
||||
Scenario Outline: Soft ranges are inclusive at the edges
|
||||
When the owner sends POST /v1/article/12/seo/check with <body>
|
||||
Then the code <code> is <present>
|
||||
|
||||
Examples:
|
||||
| body | code | present |
|
||||
| seo_title of 60 characters | title_long | absent |
|
||||
| seo_title of 61 characters | title_long | present |
|
||||
| seo_description of 70 characters | desc_short | absent |
|
||||
| seo_description of 69 characters | desc_short | present |
|
||||
| seo_description of 160 characters | desc_long | absent |
|
||||
| seo_description of 161 characters | desc_long | present |
|
||||
| slug of 75 characters | slug_long | absent |
|
||||
| slug of 76 characters | slug_long | present |
|
||||
|
||||
Scenario Outline: The body rules have inclusive edges
|
||||
When the owner sends POST /v1/article/12/seo/check with a body of <text> characters of text, <headings>
|
||||
Then the code <code> is <present>
|
||||
|
||||
Examples:
|
||||
| text | headings | code | present |
|
||||
| 999 | no heading | no_h | absent |
|
||||
| 1000 | no heading | no_h | present |
|
||||
| 1000 | one h2 | no_h | absent |
|
||||
| 1000 | one h6 | no_h | absent |
|
||||
| 1000 | only an h1 | no_h | present |
|
||||
| 300 | no heading | short | absent |
|
||||
| 299 | no heading | short | present |
|
||||
|
||||
Scenario: Lengths are counted in runes
|
||||
When the owner sends POST /v1/article/12/seo/check with a seo_title of 60 characters that are 2 bytes each
|
||||
Then title_long is absent
|
||||
|
||||
Scenario: The title range is measured on the meta title, not on the template output
|
||||
Given the site title_template adds 30 characters
|
||||
When the owner sends POST /v1/article/12/seo/check with a seo_title of 40 characters
|
||||
Then title_long is absent
|
||||
|
||||
Scenario: Text length ignores tags
|
||||
When the owner sends POST /v1/article/12/seo/check with a body of 200 characters of text wrapped in 400 characters of markup
|
||||
Then the code short is present
|
||||
|
||||
Scenario: A fully prepared article is ready
|
||||
Given the article 12 has a 45-character meta title, a 100-character description, a cover with alt text, a short slug, one author and a body with a heading, an image with alt text and 400 characters
|
||||
When the owner sends POST /v1/article/12/seo/check with {}
|
||||
Then status is "ready" and suggestions is []
|
||||
|
||||
Scenario: Body overrides replace saved values for the check only
|
||||
Given the article 12 has seo_title "Short" saved
|
||||
When the owner sends POST /v1/article/12/seo/check with {"seo_title": "<74 characters>"}
|
||||
Then suggestions contains title_long
|
||||
And the article 12 still has seo_title "Short"
|
||||
|
||||
Scenario Outline: Overrides can also clear a saved value
|
||||
Given the article 12 has <saved>
|
||||
When the owner sends POST /v1/article/12/seo/check with <body>
|
||||
Then the code <code> is <present>
|
||||
|
||||
Examples:
|
||||
| saved | body | code | present |
|
||||
| cover_image_id 5, empty alt | {"cover_image_id": null} | cover_alt | absent |
|
||||
| cover_image_id 5, empty alt | {"cover_image_alt": "A field"} | cover_alt | absent |
|
||||
| cover_image_alt "A field", cover_image_id 5 | {"cover_image_alt": ""} | cover_alt | present |
|
||||
| a 74-character seo_title and a 20-character title | {"seo_title": ""} | title_long | absent |
|
||||
|
||||
Scenario: A body override feeds the body rules and the description fallback
|
||||
Given the article 12 has the saved body of the background and no seo_description and no excerpt
|
||||
When the owner sends POST /v1/article/12/seo/check with {"body": "<p>Sentence one of exactly seventy characters, padded here to reach the minimum. Two.</p>"}
|
||||
Then the code desc_short is absent
|
||||
And the code short is present
|
||||
And the article 12 still has its saved body
|
||||
|
||||
Scenario: A body override with images and headings
|
||||
When the owner sends POST /v1/article/12/seo/check with a body holding 1000 characters, no heading and an image without alt
|
||||
Then the codes no_h and body_alt are present
|
||||
|
||||
Scenario: The check is non-persisting
|
||||
Given a snapshot of the article 12, its site and the activity log
|
||||
When the owner sends POST /v1/article/12/seo/check with {"slug": "other", "noindex": true, "excerpt": "x", "body": "<p>x</p>", "seo_dismissed": ["short"]}
|
||||
Then the article 12 is unchanged, updated_at included
|
||||
And no repository write, no activity event and no media usage change happen
|
||||
|
||||
Scenario: Dismissed codes are filtered out
|
||||
Given the article 12 has seo_dismissed ["cover_none", "no_au"] and would raise cover_none, no_au and short
|
||||
When the owner sends POST /v1/article/12/seo/check with {}
|
||||
Then suggestions has only the code "short"
|
||||
|
||||
Scenario: A dismissed override in the body filters the check
|
||||
When the owner sends POST /v1/article/12/seo/check with {"seo_dismissed": ["short", "no_au", "cover_none", "no_h"]} on an article that would raise those four only
|
||||
Then suggestions is [] and status is "ready"
|
||||
|
||||
Scenario: Dismissing everything leaves ready, noindex still hides
|
||||
Given the article 12 has noindex true
|
||||
When the owner sends POST /v1/article/12/seo/check with {"seo_dismissed": [<all 11 codes>]}
|
||||
Then status is "hidden" and suggestions is []
|
||||
|
||||
Scenario Outline: The status
|
||||
Given the article 12 has <state>
|
||||
When the owner sends POST /v1/article/12/seo/check with {}
|
||||
Then status is "<status>"
|
||||
|
||||
Examples:
|
||||
| state | status |
|
||||
| no suggestion and noindex false | ready |
|
||||
| two suggestions and noindex false | suggestions |
|
||||
| no suggestion and noindex true | hidden |
|
||||
| two suggestions and noindex true | hidden |
|
||||
|
||||
Scenario: A noindex override gives hidden without saving
|
||||
When the owner sends POST /v1/article/12/seo/check with {"noindex": true}
|
||||
Then status is "hidden" and the article 12 still has noindex false
|
||||
|
||||
Scenario: Suggestions come in a fixed order
|
||||
Given the article would raise short, title_long and no_au
|
||||
When the owner sends POST /v1/article/12/seo/check with {}
|
||||
Then the codes are in the order title_long, no_au, short
|
||||
|
||||
Scenario Outline: Slug availability on the article's site
|
||||
Given the site 1 has the articles 12 with slug "how-we-price-a-bathroom-renovation" and 14 with slug "spring" and 15 with slug "spring-2", and the site 2 has an article with slug "autumn"
|
||||
When the owner sends POST /v1/article/12/seo/check with <body>
|
||||
Then slug is <slug>
|
||||
|
||||
Examples:
|
||||
| body | slug |
|
||||
| {} | {"available": true, "suggestion": null} |
|
||||
| {"slug": "how-we-price-a-bathroom-renovation"} | {"available": true, "suggestion": null} |
|
||||
| {"slug": "fresh"} | {"available": true, "suggestion": null} |
|
||||
| {"slug": "autumn"} | {"available": true, "suggestion": null} |
|
||||
| {"slug": "spring"} | {"available": false, "suggestion": "spring-3"} |
|
||||
| {"slug": ""} | {"available": true, "suggestion": null} |
|
||||
|
||||
Scenario: A regenerated empty slug can be taken
|
||||
Given another article of the site 1 already has the slug "how-we-price-a-bathroom-renovation" and the article 12 has slug "custom"
|
||||
When the owner sends POST /v1/article/12/seo/check with {"slug": ""}
|
||||
Then slug is {"available": false, "suggestion": "how-we-price-a-bathroom-renovation-2"}
|
||||
|
||||
Scenario: The suggestion fits the slug limit
|
||||
Given another article of the site has a 100-character slug
|
||||
When the owner sends POST /v1/article/12/seo/check with that slug
|
||||
Then slug.suggestion is at most 100 characters and ends with "-2"
|
||||
|
||||
Scenario: A taken slug is not a refusal
|
||||
When the owner sends POST /v1/article/12/seo/check with a taken slug
|
||||
Then the status is 200 and not 409
|
||||
|
||||
Scenario Outline: The same validation as PATCH applies
|
||||
When the owner sends POST /v1/article/12/seo/check with <field> <value>
|
||||
Then the status is <status>
|
||||
And the body is "<body>"
|
||||
|
||||
Examples:
|
||||
| field | value | status | body |
|
||||
| seo_title | 121 characters | 400 | the validator error text |
|
||||
| seo_description | 321 characters | 400 | the validator error text |
|
||||
| excerpt | 301 characters | 400 | the validator error text |
|
||||
| cover_image_alt | 201 characters | 400 | the validator error text |
|
||||
| social_title | 121 characters | 400 | the validator error text |
|
||||
| social_description | 321 characters | 400 | the validator error text |
|
||||
| slug | "Spring" | 400 | invalid_slug |
|
||||
| slug | 101 characters | 400 | invalid_slug |
|
||||
| canonical_url | "http://example.com/a" | 422 | invalid_url |
|
||||
| cover_image_id | 999 (no such image) | 400 | image_not_found |
|
||||
| social_image_id | 999 (no such image) | 400 | image_not_found |
|
||||
| seo_dismissed | ["nope"] | 400 | the validator error text |
|
||||
|
||||
Scenario Outline: Malformed bodies are refused
|
||||
When the owner sends POST /v1/article/12/seo/check with <body>
|
||||
Then the status is 400
|
||||
And the body is apperr.BodyErrorMessage
|
||||
|
||||
Examples:
|
||||
| body |
|
||||
| {not json |
|
||||
| {"slug": null} |
|
||||
| {"noindex": null} |
|
||||
| {"seo_dismissed": null} |
|
||||
| {"body": null} |
|
||||
| {"noindex": "yes"} |
|
||||
| {"colour": "x"} |
|
||||
|
||||
Scenario: An empty body object is a valid check of the saved state
|
||||
When the owner sends POST /v1/article/12/seo/check with {}
|
||||
Then the status is 200
|
||||
|
||||
Scenario Outline: Site and author overrides are not accepted
|
||||
When the owner sends POST /v1/article/12/seo/check with <body>
|
||||
Then the status is 400 with body apperr.BodyErrorMessage
|
||||
|
||||
Examples:
|
||||
| body |
|
||||
| {"site_id": 2} |
|
||||
| {"author_ids": [2]} |
|
||||
|
||||
Scenario Outline: Anyone who can edit the article may check it
|
||||
When POST /v1/article/12/seo/check is sent with <credentials>
|
||||
Then the status is <status>
|
||||
|
||||
Examples:
|
||||
| credentials | status |
|
||||
| the owner's jwt cookie | 200 |
|
||||
| a verified admin's jwt cookie | 200 |
|
||||
| a verified account with another role | 200 |
|
||||
| a valid API key | 200 |
|
||||
| an unverified account's jwt cookie | 403 |
|
||||
| no credentials | 401 |
|
||||
|
||||
Scenario: A draft can be checked
|
||||
When the owner sends POST /v1/article/13/seo/check with {} on a draft
|
||||
Then the status is 200
|
||||
|
||||
Scenario: A missing article is not found
|
||||
When the owner sends POST /v1/article/999/seo/check with {}
|
||||
Then the status is 404 with body "Article not found"
|
||||
|
||||
Scenario: A malformed id is refused
|
||||
When the owner sends POST /v1/article/abc/seo/check with {}
|
||||
Then the status is 400 with body apperr.IdUint32ErrorMessage
|
||||
|
||||
Scenario: Publishing is never blocked by suggestions
|
||||
Given the check of the article 13 reports suggestions
|
||||
When the owner sends PATCH /v1/article/13/publish
|
||||
Then the status is 200
|
||||
|
||||
Rule: The article list carries the SEO status
|
||||
|
||||
Scenario: Items carry seo_status and seo_suggestions
|
||||
Given the articles 1 (ready), 2 (2 suggestions), 3 (noindex true) and 4 (3 suggestions, one dismissed so 2 remain)
|
||||
When a verified account sends GET /v1/article/
|
||||
Then the item 1 has seo_status "ready" and seo_suggestions 0
|
||||
And the item 2 has seo_status "suggestions" and seo_suggestions 2
|
||||
And the item 3 has seo_status "hidden"
|
||||
And the item 4 has seo_status "suggestions" and seo_suggestions 2
|
||||
And every item has the existing fields, excerpt and slug, and no seo_dismissed key
|
||||
|
||||
Scenario: A hidden article still reports its suggestion count
|
||||
Given the article 3 has noindex true and 2 non-dismissed suggestions
|
||||
When a verified account sends GET /v1/article/
|
||||
Then the item 3 has seo_status "hidden" and seo_suggestions 2
|
||||
|
||||
Scenario: The list and the check agree
|
||||
Given the articles 1 to 4 above
|
||||
When the list is read and the check is run for each article with {}
|
||||
Then for each article seo_status equals the check status and seo_suggestions equals the number of check suggestions
|
||||
|
||||
Scenario: Anonymous callers see online items with their status
|
||||
When a caller without credentials sends GET /v1/article/
|
||||
Then each online item carries seo_status and seo_suggestions and no draft is listed
|
||||
|
||||
Scenario Outline: The seo filter
|
||||
Given the articles 1 (ready), 2 (suggestions), 3 (hidden) and 4 (suggestions)
|
||||
When a verified account sends GET /v1/article/?seo=<value>
|
||||
Then the item ids are <ids>
|
||||
And total is <total>
|
||||
|
||||
Examples:
|
||||
| value | ids | total |
|
||||
| ready | 1 | 1 |
|
||||
| suggestions | 4,2 | 2 |
|
||||
| hidden | 3 | 1 |
|
||||
|
||||
Scenario: The filter composes with search, status, site, sort and paging
|
||||
Given 7 draft articles of the site "journal" titled "Tile ..." with suggestions, 3 online ones and 4 more on the site "renew"
|
||||
When a verified account sends GET /v1/article/?seo=suggestions&q=tile&status=draft&site=journal&sort=title:asc&size=5&page=2
|
||||
Then the page holds the 2 remaining items in title order and total is 7
|
||||
And pages 1 and 2 share no id
|
||||
|
||||
Scenario: Counts stay unfiltered
|
||||
Given 4 online and 2 draft articles of which 3 have suggestions
|
||||
When a verified account sends GET /v1/article/?seo=suggestions
|
||||
Then counts is {"all": 6, "online": 4, "draft": 2} and total is 3
|
||||
|
||||
Scenario: The filter is applied before paging
|
||||
Given 30 articles of which 12 have suggestions
|
||||
When a verified account sends GET /v1/article/?seo=suggestions&size=5&page=3
|
||||
Then the page holds 2 items and total is 12
|
||||
|
||||
Scenario: The filter respects visibility
|
||||
Given an offline article with suggestions
|
||||
When a caller without credentials sends GET /v1/article/?seo=suggestions
|
||||
Then the offline article is not listed and total ignores it
|
||||
|
||||
Scenario: Dismissed codes are never counted in the filter
|
||||
Given an article whose only suggestion is dismissed
|
||||
When a verified account sends GET /v1/article/?seo=suggestions
|
||||
Then the article is not listed
|
||||
|
||||
Scenario Outline: An invalid seo value is refused
|
||||
When a client sends GET /v1/article/?<query>
|
||||
Then the status is 400
|
||||
And the body is apperr.BodyErrorMessage
|
||||
And the repository was not called
|
||||
|
||||
Examples:
|
||||
| query |
|
||||
| seo=maybe |
|
||||
| seo= |
|
||||
| seo=READY |
|
||||
| seo=ready,hidden |
|
||||
| seo=1 |
|
||||
|
||||
Scenario: Invalid format is still reported first
|
||||
When a client sends GET /v1/article/?seo=maybe&format=pdf
|
||||
Then the status is 400 and the body is "The format must be one of: markdown, html, json."
|
||||
|
||||
Scenario: The existing list behaviour is unchanged without the filter
|
||||
Given the background articles
|
||||
When a verified account sends GET /v1/article/
|
||||
Then total, page, size, counts, ordering and the other item fields are as before this slice
|
||||
|
||||
Rule: GET /v1/site/{key}/sitemap lists published URLs
|
||||
|
||||
Scenario: The sitemap lists the online articles of one site
|
||||
Given the site "renew" has the online articles 12 and 16, and a draft 13
|
||||
And the site "journal" has the online article 20
|
||||
When an anonymous caller sends GET /v1/site/renew/sitemap
|
||||
Then the status is 200
|
||||
And the body is a JSON array of 2 items: {"url": "https://www.renew.example/how-we-price-a-bathroom-renovation", "modified_at": "2026-09-10T09:30:00Z", "noindex": false} and the item of the article 16
|
||||
And the header X-Total-Count is "2"
|
||||
And each item has exactly the keys url, modified_at and noindex
|
||||
|
||||
Scenario: Noindex articles are included with the flag
|
||||
Given the online article 16 has noindex true
|
||||
When an anonymous caller sends GET /v1/site/renew/sitemap
|
||||
Then the item of the article 16 has "noindex": true
|
||||
|
||||
Scenario: The url uses the slug and not the canonical override
|
||||
Given the online article 12 has canonical_url "https://other.example/a"
|
||||
When an anonymous caller sends GET /v1/site/renew/sitemap
|
||||
Then the item url is "https://www.renew.example/how-we-price-a-bathroom-renovation"
|
||||
|
||||
Scenario: Drafts are never listed
|
||||
When a caller with a verified jwt cookie sends GET /v1/site/renew/sitemap
|
||||
Then the draft 13 is not listed
|
||||
|
||||
Scenario: An unpublished article leaves the sitemap
|
||||
Given the article 12 is unpublished
|
||||
When an anonymous caller sends GET /v1/site/renew/sitemap
|
||||
Then the article 12 is not listed and X-Total-Count decreases by 1
|
||||
|
||||
Scenario: The sitemap is public
|
||||
When a caller without credentials sends GET /v1/site/renew/sitemap
|
||||
Then the status is 200
|
||||
|
||||
Scenario: An empty site answers an empty array
|
||||
Given the site "renew" has only drafts
|
||||
When an anonymous caller sends GET /v1/site/renew/sitemap
|
||||
Then the status is 200, the body is [] and X-Total-Count is "0"
|
||||
|
||||
Scenario Outline: Paging and the total header
|
||||
Given the site "renew" has <articles> online articles
|
||||
When an anonymous caller sends GET /v1/site/renew/sitemap<query>
|
||||
Then the body holds <count> items
|
||||
And X-Total-Count is "<articles>"
|
||||
|
||||
Examples:
|
||||
| articles | query | count |
|
||||
| 250 | | 100 |
|
||||
| 250 | ?size=25 | 25 |
|
||||
| 250 | ?page=3 | 50 |
|
||||
| 250 | ?page=2&size=100 | 100 |
|
||||
| 250 | ?size=500 | 250 |
|
||||
| 250 | ?page=99&size=25 | 0 |
|
||||
|
||||
Scenario: Pages partition the sitemap in a stable order
|
||||
Given 60 online articles
|
||||
When pages 1, 2 and 3 are requested with size 25
|
||||
Then they hold 25, 25 and 10 items in id ascending order with no repeat
|
||||
|
||||
Scenario Outline: Invalid paging answers 400
|
||||
When a client sends GET /v1/site/renew/sitemap?<query>
|
||||
Then the status is 400
|
||||
And the body is apperr.BodyErrorMessage
|
||||
|
||||
Examples:
|
||||
| query |
|
||||
| page=0 |
|
||||
| page=-1 |
|
||||
| page=abc |
|
||||
| page= |
|
||||
| size=0 |
|
||||
| size=10 |
|
||||
| size=1000 |
|
||||
| size=abc |
|
||||
|
||||
Scenario: An unknown key is not found
|
||||
When a client sends GET /v1/site/nope/sitemap
|
||||
Then the status is 404 with body "site_not_found"
|
||||
|
||||
Scenario: The key is not an id
|
||||
When a client sends GET /v1/site/1/sitemap on a site whose key is "renew"
|
||||
Then the status is 404
|
||||
|
||||
Scenario: The route does not disturb the owner-only site routes
|
||||
When an admin sends PATCH /v1/site/2 with {"site_name": "x"}
|
||||
Then the status is 403 with body "Only the owner can do this." as before
|
||||
|
||||
Scenario: The browser can read the total header
|
||||
When a cross-origin client reads the response of GET /v1/site/renew/sitemap with CORS configured
|
||||
Then Access-Control-Expose-Headers lists X-Total-Count and still lists Link
|
||||
|
||||
Scenario: A repository failure answers 500
|
||||
Given the article repository fails on its next call
|
||||
When a client sends GET /v1/site/renew/sitemap
|
||||
Then the status is 500
|
||||
|
||||
Rule: Layering and documentation
|
||||
|
||||
Scenario: Layering is respected
|
||||
Then use cases import no persistence, mailer, models, gorm, net/http or chi
|
||||
And the resolver, the suggestion rules and the sitemap logic live in use cases or domain packages
|
||||
And the domain packages import no GORM or HTTP
|
||||
And handlers import no persistence and no repository
|
||||
And only api/dependecyInjection.go builds the new use cases and api/router.go wires them
|
||||
And no comment is added anywhere
|
||||
|
||||
Scenario: The docs describe the new surface
|
||||
Then docs/api.md documents GET /v1/article/{id}/seo, POST /v1/article/{id}/seo/check, the seo query parameter, the seo_status and seo_suggestions item fields, GET /v1/site/{key}/sitemap, its X-Total-Count header and the CORS exposure of that header
|
||||
And docs/api/articles.md documents the resolved object, the fallback chain, the suggestion codes with their soft ranges and the draft visibility rule
|
||||
And docs/release-notes.md announces the change
|
||||
And web/src/data/apiCatalogue.ts lists the three new endpoints and the new list parameter and fields, and its spec and web/src/views/IntegrationView.spec.ts counts are updated
|
||||
@@ -0,0 +1,88 @@
|
||||
# QA procedure: SEO output backend (slice 2 of 4)
|
||||
|
||||
Spec: `features/seo_output_backend.feature`. Go tests only, in `test/` (package `test`), run with `task test`. No live server, no real SMTP, no real SQLite file outside the temp-dir repository-contract harness. Call `validator.InitValidator()` before any handler call. Error assertions compare the plain-text body to the exact token or constant named in the spec. Success bodies are JSON. Assert exact key sets by decoding into `map[string]any` and comparing sorted key lists.
|
||||
|
||||
## Divergences from docs/design
|
||||
|
||||
`docs/design` is read-only; slices 3 and 4 align to the code.
|
||||
|
||||
- **published_at:** `created_at` for online articles, `null` for drafts; `modified_at` is `updated_at`. No new column, no migration (user decision).
|
||||
- **Social image name:** the change-list fallback chain says `og_image_id`; the article field is `social_image_id`. The code name is used.
|
||||
- **Sitemap envelope:** the sitemap answers a JSON array with the total in `X-Total-Count`, as integration.md says. Articles and media list routes answer an envelope without that header. The two conventions coexist. `X-Total-Count` is added to the CORS `ExposedHeaders` (alongside `Link`) and documented in docs/api.md.
|
||||
- **Sitemap sizes:** 25, 50, 100, 500 with default 100 (integration.md), unlike the 5, 25, 50, 100 of the other paged routes. Order is id ascending.
|
||||
- **Unknown site key:** the body is the existing token `site_not_found` (`apperr.SiteNotFoundErrorMessage`), not the copy "Site not found" of integration.md.
|
||||
- **Check body:** accepts the 12 SEO fields and an optional `body`; `site_id` and `author_ids` answer 400. `{}` checks the saved state.
|
||||
- **Thresholds:** `no_h` needs at least 1000 characters of plain text and no h2-h6; `short` is under 300 characters.
|
||||
- **Status precedence:** noindex gives `hidden` regardless of suggestions; `seo_suggestions` still counts non-dismissed ones.
|
||||
- **`%site%` with an empty `site_name`:** replaced by an empty string, then the title is trimmed (whitespace only).
|
||||
- **same_as:** social link URLs only; the website is in `url` only; JSON-LD `sameAs` equals `same_as`.
|
||||
|
||||
## Setup
|
||||
|
||||
- New files `test/seo_output_*_test.go`. Fakes have unique names: `mockSeoOutArticleRepo` (articles with per-site slugs, author credits, list filters q, status, site, sort, seo with paging, a call counter, failure injection), `mockSeoOutSiteRepo` (sites with key lookup), `mockSeoOutAuthorRepo`, `mockSeoOutImageRepo` and the fake audit repository (reuse, with a counter that asserts no Append).
|
||||
- Routers mirror `api/router.go`: the public `/{id}/seo` route and the authenticated `/{id}/seo/check` route on the article router, the public `/{key}/sitemap` route on the site router. Protected routes sit behind `jwtauth.Verifier` + `jwtauth.Authenticator` with a test `jwtauth.New("HS256", ...)`. Signed `jwt` cookies with the `user_id` claim for: owner, admin, a verified account with another role, an unverified account, plus a malformed cookie. API-key requests use the key authentication path.
|
||||
- Fixtures: the background sample site 1 and article 12, builders for variants (seo_title lengths, descriptions, covers, authors with website and links, bodies with headings and images). Fixed `created_at`/`updated_at` times; no clock reads, so no clock-sensitive items.
|
||||
- Assertions read the fakes' call counters and stored state, never only the JSON.
|
||||
|
||||
## A. Resolver
|
||||
|
||||
1. Shape: exact key sets of the root, `og`, `twitter`, `image`, `fallbacks`; no `body`, `id` or `seo_dismissed`; raw response has no body text.
|
||||
2. Bare article: every output through the fallbacks with the exact values of the background; `fallbacks` values; `published_at` and `modified_at`.
|
||||
3. Tables: title chain and template variants; empty `site_name` with each template (trimmed); description chain including first-sentence extraction (tags stripped, entities, terminator or none, heading plus paragraph) and the empty chain; image chain (social, cover with alt, site, none) with `image`, `og.image`, `twitter.image`, `twitter.card`; canonical and robots (override, site default `index`/`noindex`, `noindex: true`).
|
||||
4. Social overrides apply to og and twitter only; social title and description fall back independently.
|
||||
5. Authors: ordered, `url` from website or `""`, `same_as` from links in order and never the website; no authors gives `[]` and no `author` key in json_ld.
|
||||
6. JSON-LD: compare the full decoded object to the expected one; headline uses the meta title without the template; dates in RFC 3339; image omitted when none; `datePublished` omitted for drafts.
|
||||
7. `?format=html|json|pdf` returns the identical body as the bare call; second site uses its own base_url, template and robots.
|
||||
|
||||
## B. Visibility
|
||||
|
||||
8. Credentials table for a draft: owner, admin, other verified role, API key give 200; none, unverified, malformed cookie give 404 `Article not found`. An online article is 200 for everyone.
|
||||
9. Draft has `published_at` null and no `datePublished`. Unpublish makes the object 404 for anonymous; missing article 404; `abc` gives `apperr.IdUint32ErrorMessage`; read performs no write and no audit Append; repository failure gives 500.
|
||||
|
||||
## C. Check endpoint
|
||||
|
||||
10. Shape: exact keys of root, suggestion, `slug`.
|
||||
11. Code table: one article per code with the exact `field` and `params` and the thresholds above.
|
||||
12. Edge tables: title 60/61, description 70/69 and 160/161, slug 75/76, `no_h` 999/1000 with h2, h6, h1 only, `short` 299/300, rune counting with 2-byte characters, title measured before the template, text length ignoring markup.
|
||||
13. Fully prepared article gives `ready` and `[]`; overrides replace saved values (set, clear, null image id, body); the saved article, its `updated_at`, the site, the media usage and the activity log are unchanged after every call.
|
||||
14. Dismissed: saved codes filtered; override `seo_dismissed` filters; all 11 dismissed on a noindex article gives `hidden` with `[]`; fixed code order (title_long first, no_au before short).
|
||||
15. Status table: ready, suggestions, hidden (noindex with and without suggestions); a `noindex` override gives `hidden` without saving.
|
||||
16. Slug table: own slug, free, other site's, taken with `-3` suggestion where `-2` is also taken, empty string regeneration (free and taken), 100-character suggestion, taken slug is 200 not 409.
|
||||
17. Validation table identical to PATCH (status and token); malformed and null bodies (including `body: null`) give 400 `apperr.BodyErrorMessage`; `{}` gives 200; `site_id` and `author_ids` give 400.
|
||||
18. Credentials: owner, admin, other verified role, API key give 200; unverified 403; none 401; draft 200; missing 404; `abc` `IdUint32ErrorMessage`.
|
||||
19. Publishing a draft with suggestions still returns 200.
|
||||
|
||||
## D. List
|
||||
|
||||
20. `seo_status` and `seo_suggestions` per item for ready, suggestions, hidden and a partly dismissed article; no `seo_dismissed` key on items; existing fields unchanged.
|
||||
21. Agreement test: for each fixture article, list values equal the check result of the same use case (guards the one-rule-set requirement).
|
||||
22. Filter table `ready`, `suggestions`, `hidden` (ids and totals); composition with `q`, `status`, `site`, `sort` and `page`/`size`; pages disjoint and stable; counts unchanged; filter applied before paging; anonymous caller sees online items only; dismissed codes not counted.
|
||||
23. Invalid table (`maybe`, empty, `READY`, `ready,hidden`, `1`) gives 400 `apperr.BodyErrorMessage` and the repository counter stays 0; `format=pdf` is reported first; no-filter behaviour unchanged.
|
||||
|
||||
## E. Sitemap
|
||||
|
||||
24. Only online articles of the key; `X-Total-Count` equals the filtered total; exact item key set; `noindex` flag included; url from slug and base_url; drafts excluded even with a verified cookie; unpublish removes.
|
||||
25. Public: no credentials gives 200; empty site gives `[]` and `0`.
|
||||
26. Paging table (250 articles: default 100, size 25, page 3, size 500, out of range gives empty array and the real total); 60 articles partition into 25, 25, 10 in id order with no overlap.
|
||||
27. Invalid table (`page=0`, `-1`, `abc`, empty, `size=0`, `10`, `1000`, `abc`) gives 400 `apperr.BodyErrorMessage` and the repository counter stays 0.
|
||||
28. Unknown key gives 404 `site_not_found`; an id as the key gives 404; PATCH `/v1/site/{id}` still owner only; repository failure gives 500.
|
||||
29. CORS: with the CORS middleware enabled, `Access-Control-Expose-Headers` lists `X-Total-Count` and `Link`.
|
||||
|
||||
## F. Quality gates
|
||||
|
||||
30. Layering guard: use cases import no persistence, mailer, models, gorm, net/http or chi; domain packages import no GORM or HTTP; handlers import no persistence; `api/dependecyInjection.go` builds the new use cases and `api/router.go` wires them; validation uses validate tags through `validator.Validate.Struct`; no comments added.
|
||||
31. Scoped mutation run through `task mutate` only, on the new use cases (resolver, suggestion rules, check, list status, sitemap), e.g. `MUTATE_FILES=<file names> MUTATE_RUN='TestSeoOutput' MUTATE_WORKERS=2 task mutate -- <use case package path>`. Report LIVED and NOT COVERED mutants and re-check filtered suspects without `MUTATE_RUN`. Boundary mutants (60/61, 70/69, 160/161, 75/76, 999/1000, 299/300) and the fallback-chain order are the expected high-value targets. Also `task lint:go` and `task fmt`.
|
||||
|
||||
## Non-behavioural deliverables (checked by reading)
|
||||
|
||||
- `docs/api.md`: the three new endpoints, the `seo` list parameter, the `seo_status` and `seo_suggestions` fields, the `X-Total-Count` header on the sitemap and its CORS exposure.
|
||||
- `docs/api/articles.md`: the resolved object, fallback chain, codes and soft ranges, draft visibility.
|
||||
- `docs/release-notes.md`: announcement.
|
||||
- `web/src/data/apiCatalogue.ts`: entries for `GET /v1/article/{id}/seo`, `POST /v1/article/{id}/seo/check`, `GET /v1/site/{key}/sitemap`, plus the `seo` list parameter and the two list fields; its spec and `web/src/views/IntegrationView.spec.ts` counts updated. Run under `task test:web`; report NOT RUN if the runner is not installed.
|
||||
|
||||
## Manual
|
||||
|
||||
- Real boot against a database with slice 1 data: `GET /v1/article/{id}/seo` for a published article, a draft with and without a session, the sitemap for the default site and a second site.
|
||||
- Cross-origin check that `X-Total-Count` is readable when CORS is configured.
|
||||
- Paste a resolved `json_ld` into a schema.org / Rich Results validator.
|
||||
- Not covered here: the SPA (slices 3 and 4).
|
||||
@@ -0,0 +1,512 @@
|
||||
Feature: SEO round, slice 4: Sites defaults, Articles search status, Integration "Search and sharing" and suggestion dismissal
|
||||
|
||||
As the owner of a RenewCMS install, and as anyone who edits articles or builds a frontend on the API
|
||||
I want to set the site-wide SEO defaults, see which articles need attention, dismiss suggestions I do not want, and read how the SEO routes work
|
||||
So that every article resolves good SEO data and a developer can find the routes that serve it
|
||||
|
||||
Background:
|
||||
Given the screens are SitesView (/settings/sites), ArticleView (/article, also reached as /articles), IntegrationView (/integration) and the Editor SEO panel (/article/:id/edit), inside DashboardShell, per docs/design/routes.md
|
||||
And the visual spec of record is docs/design/screens/sites.md ("Sites: SEO defaults", 5 states), articles.md ("Articles: search status", 3 states), integration.md ("Search and sharing"), editor.md (SuggestionList), docs/design/components.md (SeoStatusChip, SuggestionList), docs/design/seo-slices.md and docs/design/states.md ("SEO round"). Exact copy is read from those files and is not repeated here unless a scenario needs it
|
||||
And the board frames of docs/design/source/DirectoryFrame.dc.html (Sites form, SuggestionList), AppFrame.dc.html (Articles rows, cards and toolbar) and IntegrationPage.dc.html (group and index) are the layout tiebreaker
|
||||
And this slice is SPA only and uses the API of features/seo_data_backend.feature and features/seo_output_backend.feature, plus counts.suggestions added by features/articles_pagination_api.feature. No other Go file changes
|
||||
And the SPA calls, with relative URLs through useApi only: GET /v1/site/, POST /v1/site/ and PATCH /v1/site/{id} (site_name, title_template, default_description), GET /v1/article/ with the optional seo=suggestions parameter, whose response also carries counts.suggestions, and PATCH /v1/article/{id} with seo_dismissed. The Integration page makes no request
|
||||
And an article list item carries seo_status ("ready", "suggestions" or "hidden") and seo_suggestions (a count)
|
||||
And the SPA never re-implements a suggestion rule or an SEO status. It draws the status and the count the list returned
|
||||
And the API refuses a title_template without the exact, case-sensitive token %title% with 400 invalid_title_template, and refuses site_name above 100, title_template above 200 and default_description above 320 characters
|
||||
And a new site that omits the three fields gets site_name "", title_template "%title% | %site%" and default_description ""
|
||||
And the API refuses a seo_dismissed code outside the 11 known codes with 400, replaces the saved list with the list sent, collapses duplicates, and never reports or counts a dismissed code
|
||||
And the sample site is Renew (id 1, default, renew.example), the sample article title is "How we price a bathroom renovation", and the sample rows are those of the board frame "Articles: search status"
|
||||
And the roles are those of features/sites_authors_integration.feature: only the owner reaches the Sites form
|
||||
And every visible string goes through t(...) with the English text as the key and a French entry in web/src/i18n/messages.ts
|
||||
And the screens use Nuxt UI components and design tokens only, with no raw colors, and no comment is added anywhere
|
||||
And a scenario tagged @not-in-design uses copy or behaviour that docs/design does not define: it takes the proposal of this feature, has a French entry, and is listed in the .qa.md to be fed back to the design
|
||||
|
||||
Rule: Sites form: Site name, Title template and Default description (owner only)
|
||||
|
||||
Scenario: Field order in the form, as the board draws it
|
||||
Given the owner opens "Edit Renew"
|
||||
Then the fields appear in this order: Name, Key, Base URL, Default social image, Site name, Title template (with its Example), Default description, Default robots policy, Locale, the default switch
|
||||
And under the fields come the "Canonical URL preview" block and then the "How articles use these defaults" block
|
||||
And the slide-over keeps its existing width, header, "Cancel" and "Save changes"
|
||||
|
||||
Scenario: Edit: SEO defaults
|
||||
Given the site Renew has site_name "Renew", title_template "%title% | %site%" and default_description ""
|
||||
When the owner opens "Edit Renew"
|
||||
Then "Site name" shows "Renew" with "Shown in titles through the template, and sent as the Open Graph site name."
|
||||
And "Site name" has no "(optional)" label and an empty value is allowed
|
||||
And "Title template" shows "%title% | %site%" in the mono face with "Use %title% for the article title and %site% for the site name."
|
||||
And the "Example" row reads "How we price a bathroom renovation | Renew"
|
||||
And "Default description" is marked optional, shows the placeholder "One or two sentences about the site." and the counter "0 / 320"
|
||||
And the helper reads "Used when an article has no description, excerpt or body text."
|
||||
And the block "How articles use these defaults" lists Title "Article title, then the template.", Description "Used last, after the article's description, excerpt and body.", Image "Used when an article has no cover image." and Robots "Used unless an article is hidden from search engines."
|
||||
|
||||
Scenario: Add: defaults
|
||||
When the owner opens "Add site"
|
||||
Then "Site name" is empty with the placeholder "e.g. Renew"
|
||||
And "Title template" holds "%title% | %site%"
|
||||
And "Default description" is empty with the placeholder "One or two sentences about the site."
|
||||
And the "How articles use these defaults" block is shown
|
||||
|
||||
Scenario Outline: The live example follows the typing
|
||||
Given the form is open and "Site name" holds "<site_name>" and "Name" holds "<name>"
|
||||
When the owner types "<template>" in "Title template"
|
||||
Then the "Example" row reads "<example>"
|
||||
And no request is sent
|
||||
|
||||
Examples:
|
||||
| name | site_name | template | example |
|
||||
| Journal | Journal | %title% – %site% | How we price a bathroom renovation – Journal |
|
||||
| Journal | | %title% – %site% | How we price a bathroom renovation – Journal |
|
||||
| Journal | Le Journal | %site%: %title% | Le Journal: How we price a bathroom renovation |
|
||||
| Journal | Journal | %title% | How we price a bathroom renovation |
|
||||
| Journal | Journal | %site% / %site% | Journal / Journal |
|
||||
|
||||
@not-in-design
|
||||
Scenario: The example uses the site name, then the name, then the placeholder
|
||||
Given "Site name" and "Name" are both empty
|
||||
Then the Example row uses "Renew" as the site name
|
||||
And when "Site name" is empty and "Name" is "Journal", it uses "Journal", as the API does
|
||||
|
||||
Scenario Outline: Template: not valid
|
||||
Given the owner typed "<template>" in "Title template"
|
||||
When the field loses focus or the owner activates "Save changes"
|
||||
Then the field shows the error "The template must contain %title%." and the Example row is not shown
|
||||
And nothing is sent, the slide-over stays open and focus goes to the first invalid field
|
||||
|
||||
Examples:
|
||||
| template |
|
||||
| just text |
|
||||
| %site% |
|
||||
| %TITLE% |
|
||||
| |
|
||||
|
||||
Scenario: A valid template clears the error
|
||||
Given "Title template" shows "The template must contain %title%."
|
||||
When the owner types "%title%"
|
||||
Then the error is gone and the Example row is shown again
|
||||
|
||||
Scenario: The API refuses a template the form accepted
|
||||
When PATCH /v1/site/1 answers 400 "invalid_title_template"
|
||||
Then "Title template" shows "The template must contain %title%." and the values are kept
|
||||
|
||||
Scenario Outline: The inputs stop at the API limits
|
||||
Given the owner types a long text in <field>
|
||||
Then the input stops accepting characters at <limit>, so the API 400 for those fields is never produced by typing
|
||||
|
||||
Examples:
|
||||
| field | limit |
|
||||
| Site name | 100 |
|
||||
| Title template | 200 |
|
||||
| Default description | 320 |
|
||||
|
||||
Scenario Outline: The description counter
|
||||
When the owner types <n> characters in "Default description"
|
||||
Then the counter reads "<n> / 320" and nothing is blocked
|
||||
|
||||
Examples:
|
||||
| n |
|
||||
| 0 |
|
||||
| 45 |
|
||||
| 320 |
|
||||
|
||||
Scenario: Saving only sends what changed
|
||||
Given the owner opened "Edit Renew" and changed "Title template" to "%title% – %site%" and nothing else
|
||||
When the owner activates "Save changes"
|
||||
Then exactly one PATCH /v1/site/1 is sent containing title_template "%title% – %site%" only
|
||||
And on 200 the slide-over closes and the existing saved behaviour of the Sites list applies
|
||||
|
||||
Scenario: Several SEO fields at once
|
||||
Given the owner changed "Site name" to "Renew Journal", "Default description" to "Notes on renewal work." and "Default robots policy" to "Noindex"
|
||||
When the owner activates "Save changes"
|
||||
Then exactly one PATCH /v1/site/1 is sent containing site_name, default_description and default_robots
|
||||
And values are compared and sent trimmed, as the existing Name field is
|
||||
|
||||
Scenario: Creating a site with the defaults untouched
|
||||
Given the owner filled Name, Key and Base URL and left the three SEO fields as they were
|
||||
When the owner activates "Add site"
|
||||
Then POST /v1/site/ is sent without site_name, title_template or default_description
|
||||
And the created site has the API defaults
|
||||
|
||||
Scenario: Creating a site with SEO values
|
||||
Given the owner typed "Renew Shop" as site name, "%title% - %site%" as template and "A shop about renewal." as description
|
||||
When the owner activates "Add site"
|
||||
Then POST /v1/site/ holds site_name, title_template and default_description with those values
|
||||
|
||||
Scenario: A site without the new fields
|
||||
Given GET /v1/site/ returned a site with no site_name, title_template or default_description
|
||||
When the owner opens its edit form
|
||||
Then "Site name" and "Default description" are empty and "Title template" holds "%title% | %site%"
|
||||
And "Save changes" with no other change sends no request
|
||||
|
||||
Scenario: The new fields count as changes
|
||||
Given the owner typed in any of the three fields
|
||||
When the owner closes the slide-over
|
||||
Then the existing "Discard changes?" dialog is shown
|
||||
|
||||
Scenario Outline: Save failed
|
||||
When the save fails with <failure>
|
||||
Then the slide-over stays open with the notice "Couldn't save the site. Your changes are still here. Try again in a moment."
|
||||
And the values of the three fields are kept
|
||||
|
||||
Examples:
|
||||
| failure |
|
||||
| status 500 |
|
||||
| a network error |
|
||||
|
||||
Scenario: Owner only, as on the rest of Sites
|
||||
Given the session role is "admin" or "verified"
|
||||
Then there is no Sites entry and no form
|
||||
When the user opens /settings/sites or /settings/sites?edit=renew from a bookmark
|
||||
Then the existing 403 page "You don't have access to Sites" is shown, with nothing about SEO added
|
||||
|
||||
Scenario: A 403 owner_only on save is handled like any Sites save
|
||||
Given the owner's role changed while the form was open
|
||||
When PATCH /v1/site/1 answers 403 owner_only
|
||||
Then the existing action toast "Only the owner can manage sites" with "Ask the owner of this site." is shown, as for the other Sites fields
|
||||
|
||||
Scenario: A 401 sends the user to login
|
||||
When PATCH /v1/site/1 answers 401
|
||||
Then the user lands on /login?redirect=/settings/sites&reason=expired, as on the rest of Sites
|
||||
|
||||
Rule: Articles list: the search status chip (SeoStatusChip)
|
||||
|
||||
Scenario Outline: The chip follows the status the list returns
|
||||
Given an article item with seo_status "<status>" and seo_suggestions <count>
|
||||
Then the Status cell shows <cell>
|
||||
|
||||
Examples:
|
||||
| status | count | cell |
|
||||
| ready | 0 | its Online or Draft badge and no SEO chip |
|
||||
| suggestions | 2 | its badge and a warning-soft chip with a lightbulb icon and "2" |
|
||||
| suggestions | 1 | its badge and a warning-soft chip with a lightbulb icon and "1" |
|
||||
| hidden | 0 | its badge and an outline chip with an eye-off icon and "Hidden" |
|
||||
| hidden | 2 | its badge and an outline chip with an eye-off icon and "Hidden", no count |
|
||||
|
||||
Scenario: Chip placement on desktop
|
||||
Then the chip sits in the Status cell, in the same row as the Online or Draft badge, 6 px after it, 22 px high, with a 12 px icon
|
||||
And the Status cell is wide enough that the chip never wraps below the badge in the board's 1440 px frame
|
||||
|
||||
Scenario: Chip placement on mobile cards
|
||||
Given the viewport is 390 px wide
|
||||
Then the chip sits in the card's meta row under the title, after the Online or Draft badge and before "Updated …", 20 px high
|
||||
And the card has no other new element
|
||||
|
||||
Scenario Outline: Tooltips and accessible names
|
||||
Given a chip with <status> and <count>
|
||||
Then its tooltip and its accessible name read "<text>"
|
||||
|
||||
Examples:
|
||||
| status | count | text |
|
||||
| suggestions | 1 | 1 suggestion |
|
||||
| suggestions | 2 | 2 suggestions |
|
||||
| suggestions | 3 | 3 suggestions |
|
||||
| hidden | 0 | Hidden from search engines |
|
||||
|
||||
@not-in-design
|
||||
Scenario: A touch device has no hover, so the name is read
|
||||
Given the viewport is 390 px wide
|
||||
Then the chip carries its text for assistive technology, and the visible mobile chip is the same as on desktop
|
||||
|
||||
@not-in-design
|
||||
Scenario Outline: Items the chip cannot draw show nothing
|
||||
Given an article item <item>
|
||||
Then no SEO chip is shown and nothing breaks
|
||||
|
||||
Examples:
|
||||
| item |
|
||||
| without seo_status |
|
||||
| with seo_status "suggestions" and seo_suggestions 0 |
|
||||
| with an unknown seo_status |
|
||||
|
||||
@not-in-design
|
||||
Scenario: A row action keeps the chip
|
||||
Given a row with a chip
|
||||
When the user publishes or unpublishes it and the PATCH answers 200
|
||||
Then the row updates in place and the chip is unchanged
|
||||
And the chip is refreshed by the next list load
|
||||
|
||||
Scenario: The chip changes nothing else in the row
|
||||
Then the sort, the row menu, the Authors and Site columns, the busy state and the delete flow behave as before
|
||||
|
||||
Rule: Articles list: the "Needs attention" toggle
|
||||
|
||||
Scenario: The toggle sits next to the search field
|
||||
Then on desktop a 32 px "Needs attention" switch with a lightbulb icon and a count sits directly left of the search field, on the toolbar baseline
|
||||
And on mobile a 44 px "Needs attention" switch with the same content is part of the toolbar stack, above the Site filter when it exists
|
||||
And off, it has the default background, an accented border and the toned text colour
|
||||
And on, it uses --rc-sand as fill and border, --rc-on-sand as text and weight 500
|
||||
And it is a switch: role "switch" with aria-checked, reachable by Tab, toggled by Space and Enter
|
||||
|
||||
Scenario: Turning it on
|
||||
Given the URL is /articles?page=3&size=50&q=plaster&status=online&sort=title:asc&site=journal
|
||||
When the user turns "Needs attention" on
|
||||
Then the URL becomes /articles?size=50&q=plaster&status=online&sort=title:asc&site=journal&seo=suggestions with page omitted
|
||||
And GET /v1/article/ is requested with seo=suggestions, size 50, q "plaster", status online, sort title:asc, site journal and page 1
|
||||
And the tab counts are unchanged
|
||||
|
||||
Scenario: Turning it off
|
||||
Given the URL holds ?seo=suggestions&page=2
|
||||
When the user turns the switch off
|
||||
Then seo leaves the URL, the page resets to 1, and q, status, sort, site and size are kept
|
||||
And GET /v1/article/ is requested without seo
|
||||
|
||||
Scenario Outline: Other changes keep the filter
|
||||
Given the URL holds ?seo=suggestions
|
||||
When the user <action>
|
||||
Then ?seo=suggestions stays in the URL
|
||||
|
||||
Examples:
|
||||
| action |
|
||||
| searches for "plaster" |
|
||||
| changes the tab |
|
||||
| changes the sort |
|
||||
| chooses a site |
|
||||
| goes to page 2 |
|
||||
| changes the page size |
|
||||
|
||||
Scenario Outline: Changes made while the filter is on reset the page, as everywhere else
|
||||
Given the URL holds ?seo=suggestions&page=2
|
||||
When the user <action>
|
||||
Then the page resets to 1 and ?seo=suggestions stays
|
||||
|
||||
Examples:
|
||||
| action |
|
||||
| searches for "plaster" |
|
||||
| changes the tab |
|
||||
| changes the sort |
|
||||
| chooses a site |
|
||||
| changes the page size |
|
||||
|
||||
Scenario: Opening a URL with the filter
|
||||
When the user opens /articles?seo=suggestions&page=2
|
||||
Then the switch is on and GET /v1/article/?seo=suggestions&page=2 is requested
|
||||
|
||||
Scenario Outline: Unknown seo values are dropped silently
|
||||
Given the URL holds <query>
|
||||
Then seo is removed from the URL with no notice, the switch is off and the unfiltered list is requested
|
||||
|
||||
Examples:
|
||||
| query |
|
||||
| ?seo=maybe |
|
||||
| ?seo= |
|
||||
| ?seo=READY |
|
||||
| ?seo=ready |
|
||||
| ?seo=hidden |
|
||||
| ?seo=suggestions,x |
|
||||
|
||||
Scenario: Needs attention on
|
||||
Given the filter is on and the response holds the three articles with suggestions
|
||||
Then the list shows only those three articles, each with its chip
|
||||
And hidden-only articles are not in the list, because the API does not return them for seo=suggestions
|
||||
And the tab counts still show the full counts of the unfiltered list
|
||||
|
||||
Scenario: Same behaviour on a single-site install
|
||||
Given GET /v1/site/ returned one site
|
||||
Then the Site column and the Site filter are not rendered
|
||||
And the switch, the chips and ?seo=suggestions behave exactly as with several sites
|
||||
|
||||
Scenario Outline: The count on the switch
|
||||
Given the switch is on or off
|
||||
When the list response <answer>
|
||||
Then the switch reads <label>
|
||||
|
||||
Examples:
|
||||
| answer | label |
|
||||
| holds counts.suggestions 3 | "Needs attention" with the count "3" in the mono face |
|
||||
| holds counts.suggestions 0 | "Needs attention" with the count "0" |
|
||||
| has no counts.suggestions | "Needs attention" with no count |
|
||||
| has not arrived yet (first load) | "Needs attention" with no count |
|
||||
| failed with status 500 or a network error | "Needs attention" with no count and no extra notice |
|
||||
|
||||
@not-in-design
|
||||
Scenario: Where the count comes from
|
||||
Given the switch is on or off
|
||||
Then the count is counts.suggestions of the latest successful GET /v1/article/ response
|
||||
And no request with seo=suggestions and size=5 is sent for the count
|
||||
And the count does not change when only q, tab, site, sort, page or size change, because counts.suggestions is global like the tab counts
|
||||
|
||||
@not-in-design
|
||||
Scenario: The count survives a page or search change that is still loading
|
||||
Given the count "3" was shown from an earlier response
|
||||
When a new list request is in flight
|
||||
Then the switch keeps showing "3"
|
||||
|
||||
Scenario: Needs attention: none
|
||||
Given ?seo=suggestions, no search, the tab "All", and the response is empty
|
||||
Then the state shows "Nothing needs attention", "Every article has a clean check. Suggestions are optional, so this is just a bonus." and "Show all articles"
|
||||
And the paginator and summary are hidden
|
||||
When the user activates "Show all articles"
|
||||
Then seo leaves the URL, the page resets to 1, the other query values are kept and the list is requested without seo
|
||||
|
||||
@not-in-design
|
||||
Scenario Outline: Zero results with the filter and a search or another tab
|
||||
Given ?seo=suggestions and <condition>
|
||||
And the response is empty
|
||||
Then the existing <state> is shown and the filter stays on
|
||||
|
||||
Examples:
|
||||
| condition | state |
|
||||
| a search for "tiles" | "No results" state |
|
||||
| the tab "Draft" | "No drafts" state |
|
||||
| the tab "Online" | "Nothing is online yet" state |
|
||||
|
||||
@not-in-design
|
||||
Scenario: Zero results with the filter and a site
|
||||
Given ?seo=suggestions&site=archive, no search, the tab "All" and the response is empty
|
||||
Then "Nothing needs attention" is shown rather than "No articles on "Archive""
|
||||
|
||||
Scenario: Existing states keep working with the filter
|
||||
Then Loading, Empty, row actions, delete, the Site filter and pagination behave as in docs/design/screens/articles.md with the filter applied
|
||||
And an error loading a page keeps the previous rows and shows its Retry notice as before
|
||||
|
||||
Rule: Editor SEO panel: dismissing a suggestion (deferred from slice 3)
|
||||
|
||||
Scenario: The dismiss column and the footnote, as the board draws them
|
||||
Given the SEO panel is open and the check answers title_long and cover_alt
|
||||
Then each suggestion row ends with a dismiss "×" button, as in the board frame
|
||||
And under the list the footnote reads "Suggestions never block saving or publishing. Dismiss one and it stays hidden for this article."
|
||||
And the compact suggestion list of the open section keeps no dismiss button and no footnote, as drawn
|
||||
|
||||
Scenario: Accessible name and keyboard
|
||||
Given the dismiss button of the row "The meta title is 74 characters. Search engines may cut it off after about 60."
|
||||
Then its accessible name reads "Dismiss suggestion: The meta title is 74 characters. Search engines may cut it off after about 60." and it has a visible 2 px focus ring
|
||||
And Tab reaches it after the row's "Go to meta title" link, and Enter or Space activates it
|
||||
And the name has a French entry with the message interpolated
|
||||
|
||||
Scenario: Dismiss succeeds
|
||||
Given the article saved seo_dismissed is ["no_au"] and the check answers title_long, cover_alt and no_au was already filtered out
|
||||
When the user activates the dismiss button of title_long
|
||||
Then exactly one PATCH /v1/article/12 is sent containing seo_dismissed ["no_au", "title_long"] and no other field
|
||||
And the row stays and the button is disabled with a busy state until the PATCH answers
|
||||
And the unsaved draft, the panel values and the editor status are not touched by the request
|
||||
|
||||
Scenario: Row removal and count update
|
||||
When the PATCH answers 200
|
||||
Then the title_long row leaves the list and the remaining rows keep the order of the check
|
||||
And one new POST /v1/article/12/seo/check is sent so that the list, the section summary line and the article's status come from the server
|
||||
And the summary reads "1 suggestion" when one suggestion remains, and "Ready" with "All good" when none remains
|
||||
And the "Articles" chip count of this article is the one of the next list load
|
||||
|
||||
Scenario: Dismissing the last suggestion
|
||||
Given one suggestion is left
|
||||
When it is dismissed and the PATCH answers 200
|
||||
Then "All good" is shown with "{n} dismissed suggestions are hidden." (the board's copy, with the French plural forms) and the link "Show dismissed"
|
||||
And focus moves to the "Show dismissed" link
|
||||
|
||||
Scenario Outline: Focus after a row leaves
|
||||
Given the list holds three rows and the user dismisses the <position> one
|
||||
Then focus moves to the dismiss button of <target>
|
||||
|
||||
Examples:
|
||||
| position | target |
|
||||
| first | the new first row |
|
||||
| second | the row that took its place |
|
||||
| last | the new last row |
|
||||
|
||||
Scenario Outline: Dismiss failed
|
||||
When the PATCH fails with <failure>
|
||||
Then the row stays, the button is enabled again and an error toast shows "Couldn't dismiss the suggestion" with "Try again in a moment."
|
||||
And the panel, the draft and the editor status are unchanged and no check is sent
|
||||
|
||||
Examples:
|
||||
| failure |
|
||||
| status 500 |
|
||||
| a network error |
|
||||
|
||||
Scenario Outline: A session problem during the dismissal follows the existing rules
|
||||
When the PATCH answers <status>
|
||||
Then <result>
|
||||
|
||||
Examples:
|
||||
| status | result |
|
||||
| 401 | the user lands on /login?redirect=/article/12/edit&reason=expired, the draft is kept |
|
||||
| 404 | the "Not found" editor state is shown |
|
||||
|
||||
@not-in-design
|
||||
Scenario: Show dismissed
|
||||
Given the article has seo_dismissed ["no_au", "short"]
|
||||
Then "All good" or the list footer shows "2 dismissed suggestions are hidden." and "Show dismissed"
|
||||
When the user activates "Show dismissed"
|
||||
Then exactly one PATCH /v1/article/12 is sent with seo_dismissed [] and, on 200, a new check is sent and the restored suggestions appear
|
||||
|
||||
Scenario: Dismissal is per article and never blocks anything
|
||||
Then a dismissed code stays hidden for this article only and for every later check of it
|
||||
And Save, "Save and publish", Publish and Ctrl or Cmd S stay enabled whatever the dismissed list is
|
||||
|
||||
Scenario: Who can dismiss
|
||||
Given the session role is "owner", "admin" or "verified"
|
||||
Then the dismiss button is available, since anyone who can edit the article edits its SEO fields
|
||||
|
||||
Rule: Integration: the "Search and sharing" group
|
||||
|
||||
Scenario: The group sits after Articles
|
||||
Then web/src/data/apiCatalogue.ts has a group "Search and sharing" (key "seo") placed directly after "Articles" in API_GROUPS
|
||||
And the group description reads "RenewCMS doesn't render pages or add meta tags. These endpoints give your frontend the resolved SEO data and the list of published URLs."
|
||||
And the group shows "2 routes"
|
||||
|
||||
Scenario: The two cards
|
||||
Then the group holds GET /v1/article/{id}/seo and GET /v1/site/{key}/sitemap, both with the badge "Public" and "API key OK", collapsed by default
|
||||
And GET /v1/article/{id}/seo is removed from the "Articles" group and GET /v1/site/{key}/sitemap is removed from the "Sites" group, so no route appears twice
|
||||
And POST /v1/article/{id}/seo/check stays in "Articles"
|
||||
|
||||
Scenario: Article SEO card
|
||||
When the user expands GET /v1/article/{id}/seo
|
||||
Then the card describes the resolved SEO object: title with the site template applied, description, canonical_url, robots, og{type,title,description,url,site_name,image,image_alt,locale}, twitter{card,title,description,image,image_alt}, image{url,alt,source}, authors[{name,url,same_as}], published_at, modified_at, fallbacks and json_ld
|
||||
And it says that drafts answer 404 to anonymous callers
|
||||
And it shows "No request body.", the fetch, curl and Response tabs in one CodeSnippet with Copy, and the error rows 400, 401 and 404 of the real API
|
||||
|
||||
Scenario: Sitemap card
|
||||
When the user expands GET /v1/site/{key}/sitemap
|
||||
Then the card shows the query rows page ("A whole number from 1. Default 1.") and size ("25, 50, 100 or 500. Default 100."), the item shape { url, modified_at, noindex } and that the total is in the X-Total-Count header
|
||||
And the path in its examples uses the sample site key
|
||||
And it shows the error rows of the real API: 400 with the body-mismatch message, 401, and 404 "site_not_found"
|
||||
|
||||
Scenario: Sidebar index and Jump to select
|
||||
Then the sticky section index lists, in this order, Authentication, Articles, Search and sharing, Media, Users and invites, Settings, Sites, Authors, Images and variants, Session only, Errors, Notes
|
||||
And the mobile "Jump to" select lists the same options in the same order
|
||||
When the user activates "Search and sharing" in the index
|
||||
Then the page scrolls to the group and the item has aria-current while it is in view
|
||||
And the group has an anchor and a deep link #seo
|
||||
|
||||
Scenario: Counts stay in sync
|
||||
Then the cards per group are Articles 8, Search and sharing 2, Media 10, Users and invites 6, Settings 1
|
||||
And the group "Sites" shows "1 route" and its description no longer mentions the sitemap
|
||||
And the total number of endpoint cards in API_GROUPS is unchanged
|
||||
And web/src/data/__tests__/apiCatalogue.spec.ts and web/src/views/__tests__/IntegrationView.spec.ts use these numbers and the new section list
|
||||
|
||||
Scenario: The PATCH reference lists the new fields
|
||||
Then PATCH /v1/article/{id} lists the optional fields slug, excerpt, seo_title, seo_description, cover_image_id, cover_image_alt, social_title, social_description, social_image_id, canonical_url, noindex and seo_dismissed, with the rules of the API
|
||||
And that is asserted by apiCatalogue.spec.ts and no field is added twice
|
||||
|
||||
Scenario: The 403 row of the status table
|
||||
Then the 403 row of the Errors table also states, in a note under its messages, that site SEO defaults are owner only and that article SEO fields need only the right to edit the article
|
||||
And the plain-text messages of that row are unchanged
|
||||
|
||||
Scenario: Nothing changes for the other groups
|
||||
Then the Session only group, the Errors table, the Images and variants section, the Notes and the sample error response are as before, apart from the 403 note
|
||||
|
||||
Scenario: The page still makes no request
|
||||
Then opening and expanding the new cards sends no /v1 request
|
||||
|
||||
Rule: French, layering and visual conformance
|
||||
|
||||
Scenario: French
|
||||
Given the language is "fr"
|
||||
Then every new string of the four screens, including "Needs attention", "Hidden", the tooltips, "Nothing needs attention", the Sites form copy, the dismiss button name, footnote and toast, the new group title, description, card descriptions and query rows, the 403 note, and the @not-in-design copy, is the French message
|
||||
And a missing French entry fails the i18n spec
|
||||
|
||||
Scenario: French plurals of the tooltip
|
||||
Given the language is "fr"
|
||||
Then a chip with 1 suggestion has the tooltip "1 suggestion" and with 2 or more "{n} suggestions" in French
|
||||
|
||||
Scenario: Every call goes through useApi
|
||||
Then no component calls fetch directly and every URL is relative
|
||||
|
||||
Scenario: Slice 3 leftovers
|
||||
Then a grep of web/src for hard-coded English in templates and for t(...) keys without a French entry finds none, or every finding is reported in the qa report with its file and line
|
||||
|
||||
Scenario: Visual conformance
|
||||
Then `task visual:check -- articles`, `-- sites`, `-- integration`, `-- editor`, `-- settings`, `-- users`, `-- profile` and `-- home` pass every frame at 1440x900 and 390x844, in light and dark
|
||||
And that includes the 5 new "Sites: SEO defaults" frames, the 3 new "Articles: search status" frames and every existing frame of those screens
|
||||
And the slice 3 mobile exceptions for the dismiss column are removed from web/visual/states.ts and the Editor panel frames pass without any exception
|
||||
And no per-state exception is added; a failure is reported to the user instead
|
||||
@@ -0,0 +1,104 @@
|
||||
# QA: SEO round, slice 4 (Sites defaults, Articles search status, Integration, suggestion dismissal)
|
||||
|
||||
SPA slice only. No Go change here: the API of `features/seo_data_backend.feature` and `features/seo_output_backend.feature` already exists, and `counts.suggestions` is covered by the httptest part of `features/articles_pagination_api.qa.md`, so this file has no httptest part. A wrong contract is reported as a backend defect.
|
||||
|
||||
Roles: the domain defines only `owner` and `admin`. "verified" is a verified account without either role.
|
||||
|
||||
## Automated SPA (Vitest + Vue Test Utils, `task test:web`)
|
||||
|
||||
Mock `useApi`'s `request` per case: GET/POST/PATCH /v1/site/..., GET /v1/article/ (items with `seo_status` and `seo_suggestions`, `counts`, `total`), PATCH /v1/article/{id}, POST /v1/article/{id}/seo/check, and the media routes of the shared picker. Mount SitesView, ArticleView, IntegrationView and EditorView inside DashboardShell with a resolved session and a test router. Mock matchMedia for desktop and mobile. Use fake timers for the search debounce. Do not freeze the system date. The rendering of "Updated …" is not asserted. Report the web tests as run or NOT RUN, never as passing when not run. One spec file per numbered group, under `web/src/views/__tests__/` (`SeoSites*.spec.ts`, `SeoArticles*.spec.ts`, `SeoDismiss*.spec.ts`, `SeoIntegration*.spec.ts`).
|
||||
|
||||
Regression: every existing Sites, Articles (ArticlesPagination, ArticlesPageSizeMemory, ArticlesSitesAuthors), Integration and EditorSeo* spec now sees the toolbar count request, the new fields and the dismiss buttons. Give them default mocks (every mocked `GET /v1/article/` envelope carries `counts.suggestions: 3`, and no spec mocks an extra count request any more; sites with the three SEO fields) rather than loosening unmocked-call checks, and show that they still pass.
|
||||
|
||||
1. Sites form fields: order, copy of states 1 and 2 (edit and add), placeholders, helpers, the counter, no "(optional)" on Site name, the "How articles use these defaults" block and its placement under the preview block.
|
||||
2. Live example: the Examples table (site name, name fallback, placeholder "Renew" fallback, `%title%` only, two `%site%`), updated on each keystroke, no request sent; global replace, not first occurrence.
|
||||
3. Template validation: the four invalid values (`just text`, `%site%`, `%TITLE%`, empty) on blur and on submit, nothing sent, focus on the first invalid field, example hidden, error cleared on a valid value, 400 `invalid_title_template` from the server shows the same message.
|
||||
4. Limits: maxlength 100, 200 and 320; the counter at 0, 45 and 320.
|
||||
5. Save payloads: PATCH holds only changed fields (assert exact JSON) for template only and for name + description + robots; POST omits the three fields when untouched and sends them when changed; the discard dialog on a changed SEO field; a site without the fields opens with defaults and "Save changes" sends nothing.
|
||||
6. Save failure and sessions: 500 and network failure keep the panel and the notice; 403 `owner_only` gives the existing toast; 401 goes to `/login?redirect=/settings/sites&reason=expired`; admin and verified users get the 403 page and no form.
|
||||
7. SeoStatusChip: the status table (ready, suggestions 1 and 2, hidden with and without a count), placement in the Status cell and in the card meta row, tooltip/accessible name (singular and plural), the unusable items (no seo_status, suggestions with 0, unknown status), the row action that keeps the chip.
|
||||
8. Toggle and URL: parse and write `seo` (`parseArticleQuery`, `toRouteQuery`, `sameArticleQuery`), page reset, q/status/sort/site/size kept, other changes keep seo, reset-to-1 table, opened with `?seo=suggestions&page=2`, unknown values dropped silently via replace (the six values), the request carries `seo=suggestions` only when on, tab counts unchanged and `counts.suggestions` unchanged by the toggle.
|
||||
9. Count: `counts.suggestions` 3, 0, absent (no count shown), list pending on first load (no count), list failure 500 and network error (no count, no extra notice, URL unchanged); the count keeps its last value while a new request is in flight; no request carrying `seo=suggestions&page=1&size=5` is ever sent (assert the mocked `useApi` is never called with it, with the toggle off, with q, status and site set, and after a change of each); the count is the same on and off, and unchanged by q, tab, site, sort, page and size.
|
||||
10. Empty states: "Nothing needs attention" with its action (clears seo only), the not-in-design combinations (search, Draft, Online, a site), paginator hidden, Retry notice still works.
|
||||
11. Single-site install: the Site column and filter are absent and everything above behaves the same.
|
||||
12. Dismiss ×, rendering: one button per row of the panel list, none in the compact section list; the footnote; accessible name with the message interpolated; Tab order (after "Go to …"); Enter and Space; visible focus class.
|
||||
13. Dismiss ×, behaviour: success sends exactly one PATCH with `seo_dismissed` equal to the saved list plus the code (assert exact JSON, no other field, no draft field); the button is busy and the row stays until 200; the row leaves; one new check follows; summary line and "All good" follow the check; the draft, the panel values and the editor status are untouched; focus table (first, second, last, and the last remaining row going to "Show dismissed"); 500 and network failure keep the row and show the toast, send no check; 401 mirrors the draft and redirects; 404 shows "Not found"; the three roles; Save and Publish stay enabled; "Show dismissed" sends `seo_dismissed: []` then a check.
|
||||
14. Integration group: position after Articles, group description, 2 routes, both cards "Public" and "API key OK", expanded content (fields, query rows, tabs, error rows with the real strings), no duplicate route in Articles or Sites, `POST …/seo/check` still in Articles, index and Jump to order, deep link #seo, counts 8/2/10/6/1 and "1 route" for Sites, the 403 note, no /v1 request.
|
||||
15. Catalogue spec: update the group list, the per-group counts, the Sites description, the "Public" assertions (they currently list `GET /v1/article/{id}/seo` and the sitemap with the Articles and Sites groups) and the 403 note.
|
||||
16. i18n: every new `t()` key has a French entry (extend the i18n spec), the French plurals, one French walk through the four screens.
|
||||
|
||||
## Visual (`task visual:check -- <screen>`, desktop and mobile, light and dark)
|
||||
|
||||
Setups go in `web/visual/states.ts`, one per state, with mocked /v1 and the board's own sample data. Hard gate: every capture within 10 %, no per-state exception. Reference frames: `DirectoryFrame.dc.html` (Sites form, SuggestionList), `AppFrame.dc.html` (Articles) and `IntegrationPage.dc.html`.
|
||||
|
||||
- Sites: SEO defaults (5): Edit: SEO defaults (Renew, `f.sname`, template `%title% | %site%`, example "How we price a bathroom renovation | Renew"), Add: defaults, Template: custom (site name Journal, template `%title% – %site%`), Template: not valid, Save failed. The existing Sites form frames (7) now contain the three fields and the new block: update their setups with the board values.
|
||||
- Articles: search status (3): Status chips (rows: 2 suggestions, hidden, 3 suggestions, 1 suggestion), Needs attention on, Needs attention: none. Every existing Articles and pagination frame now shows the toggle with the count 3 and the chips of the board rows, so each setup in `web/visual/states.ts` puts `counts.suggestions: 3` in the list mock and mocks no extra request. States whose "Updated" column or text is clock-sensitive follow what the existing setups already do (`skip: clock-sensitive`), and state 8 "Published" stays skipped.
|
||||
- Integration (8 existing states): the index and the mobile select now contain "Search and sharing", and the page has the new group (collapsed). Mock nothing new. The Navigation state's open select must list the new option. If the 403 note makes a capture exceed 10 %, report it to the user; do not add an exception.
|
||||
- Editor: the dismiss column is now implemented. Remove the five `withMobileException(..., dismissColumnReason)` wrappers (and the `dismissColumnReason` constant, `withMobileException` if nothing else uses it) in `web/visual/states.ts`, covering 'Panel: defaults', 'Panel: outside the soft ranges', 'Panel: cover without alt', 'Panel: choose cover' and the fifth state at line ~5828. Those states must pass `task visual:check -- editor` at the default 10 % in both viewports. If one still fails, report it; do not restore an exception.
|
||||
- Re-run Settings, Users, Profile and Home: report any capture above 10 %. Any failure needs the user's decision (an `approvedBy` exception or a design update).
|
||||
|
||||
## Final pass: slice 3 leftovers (required in the qa report)
|
||||
|
||||
1. Grep `web/src` (excluding `__tests__`) for text in templates not passed through `t(...)`, and for `title="..."`, `placeholder="..."` and `aria-label="..."` attributes with English literals, in the files of slice 3 (`SeoPanel.vue`, `SearchSharingSection.vue`, `SuggestionList.vue`, `ApiPreviewDialog.vue`, `SearchPreview.vue`, `SocialCardPreview.vue`, `SeoDisclosure.vue`, `EditorView.vue`, `seoCopy.ts`, `seoApiPreview.ts`, `seoPreview.ts`).
|
||||
2. Extract every `t('…')` key used by those files and by the files of this slice, and confirm each has an entry in `web/src/i18n/messages.ts` (the i18n spec must cover them). Spot check on the current tree: no missing entry found among the editor strings sampled; the new ones for this slice are still to add.
|
||||
3. Report findings by file and line. Fix those that belong to this slice. Anything else is reported to the user, not fixed silently.
|
||||
|
||||
## Exit conditions
|
||||
|
||||
- All Articles, Sites and Integration frames (existing and the 8 new ones) pass `task visual:check`, plus Editor, Settings, Users, Profile and Home re-run with no regression above 10 %.
|
||||
- The slice 3 dismiss-column exceptions are gone from `web/visual/states.ts` and `grep -n dismissColumnReason web/visual/states.ts` finds nothing; the Editor panel frames pass without exception.
|
||||
- Vitest specs reported honestly, run or NOT RUN.
|
||||
- `bun lint` clean. No comment added. No Go file changed.
|
||||
|
||||
## Divergences between the design and the real API (feed back to docs/design)
|
||||
|
||||
- Sitemap errors: the design says 404 "Site not found" and 400 "Invalid page or size."; the API answers 404 `site_not_found` and 400 with the generic body-mismatch message (`apperr.BodyErrorMessage`). The Integration cards use the real strings.
|
||||
- Article list: the design (routes.md) describes an array body with `X-Total-Count`; the code reads `{items, total, page, size, counts}`. Unchanged by this slice.
|
||||
- The 403 note under the Errors table has no layout in the design.
|
||||
- The 403 note under the Errors table is a design gap: it pushes the following rows down, so Integration "6. Errors" carries an approved exception (16 % desktop, 22 % mobile).
|
||||
- Hidden chip: the board wraps the "Hidden" chip under the Online badge in the 110 px Status column; the feature says it never wraps, and the app follows the feature.
|
||||
- Add: defaults: the board's Example row always falls back to "Renew"; the app falls back to the Name, then "Renew", as the feature requires.
|
||||
- Articles row 5: the design text says row 5 has 1 suggestion, but the board data draws no chip on it; the visual setup follows the board data.
|
||||
- Picker debt: on mobile the shared media picker sheet is taller and shows more tiles than the board, so Editor "Panel: choose cover" carries an approved mobile exception (29 %). The picker was not changed in this slice.
|
||||
|
||||
## Copy and behaviour not in the design (feed back to docs/design later)
|
||||
|
||||
Each has a French entry in `web/src/i18n/messages.ts`.
|
||||
|
||||
1. Source of the count (`counts.suggestions` of the list response).
|
||||
2. Zero shown as "0"; no count while pending, absent or on failure.
|
||||
3. Empty-state precedence when `seo=suggestions` is combined with a search, a tab or a site.
|
||||
4. Chips refresh only with the next list load after a row action.
|
||||
5. Items without a usable status show no chip.
|
||||
6. Example fallback to the name, then to "Renew" as site name.
|
||||
7. Accessible name of the chip on touch.
|
||||
8. The 403 row note on the Errors table.
|
||||
9. Dismiss ×: accessible name "Dismiss suggestion: <message>", the failure toast "Couldn't dismiss the suggestion" / "Try again in a moment.", the busy state, the focus rules, and "Show dismissed" restoring all codes.
|
||||
|
||||
## Proposed French (for review, in `web/src/i18n/messages.ts`)
|
||||
|
||||
| English key | French |
|
||||
| --- | --- |
|
||||
| Needs attention | À traiter |
|
||||
| Hidden | Masqué |
|
||||
| Hidden from search engines | Masqué des moteurs de recherche |
|
||||
| Nothing needs attention | Rien à traiter |
|
||||
| Every article has a clean check. Suggestions are optional, so this is just a bonus. | Tous les articles passent la vérification. Les suggestions sont facultatives, c'est un petit plus. |
|
||||
| Show all articles | Afficher tous les articles |
|
||||
| Site name | Nom du site |
|
||||
| Title template | Modèle de titre |
|
||||
| Use %title% for the article title and %site% for the site name. | Utilisez %title% pour le titre de l'article et %site% pour le nom du site. |
|
||||
| The template must contain %title%. | Le modèle doit contenir %title%. |
|
||||
| Example | Exemple |
|
||||
| Default description | Description par défaut |
|
||||
| How articles use these defaults | Comment les articles utilisent ces valeurs par défaut |
|
||||
| Dismiss suggestion: {0} | Ignorer la suggestion : {0} |
|
||||
| Couldn't dismiss the suggestion | Impossible d'ignorer la suggestion |
|
||||
| Show dismissed | Afficher les suggestions ignorées |
|
||||
| Search and sharing | Recherche et partage (already present) |
|
||||
|
||||
## Manual checks screenshots cannot cover
|
||||
|
||||
- Keyboard: tab order through the Sites form (the new fields sit between the image and the robots policy), Space and Enter on "Needs attention", focus on the first invalid field, the dismiss button order and focus after a row leaves, the index and the Jump to select (Enter, Escape).
|
||||
- Hover and touch: the chip tooltips on desktop, the chip text read by a screen reader, the toggle's pressed state.
|
||||
- Real `task dev`: the owner sets a template and sees the title change in "What the frontend gets"; dismiss a suggestion, reload, and see it stay hidden and the article's chip count drop; the Articles filter agrees with `curl '…/v1/article/?seo=suggestions'`; the sitemap card matches `curl` on `/v1/site/renew/sitemap` and its X-Total-Count; read the screens in French.
|
||||
@@ -0,0 +1,528 @@
|
||||
Feature: Sites and authors in the Editor, Articles and Profile screens
|
||||
|
||||
As a RenewCMS user who can edit articles
|
||||
I want to choose an article's site and bylines in the editor, see them in the articles list, and create my own author profile
|
||||
So that every article belongs to the right frontend and credits the right people
|
||||
|
||||
Background:
|
||||
Given the screens are EditorView (/article/:id/edit), ArticlesView (/article) and ProfileView (/profile),
|
||||
inside DashboardShell, per docs/design/routes.md
|
||||
And the visual spec of record is docs/design/screens/editor.md (group "Editor: site and authors"),
|
||||
articles.md (group "Articles: sites and authors") and profile.md (group "Profile: author profile"),
|
||||
with the error copy in docs/design/states.md. Exact copy is read from those files and is not repeated here
|
||||
And this feature supersedes the lines of features/sites_authors_screens.feature that said
|
||||
POST /v1/author/me is not exposed in the UI and that Editor, Articles and Profile are not modified
|
||||
And POST /v1/author/me answers 201 with the author and slug_adjusted, true when the stored slug differs from the plain slug of the name
|
||||
And the SPA calls, with relative URLs through useApi only:
|
||||
GET /v1/site/, GET /v1/author/ (page, size in 5, 25, 50 or 100, and q), POST /v1/author/, POST /v1/author/me,
|
||||
GET /v1/auth/me, GET /v1/article/{id}, PATCH /v1/article/{id} with site_id and author_ids,
|
||||
and GET /v1/article/?site={key}
|
||||
And an article carries site_id and authors [{id, name, slug, ...}] in list order, and the first author is the primary byline
|
||||
And GET /v1/auth/me carries "author" (the linked author, or null) and the SPA keeps it in the session store
|
||||
And the sites fixture is Renew (id 1, renew.example, default), Journal (id 2, journal.renew.example), Projects (id 3) and Archive (id 4)
|
||||
And the authors fixture is Inès Duarte (id 2), Jonas Pereira, Camille Roche and the Marta Alves of the design
|
||||
And an author is drawn as AuthorAvatar (initials fallback, square), several as AuthorStack
|
||||
And the domain defines only the roles "owner" and "admin" (internal/domain/user, RoleOwner and RoleAdmin)
|
||||
And "author rights" means owner and admin: they may create authors and edit any author
|
||||
And "verified" below names a verified account without the owner or admin role, which has no author rights
|
||||
And "several sites" means GET /v1/site/ returned more than one site
|
||||
And every visible string goes through t(...) with the English text as the key and a French entry in web/src/i18n/messages.ts
|
||||
And a scenario tagged @not-in-design uses copy or behaviour that docs/design does not define: it takes the
|
||||
proposal of this feature, has a French entry, and is listed in the .qa.md to be fed back to the design
|
||||
And the screens use Nuxt UI components and design tokens only, with no raw colors
|
||||
And the board frames of docs/design/source/AppFrame.dc.html and DirectoryFrame.dc.html are the layout tiebreaker
|
||||
|
||||
Rule: Editor: the "Site and authors" section (MetaSection)
|
||||
|
||||
Scenario: Collapsed by default with one site and an author
|
||||
Given the install has one site and article 12 has the author "Inès Duarte"
|
||||
And nothing is remembered for this browser
|
||||
When the user opens /article/12/edit on desktop
|
||||
Then the details sidebar shows a collapsed "Site and authors" section with the one-line summary "Inès Duarte"
|
||||
And no Site select is rendered
|
||||
And the section sits in the same place in every editor state that has the details sidebar
|
||||
|
||||
Scenario: Loading and not found
|
||||
When GET /v1/article/12 is pending
|
||||
Then the section header is shown with a skeleton summary
|
||||
When GET /v1/article/12 answers 404
|
||||
Then the "Not found" state shows no section
|
||||
|
||||
Scenario Outline: The section opens by itself when it needs attention
|
||||
Given nothing is remembered for this browser
|
||||
And the install has <sites> and the article has <authors>
|
||||
When the user opens the editor on desktop
|
||||
Then the section is <state>
|
||||
|
||||
Examples:
|
||||
| sites | authors | state |
|
||||
| one site | an author | collapsed |
|
||||
| several sites | an author | open |
|
||||
| one site | no authors | open |
|
||||
| several sites | no authors | open |
|
||||
|
||||
Scenario: The choice is remembered per browser and wins over auto-open
|
||||
Given the section is collapsed by default
|
||||
When the user opens it and later opens another article in the same browser
|
||||
Then the section is open there too
|
||||
When the user collapses it and reloads
|
||||
Then it is collapsed even if the install has several sites or the article has no authors
|
||||
And the choice is kept in localStorage and nothing is sent to the API
|
||||
|
||||
Scenario: Mobile: inside the Details sheet, closed by default
|
||||
Given the viewport is 390 px wide
|
||||
When the user opens the editor
|
||||
Then the section is not visible until the Details sheet is opened
|
||||
And inside the sheet it is closed unless a choice is remembered
|
||||
When the user opens it, closes the sheet and opens it again
|
||||
Then the section keeps the choice made in the sheet
|
||||
And the sheet and the desktop sidebar share the same storage key
|
||||
|
||||
@not-in-design
|
||||
Scenario Outline: Collapsed summary line variants
|
||||
Given the section is collapsed
|
||||
And the install has <sites> and the article has <authors>
|
||||
Then the summary line reads <summary>
|
||||
|
||||
Examples:
|
||||
| sites | authors | summary |
|
||||
| one site | Inès Duarte | "Inès Duarte" |
|
||||
| one site | Inès Duarte, Jonas Pereira, Camille Roche | "Inès Duarte +2" |
|
||||
| one site | no authors | "No authors" |
|
||||
| several sites | Inès Duarte on Journal | "Journal · Inès Duarte" |
|
||||
| several sites | no authors on Journal | "Journal · No authors" |
|
||||
|
||||
Rule: Site select
|
||||
|
||||
Scenario: One site: no Site select
|
||||
Given the install has one site
|
||||
When the section is open
|
||||
Then there is no Site select and the "Authors" list is the first control
|
||||
|
||||
Scenario: Several sites: Site select above the authors
|
||||
Given the install has several sites and article 12 is on "Journal"
|
||||
When the section is open
|
||||
Then a "Site" select above the authors shows "Journal" with "journal.renew.example"
|
||||
And the helper text reads "Canonical host: journal.renew.example"
|
||||
And the select is available to every role that can edit the article
|
||||
|
||||
Scenario: Site select options
|
||||
When the user opens the Site select
|
||||
Then each option shows the site name and its host, and the default site is first
|
||||
|
||||
Scenario: Changing the site is an edit
|
||||
Given the editor shows "Saved" and the article is on "Renew"
|
||||
When the user chooses "Journal"
|
||||
Then the status becomes "Unsaved changes" and Save is enabled
|
||||
And no request is sent yet
|
||||
When the user activates Save
|
||||
Then exactly one PATCH /v1/article/12 is sent containing site_id 2
|
||||
And on 200 the status is "Saved" and the helper text shows the new host
|
||||
|
||||
Rule: Author list
|
||||
|
||||
Scenario: Authors are an ordered list; the first is the primary byline
|
||||
Given article 12 has four authors
|
||||
When the section is open
|
||||
Then the first row shows the label "Primary" (@not-in-design)
|
||||
And each row has a drag handle and a remove button
|
||||
And the hint "Drag to reorder. The first author is the primary byline." is shown
|
||||
And a long name is truncated with an ellipsis and carries the full name in title and aria-label
|
||||
|
||||
Scenario: Reorder with the keyboard
|
||||
Given an author list of three with "Jonas Pereira" second
|
||||
When the user focuses the handle of "Jonas Pereira" and presses Space or Enter
|
||||
Then a live region announces the grabbed-row message of the design (position 2 of 3 and the key instructions)
|
||||
When the user presses ArrowUp
|
||||
Then the row moves to position 1 and the new position is announced
|
||||
When the user presses Space
|
||||
Then the row is dropped there and the status becomes "Unsaved changes"
|
||||
When the user grabs a row, moves it and presses Escape
|
||||
Then the row returns to its original position and the status does not change
|
||||
|
||||
@not-in-design
|
||||
Scenario: Dropped and cancelled announcements
|
||||
Given a row was grabbed
|
||||
When the user drops it with Space
|
||||
Then the live region announces the dropped message with the final position
|
||||
When the user cancels with Escape
|
||||
Then the live region announces the cancelled message and the original position
|
||||
|
||||
Scenario: Reorder with the pointer
|
||||
When the user drags a row
|
||||
Then the row lifts and a line shows the drop position
|
||||
When the user drops it
|
||||
Then the list takes the new order and the status becomes "Unsaved changes"
|
||||
|
||||
Scenario: Remove an author
|
||||
Given the list has "Inès Duarte" and "Jonas Pereira"
|
||||
When the user activates the remove button of "Inès Duarte"
|
||||
Then "Jonas Pereira" becomes "Primary" and the status becomes "Unsaved changes"
|
||||
When the last author is removed
|
||||
Then the list shows "No authors. This article will have no byline."
|
||||
|
||||
Scenario: Saving authors
|
||||
Given the author list was reordered to [Jonas Pereira, Inès Duarte]
|
||||
When the user activates Save
|
||||
Then exactly one PATCH /v1/article/12 is sent whose author_ids follow the list order
|
||||
And a list emptied by the user is sent as author_ids []
|
||||
And fields that did not change are not sent
|
||||
|
||||
Rule: Add author
|
||||
|
||||
Scenario: The combobox
|
||||
When the user activates "Add an author"
|
||||
Then a combobox opens with a "Search authors" field and GET /v1/author/ is requested with size 100
|
||||
And authors already on the article are checked and dimmed
|
||||
When the user activates a checked author
|
||||
Then nothing happens and the author is not added twice
|
||||
When the user picks "Camille Roche"
|
||||
Then she is appended to the list and the status becomes "Unsaved changes"
|
||||
|
||||
Scenario: Searching beyond the first 100 authors
|
||||
Given the install has more than 100 authors
|
||||
When the user types "Zoe" in "Search authors"
|
||||
Then GET /v1/author/ is requested with q "Zoe" and the list shows the matches
|
||||
|
||||
Scenario Outline: "Create author…" only for roles with author rights
|
||||
Given the session role is "<role>"
|
||||
When the combobox is open
|
||||
Then the "Create author…" row is <visible>
|
||||
|
||||
Examples:
|
||||
| role | visible |
|
||||
| owner | shown |
|
||||
| admin | shown |
|
||||
| verified | absent |
|
||||
|
||||
Scenario Outline: No match
|
||||
Given the session role is "<role>"
|
||||
When the user types "Zoe Lambert" and nobody matches
|
||||
Then the message "No author matches "Zoe Lambert"." is shown
|
||||
And <create>
|
||||
|
||||
Examples:
|
||||
| role | create |
|
||||
| owner | the row Create author "Zoe Lambert"… is shown |
|
||||
| verified | no create row is shown |
|
||||
|
||||
Scenario Outline: Authors could not be loaded
|
||||
When GET /v1/author/ fails with <failure> as the combobox opens
|
||||
Then the combobox shows "Couldn't load authors", "Check your connection and try again." and "Try again"
|
||||
And the article's authors in the list are untouched
|
||||
When the user activates "Try again"
|
||||
Then GET /v1/author/ is requested again
|
||||
|
||||
Examples:
|
||||
| failure |
|
||||
| status 500 |
|
||||
| a network error |
|
||||
|
||||
Rule: Create author dialog (owner and admin)
|
||||
|
||||
Scenario: Open the dialog from the combobox
|
||||
Given the session role is "owner"
|
||||
When the user activates Create author "Zoe Lambert"…
|
||||
Then the dialog "Create author" opens over the editor, with Name prefilled "Zoe Lambert", Slug "zoe-lambert" (Auto, same SlugField as Authors), "Cancel" and "Create author"
|
||||
And the unsaved text of the article is untouched
|
||||
|
||||
Scenario: Create succeeds
|
||||
Given the Create author dialog is filled with name "Zoe Lambert" and slug "zoe-lambert"
|
||||
When the user activates "Create author"
|
||||
Then exactly one POST /v1/author/ is sent with name and slug
|
||||
And the dialog closes, "Zoe Lambert" is appended to the author list and the status becomes "Unsaved changes"
|
||||
And the article's authors are not sent to the API until Save
|
||||
|
||||
Scenario: "This is me" only when the user has no author profile
|
||||
Given the session role is "owner" and GET /v1/auth/me has author null
|
||||
When the Create author dialog is open
|
||||
Then the checkbox "This is me" shows "Links the author to marta@renew.example."
|
||||
And it is unchecked until the user checks it
|
||||
When it is checked and the user creates the author
|
||||
Then POST /v1/author/ is sent with user_id of the current user
|
||||
And the session store now holds that author, so the hint and the Profile card show the profile
|
||||
|
||||
Scenario: No "This is me" when the user already has an author
|
||||
Given GET /v1/auth/me carries an author
|
||||
When the Create author dialog is open
|
||||
Then there is no "This is me" checkbox and no user_id is ever sent
|
||||
|
||||
Scenario: Slug taken
|
||||
When POST /v1/author/ answers 409 author_slug_taken
|
||||
Then the dialog shows "The slug "zoe-lambert" is already used by another author." and the action "Use zoe-lambert-2"
|
||||
And activating the action sets the slug and keeps the name
|
||||
|
||||
Scenario Outline: Create author failed
|
||||
When POST /v1/author/ fails with <failure>
|
||||
Then the dialog stays open with "Couldn't create the author" and "The article is unchanged. Try again in a moment."
|
||||
And the values are kept and the article is unchanged
|
||||
|
||||
Examples:
|
||||
| failure |
|
||||
| status 500 |
|
||||
| a network error |
|
||||
|
||||
Scenario: Role changed while the dialog was open
|
||||
When POST /v1/author/ answers 403
|
||||
Then the error toast of states.md "Only an owner or admin can change authors" shows and the dialog closes
|
||||
|
||||
Rule: "Create my author profile" hint (every role)
|
||||
|
||||
Scenario Outline: The hint appears
|
||||
Given the session role is "<role>", GET /v1/auth/me has author null, the article has no authors and the hint was never dismissed
|
||||
When the section is open
|
||||
Then the dismissible hint "You don't have an author profile yet" with "Create my author profile" is shown
|
||||
And the list shows "No authors. This article will have no byline."
|
||||
|
||||
Examples:
|
||||
| role |
|
||||
| owner |
|
||||
| admin |
|
||||
| verified |
|
||||
|
||||
Scenario Outline: The hint stays away
|
||||
Given <condition>
|
||||
Then the hint is not shown
|
||||
|
||||
Examples:
|
||||
| condition |
|
||||
| the user already has an author profile |
|
||||
| the article has an author |
|
||||
| the hint was dismissed by this user |
|
||||
|
||||
Scenario: Create my author profile
|
||||
Given the hint is shown
|
||||
When the user activates "Create my author profile"
|
||||
Then exactly one POST /v1/author/me is sent with no body and no dialog opens
|
||||
And on 201 the new author is added to the list as the primary author
|
||||
And the status becomes "Unsaved changes" and the hint disappears
|
||||
And the session store holds the author, so /profile shows the "Created" card
|
||||
|
||||
@not-in-design
|
||||
Scenario: The hint-success toast
|
||||
When POST /v1/author/me answers 201
|
||||
Then a success toast shows "Author profile created" and "Marta Alves is now your byline." (the Profile copy)
|
||||
|
||||
Scenario Outline: Create my author profile fails
|
||||
When POST /v1/author/me fails with <failure>
|
||||
Then the hint stays, an error toast shows "Couldn't create your author profile" and "Try again in a moment."
|
||||
And the article is unchanged
|
||||
|
||||
Examples:
|
||||
| failure |
|
||||
| status 500 |
|
||||
| a network error |
|
||||
|
||||
Scenario: The profile already exists (409)
|
||||
When POST /v1/author/me answers 409 user_already_linked
|
||||
Then GET /v1/auth/me is requested again, the hint disappears and the existing author is offered in the combobox
|
||||
|
||||
Scenario: Dismissing the hint
|
||||
When the user dismisses the hint
|
||||
Then it disappears and does not come back for this user in this browser, on later visits to any article
|
||||
And the dismissal is kept in localStorage keyed by user id
|
||||
And dismissing sends no request
|
||||
|
||||
Rule: Editor failures and keyboard
|
||||
|
||||
Scenario: The sites could not be loaded
|
||||
Given GET /v1/site/ fails
|
||||
When the user opens the editor
|
||||
Then the editor still loads, no Site select is rendered and no notice is shown
|
||||
|
||||
Scenario Outline: Save is refused for a site or author that no longer exists
|
||||
Given the user changed the <what>
|
||||
When PATCH /v1/article/12 answers 404 <code>
|
||||
Then the existing "Save failed" state is shown with the changes kept
|
||||
And an info toast "<toast>" shows and the lists are reloaded
|
||||
|
||||
Examples:
|
||||
| what | code | toast |
|
||||
| site | site_not_found | That site no longer exists |
|
||||
| author | author_not_found | That author no longer exists |
|
||||
|
||||
Scenario: Existing save behaviour is kept
|
||||
Given the user changed only the site or the authors
|
||||
Then "Save and publish", the leave-confirmation dialog, Ctrl/Cmd S and the draft kept in sessionStorage after a session expiry treat the change like any other edit
|
||||
And the restored draft shows "Unsaved changes" with the chosen site and author order
|
||||
|
||||
Rule: Articles list: Authors column, Site column and Site filter
|
||||
|
||||
Scenario Outline: Authors column on every frame
|
||||
Given an article with <authors>
|
||||
When the list is shown
|
||||
Then the Authors cell shows <cell>
|
||||
|
||||
Examples:
|
||||
| authors | cell |
|
||||
| no authors | "—" |
|
||||
| one author | one avatar |
|
||||
| three | three avatars, no "+N" |
|
||||
| five | three avatars and "+2" |
|
||||
|
||||
Scenario: Mobile Authors cell, and no site on the cards
|
||||
Given the viewport is 390 px wide
|
||||
Then the card shows the avatars with the first name of the first author, as drawn in the board
|
||||
And the card shows no site, as in the design
|
||||
|
||||
Scenario: One site: no Site column and no filter
|
||||
Given the install has one site
|
||||
Then the list has an Authors column, no Site column and no Site filter
|
||||
|
||||
Scenario: Several sites: Site column and Site filter
|
||||
Given the install has several sites
|
||||
Then the list has a Site column showing the site name as read-only text for every role
|
||||
And the toolbar has a Site select with "All sites" and every site name
|
||||
|
||||
Scenario: Choosing a site
|
||||
Given the list is on page 3
|
||||
When the user chooses "Journal" in the Site filter
|
||||
Then the URL becomes /article?site=journal with the page omitted
|
||||
And GET /v1/article/?site=journal is requested with the current q, status and sort
|
||||
And the tab counts still show the full list
|
||||
|
||||
Scenario Outline: Other changes keep the site
|
||||
Given the URL holds ?site=journal
|
||||
When the user <action>
|
||||
Then ?site=journal stays in the URL
|
||||
|
||||
Examples:
|
||||
| action |
|
||||
| searches for "plaster" |
|
||||
| changes the tab |
|
||||
| changes the sort |
|
||||
| goes to page 2 |
|
||||
| changes the page size |
|
||||
|
||||
Scenario: Choosing "All sites"
|
||||
Given the URL holds ?site=journal
|
||||
When the user chooses "All sites"
|
||||
Then site leaves the URL, the page resets to 1 and the full list is requested
|
||||
|
||||
Scenario: Opening a URL with a site
|
||||
When the user opens /article?site=journal&page=2
|
||||
Then the Site filter shows "Journal" and GET /v1/article/?site=journal&page=2 is requested
|
||||
|
||||
Scenario Outline: A site key that cannot be used is dropped silently
|
||||
Given the URL holds <query>
|
||||
Then the key is removed from the URL with no notice and the unfiltered list is requested
|
||||
|
||||
Examples:
|
||||
| query |
|
||||
| ?site=nope |
|
||||
| ?site=renew on a one-site install |
|
||||
|
||||
Scenario: No articles on a site
|
||||
Given ?site=archive and the response is empty with no search and the tab "All"
|
||||
Then the state shows "No articles on "Archive"", "Move articles here from the editor, or choose another site." and "Show all sites"
|
||||
When the user activates "Show all sites"
|
||||
Then site leaves the URL and the full list is requested
|
||||
|
||||
Scenario: Zero results on a site with a search or another tab
|
||||
Given ?site=archive and a search or a tab other than "All" is active
|
||||
Then the existing "No results" or "No drafts" state is shown
|
||||
|
||||
Scenario: Existing states keep working with a site
|
||||
Then Loading, Empty, row actions, delete and pagination states behave as in docs/design/screens/articles.md with the site filter applied
|
||||
|
||||
Scenario: The sites could not be loaded
|
||||
Given GET /v1/site/ fails
|
||||
Then the list renders as a single-site install, with no Site column and no Site filter
|
||||
|
||||
Rule: Profile: the Author profile card
|
||||
|
||||
Scenario: Position and roles
|
||||
Then in every Profile frame the "Author profile" card sits between "Account" and "Password"
|
||||
And it is shown to every role
|
||||
|
||||
Scenario: Loading
|
||||
When GET /v1/auth/me is pending
|
||||
Then the card shows a skeleton
|
||||
|
||||
Scenario: No author profile
|
||||
Given GET /v1/auth/me has author null
|
||||
Then the card shows the copy of state 1, a "Create my author profile" button and the line "Uses your display name, Marta Alves. You can change it afterwards."
|
||||
|
||||
@not-in-design
|
||||
Scenario: No author profile and no display name
|
||||
Given GET /v1/auth/me has author null and no display name
|
||||
Then the line reads "Uses your username, marta. You can change it afterwards."
|
||||
|
||||
Scenario: Create succeeds
|
||||
When the user activates "Create my author profile"
|
||||
Then exactly one POST /v1/author/me is sent
|
||||
And on 201 the card shows "Author profile created", "Marta Alves is now your byline." and "Edit author" with "Linked to your account. New articles start with this author."
|
||||
And the session store holds the author
|
||||
|
||||
Scenario: Slug adjusted
|
||||
Given the 201 answer has slug_adjusted true and the slug "marta-alves-2"
|
||||
Then no error is shown and the card also shows "Your slug is marta-alves-2" with "marta-alves was already used by another author. You can change it in Edit author."
|
||||
|
||||
Scenario Outline: The notice follows slug_adjusted, never the slug itself
|
||||
Given the author's name is "<name>"
|
||||
And the 201 answer has the slug "<returned>" and slug_adjusted <flag>
|
||||
Then the card <notice> the "Your slug is" notice
|
||||
|
||||
Examples:
|
||||
| name | returned | flag | notice |
|
||||
| Marta Alves | marta-alves | false | does not show |
|
||||
| Marta Alves | marta-alves-2 | true | shows |
|
||||
| Inès Duarte | ines-duarte-2 | true | shows |
|
||||
| Jean-Luc O'Neil | jean-luc-o-neil | false | does not show |
|
||||
| Zoë Müller | zoe-muller | false | does not show |
|
||||
| Agent 007 | agent-007 | false | does not show |
|
||||
| Agent 007 | agent-007-2 | true | shows |
|
||||
|
||||
Scenario Outline: Create fails
|
||||
When POST /v1/author/me fails with <failure>
|
||||
Then the card shows "Couldn't create your author profile" and "Try again in a moment." and the button stays available
|
||||
|
||||
Examples:
|
||||
| failure |
|
||||
| status 500 |
|
||||
| a network error |
|
||||
|
||||
Scenario: Profile already exists (409)
|
||||
When POST /v1/author/me answers 409 user_already_linked
|
||||
Then GET /v1/auth/me is requested again and the card shows the existing author
|
||||
|
||||
Scenario: Existing author on load
|
||||
Given GET /v1/auth/me carries an author
|
||||
Then the card shows the author's name, "Edit author" and "Linked to your account. New articles start with this author." without the "Created" banner
|
||||
|
||||
Scenario: Edit own author without author rights
|
||||
Given the session role has no author rights and has a linked author
|
||||
When the user activates "Edit author"
|
||||
Then the author form opens titled "Edit Marta Alves" with Linked user "marta@renew.example" locked, "This is your author profile. Only an owner or admin can change the link." and "Save changes"
|
||||
And there is no "Unlink" and no delete action on the form or on the screen
|
||||
When the user saves a change
|
||||
Then exactly one PATCH /v1/author/{id} is sent with only the changed fields
|
||||
|
||||
@not-in-design
|
||||
Scenario: Edit author as owner or admin
|
||||
Given the session role is "owner" or "admin" with a linked author
|
||||
When the user activates "Edit author" on /profile
|
||||
Then the existing AuthorFormPanel opens in place, on /profile, with "Unlink" allowed
|
||||
|
||||
Scenario: Language and session
|
||||
Given the language is "fr"
|
||||
Then every new string on the three screens is the French message
|
||||
And a 401 on any new call lands on /login?redirect=<path>&reason=expired and a 403 from an unverified account lands on /register/pending
|
||||
|
||||
Rule: Catalogue and copy left over from the Sites and Authors screens
|
||||
|
||||
Scenario: Authors routes in the API catalogue
|
||||
Then web/src/data/apiCatalogue.ts has an "Authors" group and an "Authors · owner and admin" group covering every /v1/author route, including POST /v1/author/me as a session-only route
|
||||
And web/src/data/__tests__/apiCatalogue.spec.ts covers them
|
||||
|
||||
Scenario: French strings for the catalogue groups
|
||||
Given the language is "fr"
|
||||
Then the catalogue group titles "Sites", "Sites · owner only", "Authors" and "Authors · owner and admin" and their descriptions have French entries
|
||||
|
||||
Scenario: Session-only rows
|
||||
Then the session-only routes of Sites and Authors appear in SESSION_GROUPS with SESSION_REQUIRED_MESSAGE
|
||||
|
||||
Scenario: The owner_only copy of the design board
|
||||
Then the 403 page copy "You don't have access to Sites" with "Only the owner can manage sites. Ask the owner of this site if you need a change."
|
||||
And the action toast "Only the owner can manage sites" with "Ask the owner of this site."
|
||||
exist in the SPA and have French entries
|
||||
@@ -0,0 +1,64 @@
|
||||
# QA: Sites and authors in Editor, Articles and Profile
|
||||
|
||||
SPA slice only. No Go change: the API already exists (commits "Sites feature backend" and "Authors feature backend"). A wrong contract is reported as a backend defect.
|
||||
|
||||
Roles: the domain defines only `owner` and `admin` (`internal/domain/user`). There is no "member" constant. "verified" in the feature and below is a verified account without the owner or admin role, which has no author rights. The earlier `sites_authors_screens` files still say "member" for the same account; that wording is left as is.
|
||||
|
||||
## Automated SPA (Vitest + Vue Test Utils, `task test:web`)
|
||||
|
||||
Mock `useApi`'s `request` per case for GET /v1/site/, GET /v1/author/, POST /v1/author/, POST /v1/author/me, GET /v1/auth/me, GET and PATCH /v1/article/{id} and GET /v1/article/. Mount EditorView, ArticlesView and ProfileView inside DashboardShell with a resolved session and a test router. Roles: "owner" (Marta Alves, no author), "admin", "verified". Mock matchMedia for desktop and mobile. Use localStorage fakes for the remembered section state and the dismissed hint. Do not freeze the system date. Report the web tests as run or NOT RUN, never as passing when not run.
|
||||
|
||||
Regression: every existing Editor, Articles, ArticlesPagination, ArticlesPageSizeMemory and Profile spec now sees the new calls. Give them default mocks (one site, one author, author null where relevant) rather than loosening unmocked-call checks, and show that they still pass.
|
||||
|
||||
1. MetaSection: collapsed summary "Inès Duarte"; open/closed Examples (sites x authors); remembered choice wins over auto-open; same key in the desktop sidebar and the mobile sheet; mobile closed in the Details sheet; loading skeleton; no section on 404; summary variants.
|
||||
2. SiteSelect: absent with one site; present with helper "Canonical host: ..."; options with name and host and the default first; choosing marks "Unsaved changes"; the PATCH contains `site_id` and only the changed fields; GET /v1/site/ failure renders no select and no notice.
|
||||
3. AuthorList: Primary label, handle, remove, truncation with title and aria-label; keyboard reorder (grab, ArrowUp/Down, drop, Escape, live region text including dropped and cancelled); pointer reorder (use the sortable test helper; assert order and "Unsaved changes"); removing the last author shows the no-byline text; PATCH `author_ids` order, `[]` when emptied, absent when unchanged.
|
||||
4. AuthorSelect: opens with GET /v1/author/ size 100; only sizes 5, 25, 50 or 100 are ever sent (other sizes answer 400); `q` search beyond the first 100; checked and dimmed items do nothing when activated; append on pick; "Create author…" per role (owner, admin, verified); no-match message with and without the create row; error state with "Try again".
|
||||
5. Create author dialog: prefilled name and auto slug; POST body; appended to the list and "Unsaved changes"; the article's authors are not sent before Save; "This is me" only when author is null (default unchecked) and sends `user_id`; session store updated; slug taken and the "Use zoe-lambert-2" action; failure Examples; 403 toast.
|
||||
6. CreateAuthorHint: shown by role Examples; hidden for author present, article with authors, dismissed; POST /v1/author/me with no body and no dialog; list and toast; session updated; failure Examples; 409 refetch; dismissal stored in localStorage by user id and never re-shown; no request on dismiss.
|
||||
7. Editor save: a site-only or author-only edit enables Save, "Save and publish", leave-confirmation and the sessionStorage draft restore; 404 `site_not_found` / `author_not_found` handling with the "Save failed" state and the info toast.
|
||||
8. ArticlesView: Authors cell Examples (0, 1, 3, 5 authors); mobile cell and no site on the cards; Site column and filter only with several sites; `?site=` read, written, combined with q/tab/sort/size/page and page reset; "All sites"; unknown key and single-site key dropped silently; "No articles on "Archive"" and "Show all sites"; "No results"/"No drafts" with a site and a search or tab; GET /v1/site/ failure falls back to single-site; tab counts unchanged.
|
||||
9. ProfileView AuthorProfileCard: position between Account and Password for all roles; skeleton while loading; states 1 to 5 (no profile, error, created, created with adjusted slug, edit own author with locked link and no Unlink or delete); owner/admin Edit author reuses AuthorFormPanel with Unlink allowed; POST /v1/author/me count; 409 refetch; author present on load.
|
||||
10. Slug adjusted comes from the server: POST /v1/author/me returns `slug_adjusted` and the SPA shows the "Your slug is" notice from that flag only. Vitest cases feed mocked responses (accented names, apostrophes, collision `marta-alves-2`, `agent-007` with the flag false) and check `baseSlugOf` strips only the one collision suffix. The slug rule itself is covered in Go (`features/authors_backend.feature`, `test/authors_backend_http_test.go`).
|
||||
11. i18n: every new `t()` key has a French entry (extend the i18n spec); one French walk through the three screens.
|
||||
12. Catalogue group (final scenario group): the Authors routes and groups in `apiCatalogue.ts` and its spec, French titles and descriptions for the Sites and Authors groups, Sites and Authors rows in `SESSION_GROUPS` with `SESSION_REQUIRED_MESSAGE`, and the owner_only 403 page and toast copy with French entries.
|
||||
|
||||
Handoff note for the coder: a grep of the SPA after the earlier commit found the Sites catalogue groups ("Sites", "Sites · owner only") but no `/v1/author` group, no French entry for "Sites · owner only", and no `owner_only` copy in `web/src`; `SESSION_REQUIRED_MESSAGE` and `SESSION_GROUPS` exist. Treat item 12 as work to do, and verify each part before adding it.
|
||||
|
||||
## Visual (`task visual:check -- <screen>`, desktop and mobile, light and dark)
|
||||
|
||||
Setups go in `web/visual/states.ts` (one setup per state, mocked /v1, the board's own sample data, no `skip` unless the state depends on the date). Hard gate: every capture within 10 %, with no per-state exception. Reference frames: `AppFrame.dc.html` (section, Articles columns, Profile card) and `DirectoryFrame.dc.html` (section content).
|
||||
|
||||
- Editor, all existing frames that show the sidebar: the section collapsed with the summary "Inès Duarte" (one site, one author). Their existing setups need default mocks for /v1/site/ and the article's authors. Not found has none. Loading shows the skeleton summary.
|
||||
- Editor: site and authors (16): open one site, several sites, Site select open, no authors with hint, many authors, add open, no match, add open (no create), no match (no create), add error, reorder keyboard, reorder pointer, create dialog, for me, slug taken, failed. The "(no create)" frames use a verified session.
|
||||
- Articles (existing frames + pagination frames): the Authors column in every frame. Articles: sites and authors (3): several sites, Site filter open, no articles on a site.
|
||||
- Profile (existing frames): the Author profile card in its default state in every frame. Profile: author profile (5): no profile, error, created, slug adjusted, edit own author.
|
||||
- Re-run Settings, Users and Home too: report any capture that moves above 10 %. Any failure needs the user's decision (an `approvedBy` exception or a design update).
|
||||
|
||||
## Exit conditions
|
||||
|
||||
- All existing Editor, Articles and Profile frames pass `task visual:check`, with no per-state exception.
|
||||
- The new frames pass.
|
||||
- Settings, Users and Home are re-run for regressions.
|
||||
- Vitest specs are reported honestly, run or NOT RUN.
|
||||
|
||||
## Copy and behaviour not in the design (feed back to docs/design later)
|
||||
|
||||
Each has a French entry in `web/src/i18n/messages.ts`.
|
||||
|
||||
1. Editor hint-success toast: "Author profile created" / "Marta Alves is now your byline." (reuses the Profile copy).
|
||||
2. The row label "Primary".
|
||||
3. The "dropped" and "cancelled" live-region announcements (only "grabbed" is in the design).
|
||||
4. Collapsed-summary variants: "Inès Duarte +2", "No authors", "Journal · Inès Duarte", "Journal · No authors".
|
||||
5. Profile line without a display name: "Uses your username, marta. You can change it afterwards."
|
||||
6. Profile "Edit author" for owner and admin: AuthorFormPanel in place on /profile with Unlink allowed.
|
||||
|
||||
## Known gap (no change in this slice)
|
||||
|
||||
`GET /media/{id}/usage` returns articles only. An image used as an author avatar or a site social image can therefore look unused in the Media detail panel and in the delete confirmation. This needs a Go change and is not part of this slice.
|
||||
|
||||
## Manual checks screenshots cannot cover
|
||||
|
||||
- Keyboard: tab order through the section, the Site select, handles, remove buttons, "Add an author", the dialog and the hint close button; focus returns to the opener after the dialog; the live region reads the grabbed, moved, dropped and cancelled messages in a screen reader.
|
||||
- Pointer: drag feel, the drop line, scroll while dragging on mobile.
|
||||
- Real `task dev`: an owner creates an author inline with "This is me", then opens /profile; a verified account creates a profile from the hint, saves, and the Authors column shows the avatar; filter by site and share the URL.
|
||||
@@ -0,0 +1,634 @@
|
||||
Feature: Sites and Authors screens
|
||||
|
||||
As a RenewCMS owner or admin
|
||||
I want /settings/sites and /authors to list, add, edit and delete sites and authors
|
||||
So that every article belongs to a frontend and credits the right bylines
|
||||
|
||||
Background:
|
||||
Given /settings/sites is a verified route rendered as SitesView and /authors is a verified route
|
||||
rendered as AuthorsView, both inside DashboardShell, per docs/design/routes.md
|
||||
And both screens are built from the shared directory pieces, defined once and not redrawn:
|
||||
DirectoryList, DirectoryPanel (the slide-over), ReassignDialog, SlugField and MediaField
|
||||
And the screens call, with relative URLs through useApi only, GET, POST, PATCH and DELETE on
|
||||
/v1/site/ and /v1/author/, PATCH /v1/site/{id}/default and GET /v1/user/
|
||||
And POST /v1/author/me and the changes to the Editor, Articles and Profile screens are specified in features/sites_authors_integration.feature
|
||||
And a site has the fields id, name, key, base_url, default_social_image_id, default_robots
|
||||
("index" or "noindex"), locale, is_default and article_count
|
||||
And an author has the fields id, name, slug, bio, avatar_id, website, social_links, user_id,
|
||||
is_linked, article_count and, for owner and admin only, user_email
|
||||
And an error answered by the API is a plain-text code, and the SPA maps the code to the copy
|
||||
of docs/design/states.md, never showing the code itself
|
||||
And the sites fixture is, in list order:
|
||||
| name | key | base_url | articles | default |
|
||||
| Renew | renew | https://renew.example | 268 | yes |
|
||||
| Journal | journal | https://journal.example | 38 | no |
|
||||
| Projects | projects | https://projects.example | 6 | no |
|
||||
| Archive | archive | https://archive.example | 0 | no |
|
||||
And the authors fixture includes "Inès Duarte" (slug ines-duarte, linked, 9 articles),
|
||||
"Camille Roche" (slug camille-roche, guest, 3 articles), "Léa Fontaine" (slug lea-fontaine,
|
||||
guest, 0 articles) and one author with 1 article
|
||||
And every visible string goes through t(...) with the English text as the key and its French
|
||||
entry in web/src/i18n/messages.ts
|
||||
And the screens use Nuxt UI components and design tokens only, with no raw colors
|
||||
And the board frames of docs/design/source/DirectoryFrame.dc.html are the layout tiebreaker
|
||||
|
||||
Rule: Sites list
|
||||
|
||||
Scenario: Sites: default (owner)
|
||||
Given the session role is "owner"
|
||||
And GET /v1/site/ answers 200 with the sites fixture
|
||||
When the user navigates to /settings/sites
|
||||
Then the page shows "Sites", "The frontends that display your content." and a primary
|
||||
"Add site" button
|
||||
And the columns are "Site", "Base URL" and "Articles"
|
||||
And each row shows the name with its key and the base URL
|
||||
And the counts read "268 articles", "38 articles", "6 articles" and "No articles"
|
||||
And "Renew" carries a "Default" badge
|
||||
And a site whose default_robots is "noindex" carries a "Noindex" badge
|
||||
And below md the rows are cards and a full-width "Add site" button is pinned to the bottom
|
||||
|
||||
Scenario: Sites: only the default site
|
||||
Given GET /v1/site/ answers 200 with only the default site
|
||||
When the owner navigates to /settings/sites
|
||||
Then the row is listed and the hint "Add another site if your content is shown on more than one
|
||||
frontend. Each article belongs to one site." appears under the list
|
||||
And no empty-state wall is drawn
|
||||
|
||||
Scenario: Sites: loading
|
||||
Given GET /v1/site/ is pending
|
||||
When the owner navigates to /settings/sites
|
||||
Then no skeleton shows before 150 ms
|
||||
And after 150 ms skeleton rows are drawn and the list has aria-busy "true"
|
||||
|
||||
Scenario Outline: Sites: error on load
|
||||
Given GET /v1/site/ fails with <failure>
|
||||
When the owner navigates to /settings/sites
|
||||
Then an alert shows "Couldn't load sites", "Check your connection and try again." and a
|
||||
"Try again" action
|
||||
And no rows are drawn
|
||||
When the user activates "Try again"
|
||||
Then GET /v1/site/ is requested again and, on 200, the list replaces the alert
|
||||
|
||||
Examples:
|
||||
| failure |
|
||||
| status 500 |
|
||||
| a network error |
|
||||
|
||||
Scenario: Sites: row menu
|
||||
Given the sites list is shown
|
||||
When the user activates the ellipsis button of "Journal", or presses Enter on it
|
||||
Then a menu offers "Edit", "Set as default" and "Delete…"
|
||||
And below md the menu is a bottom sheet titled "Journal"
|
||||
|
||||
Scenario: Sites: delete unavailable on the default site
|
||||
Given the sites list is shown
|
||||
When the user opens the menu of "Renew"
|
||||
Then "Delete…" has aria-disabled "true" and stays focusable
|
||||
And a tooltip on desktop, and text in the sheet on touch, reads "The default site can't be
|
||||
deleted. Make another site the default first."
|
||||
And activating it opens no dialog and sends no request
|
||||
|
||||
Scenario: Sites: set as default, confirm and success
|
||||
Given the sites list is shown
|
||||
When the user chooses "Set as default" on "Journal"
|
||||
Then a dialog titled "Make Journal the default site?" reads "New articles start on this site.
|
||||
Articles that are already on other sites stay where they are." with "Cancel" and
|
||||
"Make default"
|
||||
When the user activates "Make default"
|
||||
Then exactly one PATCH /v1/site/2/default is sent with no body
|
||||
And the button reads "Saving…" while it runs
|
||||
And on 200 the "Default" badge moves to "Journal" and a toast shows "Default site changed" and
|
||||
"\"Journal\" is now the default site."
|
||||
|
||||
Scenario Outline: Sites: set as default, failures
|
||||
Given the "Make Journal the default site?" dialog is open
|
||||
When PATCH /v1/site/2/default answers <status>
|
||||
Then <outcome>
|
||||
|
||||
Examples:
|
||||
| status | outcome |
|
||||
| 500 | the dialog stays open with the notice "Couldn't save the site. Your changes are still here. Try again in a moment." |
|
||||
| 404 | the dialog closes, the row leaves the list and an info toast shows "That site no longer exists" and "It was deleted somewhere else, so we removed it from the list." |
|
||||
| 403 | the dialog closes and an error toast shows "Only the owner can manage sites" and "Ask the owner of this site." |
|
||||
|
||||
Rule: Sites access
|
||||
|
||||
Scenario: Sites: hidden entry for an admin
|
||||
Given the session role is "admin"
|
||||
When the user opens /settings
|
||||
Then the sidebar has no "Publishing" group and no "Sites" entry
|
||||
And the page has no "Publishing" card and no "Manage sites" row
|
||||
|
||||
Scenario: Sites: the owner sees the entry
|
||||
Given the session role is "owner"
|
||||
When the user opens /settings
|
||||
Then the sidebar has a "Publishing" group with a "Sites" entry linking to /settings/sites
|
||||
And Settings has a "Publishing" card with a "Manage sites" row linking to /settings/sites
|
||||
|
||||
Scenario Outline: Sites: forbidden (403 page)
|
||||
Given the session role is "<role>"
|
||||
When the user opens <path>
|
||||
Then the page shows "You don't have access to Sites", "Only the owner can manage sites. Ask the
|
||||
owner of this site if you need a change." and a "Back to Settings" button
|
||||
And the user is not redirected, no slide-over opens and the sidebar has no Sites entry
|
||||
When the user activates "Back to Settings"
|
||||
Then the user lands on /settings
|
||||
|
||||
Examples:
|
||||
| role | path |
|
||||
| admin | /settings/sites |
|
||||
| member | /settings/sites |
|
||||
| admin | /settings/sites?edit=journal |
|
||||
|
||||
Scenario: Sites: the API answers 403 where the SPA expected the owner
|
||||
Given the session role is "owner" but the API answers 403 "Only the owner can do this."
|
||||
When the answer is for a page load
|
||||
Then the 403 page shows
|
||||
When the answer is for an action
|
||||
Then an error toast shows "Only the owner can manage sites" and "Ask the owner of this site."
|
||||
|
||||
Rule: Sites form
|
||||
|
||||
Scenario: Sites form: add, empty
|
||||
Given the sites list is shown and the default site is "Renew"
|
||||
When the user activates "Add site" (the page header button, or the pinned bottom button below md)
|
||||
Then a slide-over titled "Add site" opens, a 92 % bottom sheet below md
|
||||
And it has the fields Name (placeholder "e.g. Journal"), Key (placeholder "Generated from the
|
||||
name"), Base URL (placeholder "https://blog.example.com", help "The public address of the
|
||||
frontend. Use https and no path."), "Default social image (optional)" with "Choose image"
|
||||
and "Used when an article has no image of its own.", "Default robots policy" with "Index"
|
||||
and "Noindex" and "Search engines may list this site's pages.", "Locale (optional)"
|
||||
(placeholder "e.g. en or fr-CH", help "A language tag. Leave empty if the site has no
|
||||
single language."), and the switch "Make this the default site" with "New articles start
|
||||
here. The current default is Renew."
|
||||
And a "Canonical URL preview" is shown, plus "Cancel" and "Add site"
|
||||
And Name has focus
|
||||
|
||||
Scenario: Sites form: key from the name
|
||||
Given the Add site slide-over is open
|
||||
When the user types "Journal" in Name
|
||||
Then Key shows "journal" with an "Auto" badge and the help "Lowercase letters, numbers and
|
||||
hyphens. Used in API paths. It can't be changed after the site is added."
|
||||
When the user activates the pencil
|
||||
Then Key becomes editable and no longer follows the name
|
||||
|
||||
Scenario Outline: Sites form: base URL not valid
|
||||
Given the Add site slide-over is open with a valid name and key
|
||||
When the user enters base URL "<value>" and leaves the field or submits
|
||||
Then no request is sent
|
||||
And the Base URL error reads "<message>"
|
||||
|
||||
Examples:
|
||||
| value | message |
|
||||
| http://blog.example.com | Use https. For example https://blog.example.com. |
|
||||
| https://blog.example.com/en | Remove the path. Use only the host, like https://blog.example.com. |
|
||||
| blog | Enter a full URL, like https://blog.example.com. |
|
||||
|
||||
Scenario: Sites form: base URL refused by the server
|
||||
Given the form passed the client checks
|
||||
When POST or PATCH answers 400 invalid_site_url
|
||||
Then Base URL shows "Enter a full URL, like https://blog.example.com."
|
||||
|
||||
Scenario Outline: Sites form: loopback hosts accept http
|
||||
Given the Add site slide-over is open
|
||||
When the user enters base URL "<value>"
|
||||
Then no base URL error is shown
|
||||
|
||||
Examples:
|
||||
| value |
|
||||
| http://localhost:5173 |
|
||||
| http://127.0.0.1:8081 |
|
||||
| http://[::1]:5173 |
|
||||
|
||||
Scenario: Sites form: add succeeds
|
||||
Given the Add site slide-over is filled with name "Journal", key "journal", base URL
|
||||
"https://journal.example", robots "Noindex", empty locale and the default switch off
|
||||
When the user activates "Add site"
|
||||
Then exactly one POST /v1/site/ is sent with name, key, base_url, default_robots "noindex",
|
||||
no locale, no default_social_image_id and is_default false
|
||||
And the button reads "Saving…" while the request runs and the fields are disabled
|
||||
And on 201 the slide-over closes and the new site is listed
|
||||
|
||||
Scenario: Sites form: duplicate key
|
||||
Given the Add site slide-over has key "journal" and a site with that key is in the loaded list
|
||||
When the user leaves Key, or submits and POST /v1/site/ answers 409 site_key_taken
|
||||
Then Key shows "A site with the key \"journal\" already exists. Choose another key." and a
|
||||
suggestion "Use journal-2"
|
||||
And activating the suggestion sets Key to "journal-2"
|
||||
|
||||
Scenario Outline: Sites form: save failed
|
||||
Given the Add site slide-over is filled
|
||||
When the save fails with <failure>
|
||||
Then a notice in the panel reads "Couldn't save the site. Your changes are still here. Try again in a moment."
|
||||
And all the values are kept and the form is enabled again
|
||||
|
||||
Examples:
|
||||
| failure |
|
||||
| status 500 |
|
||||
| a network error |
|
||||
|
||||
Scenario: Sites form: invalid locale from the server
|
||||
Given the form has locale "english"
|
||||
When the save answers 400 invalid_locale
|
||||
Then Locale shows "Use a language tag like en or fr-CH." and the panel stays open
|
||||
|
||||
Scenario: Sites form: edit the default site
|
||||
When the owner chooses "Edit" on "Renew"
|
||||
Then a slide-over titled "Edit Renew" opens with the fields filled
|
||||
And Key shows "renew" read-only with a lock and "Used in API paths, so it can't change."
|
||||
And "Default site" is on and locked with "New articles start on the default site. To change it,
|
||||
make another site the default."
|
||||
And the submit reads "Save changes"
|
||||
|
||||
Scenario: Sites form: edit another site, noindex
|
||||
When the owner chooses "Edit" on "Projects" whose robots is "noindex"
|
||||
Then the slide-over is titled "Edit Projects", Key is read-only and locked, "Noindex" is
|
||||
selected with "Asks search engines not to list this site's pages." and the switch
|
||||
"Make this the default site" is available
|
||||
When the user changes the name and activates "Save changes"
|
||||
Then exactly one PATCH /v1/site/3 is sent without the key field
|
||||
|
||||
Scenario: Sites form: make another site the default from the form
|
||||
Given the "Projects" edit form has the default switch turned on
|
||||
When the user activates "Save changes"
|
||||
Then the SPA sends PATCH /v1/site/3 for the changed fields, then PATCH /v1/site/3/default
|
||||
And is_default is never sent in the first PATCH
|
||||
|
||||
Scenario: Sites form: discard changes
|
||||
Given a slide-over is open with a changed field
|
||||
When the user closes it with "Cancel", Escape or the backdrop
|
||||
Then the existing "Discard changes?" dialog is asked
|
||||
And an unchanged form closes without it
|
||||
|
||||
Scenario: Sites form: deep link
|
||||
Given the session role is "owner"
|
||||
When the user opens /settings/sites?edit=projects
|
||||
Then the "Edit Projects" slide-over opens
|
||||
When the user opens /settings/sites?edit=nope
|
||||
Then an info toast shows "That site no longer exists" and the slide-over stays closed
|
||||
|
||||
Rule: Sites delete
|
||||
|
||||
Scenario: Sites delete: site with articles
|
||||
Given the sites list is shown
|
||||
When the owner chooses "Delete…" on "Journal"
|
||||
Then a dialog titled "Delete this site?" reads "\"Journal\" will be deleted. 38 articles belong
|
||||
to it, so choose a site to move them to. This can't be undone."
|
||||
And "Move articles to" defaults to the default site "Renew" shown with "renew.example"
|
||||
And the text "38 articles will move to Renew. Their canonical host changes to renew.example."
|
||||
is shown, with "Cancel" and "Move 38 articles and delete"
|
||||
|
||||
Scenario: Sites delete: choose destination
|
||||
Given the "Delete this site?" dialog is open for "Journal"
|
||||
When the user opens the select
|
||||
Then "Journal" is not offered and each option shows the name and the host
|
||||
|
||||
Scenario: Sites delete: with articles succeeds
|
||||
Given the dialog is open for "Journal" (id 2) with destination "Renew" (id 1)
|
||||
When the user activates "Move 38 articles and delete"
|
||||
Then exactly one DELETE /v1/site/2?reassign_to=1 is sent
|
||||
And the button reads "Moving articles…" while it runs
|
||||
And on 204 the dialog closes, the row leaves the list and a toast shows "Site deleted" and
|
||||
"38 articles moved to Renew."
|
||||
|
||||
Scenario: Sites delete: no articles
|
||||
When the owner chooses "Delete…" on "Archive"
|
||||
Then a dialog titled "Delete this site?" reads "\"Archive\" will be deleted. No articles belong
|
||||
to it. This can't be undone." with "Cancel" and "Delete site" and no select
|
||||
When the user activates "Delete site"
|
||||
Then DELETE /v1/site/4 is sent with no reassign_to and, on 204, the row leaves the list
|
||||
|
||||
Scenario Outline: Sites delete: failures
|
||||
Given the delete dialog is open for "Journal"
|
||||
When DELETE answers <status>
|
||||
Then <outcome>
|
||||
|
||||
Examples:
|
||||
| status | outcome |
|
||||
| 500 or network | the dialog stays open with the notice titled "Couldn't delete the site" and text "Nothing was changed. Try again in a moment." |
|
||||
| 409 site_has_articles | the dialog stays open and shows "Choose where the articles go. This site has 38 articles." |
|
||||
| 403 default_site | the dialog closes and an error toast shows "The default site can't be deleted. Make another site the default first." |
|
||||
| 404 | the dialog closes, the row leaves the list and the info toast "That site no longer exists" shows |
|
||||
|
||||
Rule: Authors list
|
||||
|
||||
Scenario Outline: Authors: default
|
||||
Given the session role is "<role>"
|
||||
And GET /v1/author/ answers 200 with the authors fixture
|
||||
When the user navigates to /authors
|
||||
Then the sidebar entry "Authors" sits between "Media" and "Users" and carries aria-current "page"
|
||||
And the page shows "Authors", "The names readers see on your articles. An author doesn't need
|
||||
an account.", a primary "Add author" button and the search field "Search by name or slug"
|
||||
And the columns are "Author", "Slug", "Account" and "Articles"
|
||||
And each row shows the avatar and name, the slug, a "Linked" or "Guest" badge, and
|
||||
"9 articles", "1 article" or "No articles"
|
||||
And a long name is truncated and shown in full on hover
|
||||
And the first request is GET /v1/author/?page=1&size=25
|
||||
|
||||
Examples:
|
||||
| role |
|
||||
| owner |
|
||||
| admin |
|
||||
|
||||
Scenario: Authors: loading
|
||||
Given GET /v1/author/ is pending
|
||||
When the user navigates to /authors
|
||||
Then skeleton rows are drawn and the list has aria-busy "true"
|
||||
|
||||
Scenario Outline: Authors: error on load
|
||||
Given GET /v1/author/ fails with <failure>
|
||||
When the user navigates to /authors
|
||||
Then an alert shows "Couldn't load authors", "Check your connection and try again." and "Try again"
|
||||
When the user activates "Try again"
|
||||
Then the list is requested again
|
||||
|
||||
Examples:
|
||||
| failure |
|
||||
| status 500 |
|
||||
| a network error |
|
||||
|
||||
Scenario Outline: Authors: empty, first run
|
||||
Given GET /v1/author/ answers 200 with total 0 and no search
|
||||
And the session role is "<role>"
|
||||
When the user navigates to /authors
|
||||
Then the toolbar is hidden and the empty state shows "No authors yet" and "Authors are the names
|
||||
readers see on articles. They don't need an account."
|
||||
And <button>
|
||||
|
||||
Examples:
|
||||
| role | button |
|
||||
| owner | an "Add author" button is shown |
|
||||
| admin | an "Add author" button is shown |
|
||||
| member | no "Add author" button is shown |
|
||||
|
||||
Scenario: Authors: no results
|
||||
Given the user has searched "zoe" and GET /v1/author/?q=zoe answers 200 with total 0
|
||||
Then the state shows "No authors match \"zoe\"", "Check the spelling, or search for a shorter
|
||||
part of the name." and "Clear search"
|
||||
When the user activates "Clear search"
|
||||
Then q leaves the URL and the full list is requested
|
||||
|
||||
Scenario: Authors: search and pagination in the URL
|
||||
When the user types "cam" in the search field
|
||||
Then after the debounce GET /v1/author/?q=cam&page=1&size=25 is sent and the URL holds q=cam
|
||||
When the user opens /authors?q=camille&page=2&size=50
|
||||
Then GET /v1/author/?q=camille&page=2&size=50 is sent
|
||||
And the Articles paginator is shown only when total exceeds 25, with page sizes 5, 25, 50, 100
|
||||
|
||||
Scenario Outline: Authors: invalid page or size in the URL
|
||||
When the user opens /authors?<query>
|
||||
Then the invalid value is replaced by its default with no notice and the API 400 never reaches the user
|
||||
|
||||
Examples:
|
||||
| query |
|
||||
| size=30 |
|
||||
| page=abc |
|
||||
| page=0 |
|
||||
|
||||
Scenario: Authors: row menu (owner or admin)
|
||||
When the user activates the ellipsis of "Camille Roche" (a guest)
|
||||
Then a menu offers "Edit", "Link user" and "Delete…"
|
||||
And for "Inès Duarte" (linked) the menu offers "Edit" and "Delete…"
|
||||
And below md the menu is a bottom sheet
|
||||
|
||||
Scenario: Authors: read-only list (other roles)
|
||||
Given the session role is "member"
|
||||
When the user navigates to /authors
|
||||
Then the description reads "The names readers see on your articles. Only an owner or admin can
|
||||
change authors."
|
||||
And there is no "Add author" button, no pinned bottom button, no row menu and no slide-over form
|
||||
And search still works and each row shows a chevron
|
||||
And the "Authors" sidebar entry is visible
|
||||
|
||||
Scenario: Authors: read-only detail
|
||||
Given the session role is "member"
|
||||
When the user opens the row "Inès Duarte"
|
||||
Then a panel of the same width as the form shows "Inès Duarte", "Linked", "9 articles", "Bio",
|
||||
"Website" and "Only an owner or admin can change this author."
|
||||
And no field is editable, the account email is not shown and "Close" is the only action
|
||||
When the user opens /authors?edit=ines-duarte
|
||||
Then the same read-only detail opens
|
||||
|
||||
Rule: Authors form
|
||||
|
||||
Scenario: Authors form: add, empty
|
||||
Given the session role is "owner" or "admin"
|
||||
When the user activates "Add author"
|
||||
Then a slide-over titled "Add author" opens, a 92 % bottom sheet below md
|
||||
And it shows "Avatar (optional)" with "Choose image", Name (placeholder "e.g. Camille Roche"),
|
||||
Slug (placeholder "Generated from the name"), "Bio (optional)" (placeholder "A sentence or two
|
||||
about the author.") with the counter "0 / 280", "Website (optional)" (placeholder
|
||||
"https://example.com"), "Social links (optional)" with "Add link" and "0 of 5", "Linked user
|
||||
(optional)" showing "No linked user" with "Link a CMS user if this author has an account.
|
||||
Guest writers need no link.", and a "Byline preview" ("Author name", "The bio appears here.")
|
||||
And the buttons are "Cancel" and "Add author"
|
||||
|
||||
Scenario: Authors form: slug from the name
|
||||
When the user types "Camille Roche" in Name
|
||||
Then Slug shows "camille-roche" with an "Auto" badge, an "Edit slug" pencil and the help
|
||||
"Generated from the name. Used in public author URLs and API paths. Unique across all authors."
|
||||
And the byline preview shows the typed name
|
||||
|
||||
Scenario: Authors form: add succeeds
|
||||
Given the form has name "Camille Roche", the automatic slug, a bio, a website and one link
|
||||
When the user activates "Add author"
|
||||
Then exactly one POST /v1/author/ is sent with name, slug "camille-roche", bio, avatar_id,
|
||||
website, social_links [{type,url}] and user_id
|
||||
And the button reads "Saving…" while it runs
|
||||
And on 201 the slide-over closes and the author is listed
|
||||
|
||||
Scenario: Authors form: slug collision
|
||||
Given the form has slug "camille-roche" and POST answers 409 author_slug_taken
|
||||
Then Slug shows "The slug \"camille-roche\" is already used by another author.", a suggestion
|
||||
"Use camille-roche-2" and "Reset to match the name"
|
||||
And activating a suggestion rewrites the slug and keeps the other values
|
||||
|
||||
Scenario Outline: Authors form: validation
|
||||
Given the Add author slide-over is open
|
||||
When the user submits with <input>
|
||||
Then no request is sent and <message> is shown under <field>
|
||||
|
||||
Examples:
|
||||
| input | field | message |
|
||||
| an empty name | Name | Enter a name. |
|
||||
| a bio of 291 characters | Bio | Shorten the bio to 280 characters. with the counter "291 / 280" in error color |
|
||||
| website "example.com" | Website | Enter a full URL starting with https://. |
|
||||
| a social link with url "http://x" | its row | Enter a full URL starting with https://. |
|
||||
|
||||
Scenario Outline: Authors form: server validation codes
|
||||
When the save answers <status> <code>
|
||||
Then <message> is shown under <field>
|
||||
|
||||
Examples:
|
||||
| status | code | field | message |
|
||||
| 422 | bio_too_long | Bio | Shorten the bio to 280 characters. |
|
||||
| 422 | invalid_url | the field | Enter a full URL starting with https://. |
|
||||
| 409 | user_already_linked | Linked user | That user already has an author. Choose another user. |
|
||||
|
||||
Scenario: Authors form: social links
|
||||
When the user activates "Add link"
|
||||
Then a row with a type select (X, LinkedIn, GitHub, Mastodon, Custom) and a URL field is added
|
||||
And the placeholders per type are "https://x.com/username", "https://www.linkedin.com/in/username",
|
||||
"https://github.com/username", "https://mastodon.social/@username" and "https://example.com"
|
||||
And an invalid link shows "Enter a full URL starting with https://."
|
||||
And after the fifth row "Add link" is disabled and "You can add up to 5 links." is shown
|
||||
And the links are sent as social_links with the lowercase types x, linkedin, github, mastodon, custom
|
||||
|
||||
Scenario: Authors form: linked user, choose
|
||||
Given the options are the users of GET /v1/user/ minus every user_id found by paging
|
||||
GET /v1/author/?size=100
|
||||
When the user opens the Linked user select
|
||||
Then under the title "Choose a user" the group "Users without an author" lists "Marta Alves"
|
||||
with "marta@renew.example" and "Rui Santos" with "rui@renew.example"
|
||||
And when no user is left it reads "Every user already has an author."
|
||||
|
||||
Scenario: Authors form: edit a linked author
|
||||
When the user chooses "Edit" on "Inès Duarte"
|
||||
Then the slide-over is titled "Edit Inès Duarte" with the fields filled
|
||||
And Linked user shows "ines.duarte@renew.example" with "Unlink" and "New articles by this user
|
||||
start with this author."
|
||||
And the submit reads "Save changes"
|
||||
And saving sends one PATCH /v1/author/{id} with only the changed fields
|
||||
|
||||
Scenario: Authors form: unlink
|
||||
Given the edit form of "Inès Duarte" is open (owner or admin)
|
||||
When the user activates "Unlink"
|
||||
Then a dialog titled "Unlink Inès Duarte?" reads "Inès Duarte will stay on their articles. New
|
||||
articles by ines.duarte@renew.example will no longer start with this author." with "Cancel"
|
||||
and "Unlink user"
|
||||
When the user activates "Unlink user"
|
||||
Then exactly one PATCH /v1/author/{id} is sent with {"user_id": null}
|
||||
And on 200 the field returns to "No linked user" and a toast shows "User unlinked" and
|
||||
"Inès Duarte is now a guest author."
|
||||
|
||||
Scenario: Authors form: link a guest
|
||||
When the user chooses "Link user" on "Camille Roche", in the row menu or the form
|
||||
Then a dialog titled "Link Camille Roche to a user?" reads "Only users without an author are
|
||||
listed." with the same user list, "Cancel" and "Link user"
|
||||
When the user picks a user and activates "Link user"
|
||||
Then exactly one PATCH /v1/author/{id} is sent with that user_id and the row shows "Linked"
|
||||
|
||||
Scenario: Authors form: avatar picker
|
||||
When the user activates "Choose image"
|
||||
Then the existing media picker opens titled "Choose an image" with "The avatar for Camille Roche."
|
||||
and "Shown as a square. Choose an image with the face or logo near the middle." and "Use image"
|
||||
When the user picks an image and activates "Use image"
|
||||
Then the avatar shows as a square and avatar_id is sent on save
|
||||
And the Sites default social image uses this same picker and sends default_social_image_id
|
||||
|
||||
Scenario Outline: Authors form: save failed
|
||||
When the save fails with <failure>
|
||||
Then a notice in the panel reads "Couldn't save the author. Your changes are still here. Try again in a moment."
|
||||
And the values are kept
|
||||
|
||||
Examples:
|
||||
| failure |
|
||||
| status 500 |
|
||||
| a network error |
|
||||
|
||||
Scenario: Authors form: role changed while open
|
||||
When the save answers 403 author_rights
|
||||
Then an error toast shows "Only an owner or admin can change authors" and "You can still edit
|
||||
your own author profile."
|
||||
|
||||
Scenario: Authors form: deep link
|
||||
When an owner or admin opens /authors?edit=camille-roche
|
||||
Then the "Edit Camille Roche" slide-over opens
|
||||
When the slug is unknown
|
||||
Then an info toast shows "That author no longer exists" and nothing opens
|
||||
|
||||
Scenario: Authors form: own author, any role, by deep link only
|
||||
Given the session role is "member" and GET /v1/auth/me carries an author with slug "ines-duarte"
|
||||
When the user opens /authors?edit=ines-duarte
|
||||
Then the form opens with the linked user locked, no "Unlink", no "Link user" and no delete action
|
||||
And saving sends PATCH /v1/author/{id} with only the changed fields
|
||||
When the same member opens /authors?edit=camille-roche
|
||||
Then the read-only detail opens
|
||||
|
||||
Rule: Authors delete
|
||||
|
||||
Scenario: Authors delete: reassign (recommended)
|
||||
When an owner or admin chooses "Delete…" on "Camille Roche" (id 7, 3 articles)
|
||||
Then a dialog titled "Delete this author?" reads "\"Camille Roche\" will be deleted and is
|
||||
credited on 3 articles. This can't be undone."
|
||||
And "Credit these articles to" is preselected on the first other author, with "Where an article
|
||||
has several authors, Camille Roche is removed and the others stay."
|
||||
And the options come from GET /v1/author/?size=100 without the deleted author
|
||||
And the buttons are "Cancel" and "Delete and reassign 3 articles"
|
||||
And for a linked author the line "Linked to ines.duarte@renew.example. The user account isn't
|
||||
affected." is added
|
||||
|
||||
Scenario: Authors delete: reassign succeeds
|
||||
Given the dialog is open with destination "Inès Duarte" (id 2)
|
||||
When the user activates "Delete and reassign 3 articles"
|
||||
Then exactly one DELETE /v1/author/7?reassign_to=2 is sent
|
||||
And the button reads "Reassigning…" while it runs
|
||||
And on 204 the row leaves the list and a toast shows "Author deleted" and "3 articles now credit
|
||||
Inès Duarte."
|
||||
|
||||
Scenario: Authors delete: choose who
|
||||
When the user opens the select
|
||||
Then the deleted author is not listed and the last option is "Nobody" with "Remove the byline"
|
||||
|
||||
Scenario: Authors delete: nobody
|
||||
When the user chooses "Nobody"
|
||||
Then the text "The articles keep any other authors. Articles with only this author will have no
|
||||
byline." is shown
|
||||
When the user confirms
|
||||
Then DELETE /v1/author/7?reassign_to=none is sent
|
||||
|
||||
Scenario Outline: Authors delete: failed (notice shared by site and author delete)
|
||||
Given an author delete dialog is open
|
||||
When DELETE fails with <failure>
|
||||
Then the dialog stays open with "Couldn't delete the author" and "Nothing was changed. Try again in a moment."
|
||||
And the buttons are enabled again
|
||||
|
||||
Examples:
|
||||
| failure |
|
||||
| status 500 |
|
||||
| a network error |
|
||||
|
||||
Scenario: Authors delete: server fallback (409)
|
||||
When DELETE answers 409 author_has_articles
|
||||
Then a dialog titled "Can't delete this author" reads "\"Camille Roche\" is credited on 3
|
||||
articles. Choose another author to credit instead, or remove Camille Roche from those
|
||||
articles first."
|
||||
And its buttons are "Close" and "Reassign articles"
|
||||
And "Reassign articles" reopens the reassign dialog
|
||||
|
||||
Scenario: Authors delete: no articles
|
||||
When the user chooses "Delete…" on "Léa Fontaine"
|
||||
Then a dialog titled "Delete this author?" reads "\"Léa Fontaine\" will be deleted. No articles
|
||||
credit this author. This can't be undone." with "Cancel" and "Delete author" and no select
|
||||
When the user confirms
|
||||
Then DELETE /v1/author/{id} is sent with no reassign_to and the row leaves the list
|
||||
|
||||
Scenario: Authors delete: author already gone
|
||||
When DELETE answers 404 author_not_found
|
||||
Then the dialog closes, the row leaves the list and the info toast "That author no longer
|
||||
exists" shows
|
||||
|
||||
Rule: Cross-cutting
|
||||
|
||||
Scenario Outline: Session problems use the app-wide handling
|
||||
Given a load of <path> answers <status>
|
||||
Then <outcome>
|
||||
|
||||
Examples:
|
||||
| path | status | outcome |
|
||||
| /authors | 401 | the user lands on /login?redirect=/authors&reason=expired |
|
||||
| /settings/sites | 401 | the user lands on /login?redirect=/settings/sites&reason=expired |
|
||||
| /authors | 403 (unverified) | the user lands on /register/pending |
|
||||
|
||||
Scenario: Slide-over accessibility
|
||||
When a slide-over or dialog is open
|
||||
Then focus moves into it, is trapped, and returns to the opening control on close
|
||||
And Escape closes it unless a request is running
|
||||
|
||||
Scenario: Language: every string has a French entry
|
||||
Given the language is "fr"
|
||||
When the user opens each state of both screens
|
||||
Then every visible string is the French message and none falls back to English
|
||||
|
||||
Scenario: Editor, Articles and Profile
|
||||
Then their changes are specified in features/sites_authors_integration.feature
|
||||
@@ -0,0 +1,117 @@
|
||||
# QA: Sites and Authors screens
|
||||
|
||||
SPA slice only. The Go API already exists (commits "Sites feature backend" and "Authors feature backend"), so no new Go test is requested. If a contract below turns out wrong, report it as a backend defect.
|
||||
|
||||
## Automated SPA (Vitest + Vue Test Utils, `task test:web`)
|
||||
|
||||
Mock `useApi`'s `request` per case for GET/POST/PATCH/DELETE on /v1/site/ and /v1/author/, PATCH /v1/site/{id}/default and GET /v1/user/. Mount SitesView and AuthorsView inside DashboardShell with a resolved session and a test router. Roles: "owner" (Marta Alves), "admin", and "member". Mock matchMedia for desktop and below-md. Do not freeze the system date. Use fake timers only for the 150 ms skeleton delay and the search debounce. Un-run web tests are NOT RUN, never passing.
|
||||
|
||||
Shared pieces get their own specs, reused by both screens (`DirectoryList`, `DirectoryPanel`, `ReassignDialog`, `SlugField`, `MediaField`):
|
||||
1. **DirectoryList** - rows, truncation, read-only chevron variant, below-md cards, loading (skeleton after 150 ms, aria-busy), error alert with "Try again".
|
||||
2. **DirectoryPanel** - desktop slide-over and 92 % bottom sheet below md, focus trap and return, "Discard changes?" on a dirty close, Escape ignored while sending.
|
||||
3. **SlugField** - auto from the name, "Auto" badge, pencil, "Reset to match the name", suggestion, locked variant with lock and "Used in API paths, so it can't change."
|
||||
4. **MediaField** - opens the existing picker, square avatar variant, "Use image" returns the id.
|
||||
5. **ReassignDialog** - select excludes the deleted item, default selection, count in the button, in-flight label, failed notice, 409 notice.
|
||||
|
||||
Sites (SitesView), one test per scenario in the feature:
|
||||
6. Default list: columns, badges "Default" and "Noindex", counts including "No articles", mobile cards and pinned "Add site".
|
||||
7. Only the default site hint; no empty-state wall.
|
||||
8. Loading: nothing before 150 ms, skeleton after.
|
||||
9. Error Examples-driven (500, network) and "Try again".
|
||||
10. Row menu and the bottom-sheet title; Default site: "Delete…" aria-disabled, focusable, tooltip text, no request on activate.
|
||||
11. Set as default: dialog copy, one PATCH /v1/site/2/default, "Saving…", badge moves, toast; failures 500/404/403.
|
||||
12. Hidden entry (admin) and the owner's entry: sidebar Publishing group, Sites entry, Settings "Publishing" card and "Manage sites" row. Extend the existing `SettingsView.spec.ts` and the shell navigation spec for role-based visibility.
|
||||
13. 403 page for admin and member on /settings/sites and on ?edit=journal; "Back to Settings"; no redirect; the API-403 page load versus action toast.
|
||||
14. Form: Add empty (every label, placeholder, help); key from the name and pencil; URL validation Examples (3 messages, no request); server invalid_site_url; loopback http accepted; duplicate key (blur against the loaded list and 409) with the suggestion; save failed Examples; invalid_locale; Edit default site (lock, switch on and locked); Edit other site, noindex; PATCH has no key; default switch sends the two calls in order; discard; deep link and unknown key toast.
|
||||
15. Delete: with articles (copy, default destination, one DELETE with reassign_to=1, "Moving articles…", toast); destination options (no deleted site, name and host); no articles (no select, no reassign_to); failures: 500/network with title "Couldn't delete the site" and "Nothing was changed. Try again in a moment.", 409, 403 default_site, 404.
|
||||
|
||||
Authors (AuthorsView):
|
||||
16. Default list for owner and admin: columns, badges, "9 articles"/"1 article"/"No articles", first request `?page=1&size=25`; sidebar entry order and aria-current.
|
||||
17. Loading, error Examples, empty (owner, admin with button; member without), no results and "Clear search".
|
||||
18. Search and pagination: debounce, URL q/page/size, paginator above 25, invalid page/size replaced silently.
|
||||
19. Row menu: guest has Edit, Link user, Delete…; linked has Edit, Delete…; mobile sheet.
|
||||
20. Read-only list and detail for member (no button, no menu, no bottom button, search works, no email); `?edit=` opens the read-only detail.
|
||||
21. Form: Add empty copy; slug from the name; add succeeds with the exact POST body; slug collision and suggestions; validation Examples; server codes Examples (bio_too_long, invalid_url, user_already_linked); social links (types, placeholders, limit of 5, bad link); linked user options computed from GET /v1/user/ minus user_ids paged from GET /v1/author/?size=100, and "Every user already has an author."; edit linked; unlink (PATCH user_id null, toast); re-link; avatar picker; save failed Examples; 403 author_rights toast; deep link and unknown slug toast.
|
||||
22. Own author by deep link only: member opens `/authors?edit=<own slug>` (own author from GET /v1/auth/me), form with locked link and no delete, PATCH on save; another slug opens the read-only detail. POST /v1/author/me is covered by features/sites_authors_integration.qa.md.
|
||||
23. Delete: reassign (copy, linked line, first other author preselected, one DELETE ?reassign_to=2, "Reassigning…", toast); choose who (no deleted author, "Nobody" last); nobody sends `reassign_to=none`; failed Examples; 409 fallback dialog and "Reassign articles"; no articles; 404.
|
||||
24. 401 and 403 app-wide redirects on both routes.
|
||||
25. French: `setLocale('fr')`, walk the list, form, delete and 403 page of each screen, no English source string remains.
|
||||
26. Messages: every new `t()` key has a French entry (extend the i18n spec). Router: /settings/sites and /authors are registered and verified.
|
||||
27. Editor, Articles and Profile changes and their regression specs are covered by features/sites_authors_integration.qa.md.
|
||||
|
||||
## Visual (`task visual:check -- <screen>`, desktop and mobile, light and dark)
|
||||
|
||||
Reference: docs/design/screens/sites.md and authors.md, board frames in `docs/design/source/DirectoryFrame.dc.html` (list, panel, dialogs) and `AppFrame.dc.html` (sidebar, Settings card). Add each state to `web/visual/states.ts` as the groups `sites`, `sites-form`, `sites-delete`, `authors`, `authors-form`, `authors-delete`, with mocked /v1 calls and the board's own sample data. Hard gate: every capture within 10 %. No state is clock-sensitive, so none gets `skip`. Confirm in the frame script before skipping anything. Sample data: the sites fixture (268, 38, 6 and 0 articles), the authors fixture, Camille Roche (3 articles), Inès Duarte (ines.duarte@renew.example, 9 articles), Léa Fontaine, Marta Alves (marta@renew.example), Rui Santos (rui@renew.example), the 291-character bio for validation, "zoe" for no results. Read the host and row order from the frame.
|
||||
|
||||
Sites (9):
|
||||
- [ ] Default
|
||||
- [ ] Only the default site
|
||||
- [ ] Loading (setup holds the request)
|
||||
- [ ] Error
|
||||
- [ ] Row menu
|
||||
- [ ] Default site: delete unavailable
|
||||
- [ ] Set as default: confirm
|
||||
- [ ] Hidden entry (admin) (path /settings, admin session)
|
||||
- [ ] Forbidden (403)
|
||||
|
||||
Sites: form (7):
|
||||
- [ ] Add: empty
|
||||
- [ ] Add: key from the name
|
||||
- [ ] Add: URL not valid
|
||||
- [ ] Add: duplicate key
|
||||
- [ ] Add: save failed
|
||||
- [ ] Edit: default site
|
||||
- [ ] Edit: other site, noindex
|
||||
|
||||
Sites: delete (3):
|
||||
- [ ] With articles
|
||||
- [ ] Choose destination
|
||||
- [ ] No articles
|
||||
|
||||
Authors (8):
|
||||
- [ ] Default
|
||||
- [ ] Loading
|
||||
- [ ] Error
|
||||
- [ ] Empty, first run
|
||||
- [ ] No results
|
||||
- [ ] Row menu
|
||||
- [ ] Read-only list (other roles)
|
||||
- [ ] Read-only detail
|
||||
|
||||
Authors: form (11):
|
||||
- [ ] Add: empty
|
||||
- [ ] Slug from the name
|
||||
- [ ] Slug collision
|
||||
- [ ] Validation
|
||||
- [ ] Social links
|
||||
- [ ] Linked user: choose
|
||||
- [ ] Edit: linked author
|
||||
- [ ] Avatar: picker
|
||||
- [ ] Save failed
|
||||
- [ ] Unlink: confirm
|
||||
- [ ] Re-link
|
||||
|
||||
Authors: delete (6):
|
||||
- [ ] Reassign (recommended)
|
||||
- [ ] Choose who
|
||||
- [ ] Nobody
|
||||
- [ ] Failed
|
||||
- [ ] Server fallback (409)
|
||||
- [ ] No articles
|
||||
|
||||
Layout from the frame, not components.md: row height as in Users; slide-over width and the 92 % bottom sheet at 390 px; bottom sheet row menu titled with the site name; pinned mobile "Add site"/"Add author" button.
|
||||
|
||||
Not drawn on the board, Vitest only: in-flight labels ("Saving…", "Moving articles…", "Reassigning…"), the 403 and 404 toasts, the 401 redirect, the pagination states of the Authors list, Set-as-default failures, `invalid_locale`, the loopback rule and the discard dialog.
|
||||
|
||||
Risk: the sidebar gains "Authors" for every role and "Publishing > Sites" for the owner, and Settings gains a Publishing card for the owner. This can push existing captures of other screens over 10 %. Re-run `task visual:check` for the Settings, Users, Media and API keys screens after the setups pass. A failure needs the user's decision (an `approvedBy` exception or a design update).
|
||||
|
||||
Manual checks screenshots cannot cover:
|
||||
- Keyboard: Tab order through "Add", search, rows and the ellipsis buttons; Enter opens the menu; focus is trapped in the panel and dialogs and returns to the opener; the disabled "Delete…" stays focusable; the select options are reachable by keyboard.
|
||||
- Hover and motion: truncated name tooltip, row hover, slide-over and sheet motion, skeleton pulse stopped under reduced motion.
|
||||
|
||||
## Manual verification (real `task dev`)
|
||||
- Owner: add a site with the loopback URL http://localhost:5173, set it default, delete a site with articles and check the articles moved. Admin: no Sites entry, a direct link shows the 403 page.
|
||||
- Authors: owner creates, links and unlinks an author; member sees the read-only list and detail; member with an author opens `/authors?edit=<own slug>` and cannot delete.
|
||||
|
||||
## French strings for web/src/i18n/messages.ts
|
||||
Keyed by the English text, with the English as in the design. `coder` completes them for every string listed in the two screen files. Proposed French for the main ones: Sites = Sites; Add site = Ajouter un site; Add author = Ajouter un auteur; Authors = Auteurs; Default = Par défaut; Noindex = Noindex; Set as default = Définir par défaut; Delete… = Supprimer… ; Edit = Modifier; Link user = Lier un utilisateur; Cancel = Annuler; Save changes = Enregistrer les modifications; Saving… = Enregistrement…; Moving articles… = Déplacement des articles…; Reassigning… = Réattribution…; Guest = Invité; Linked = Lié; Try again = Réessayer; Couldn't load sites = Impossible de charger les sites; Couldn't load authors = Impossible de charger les auteurs; Couldn't delete the site = Impossible de supprimer le site; You don't have access to Sites = Vous n'avez pas accès aux sites; Back to Settings = Retour aux réglages; Nobody = Personne; Unlink user = Dissocier l'utilisateur.
|
||||
@@ -0,0 +1,784 @@
|
||||
Feature: Sites backend, the owner manages sites and every article belongs to exactly one
|
||||
|
||||
As the owner of a RenewCMS installation
|
||||
I want to create, edit, delete and choose a default among several sites, and assign each article to one
|
||||
So that a single back-office can hold the content of more than one website
|
||||
|
||||
Background:
|
||||
Given the spec of record is docs/design/screens/sites.md, docs/design/states.md (site rows), docs/design/routes.md and docs/design/sites-authors-slices.md
|
||||
And this slice is backend only: no SPA, no change to docs/design
|
||||
And a Site has id (uint32), name, key, base_url, default_social_image_id (nullable), default_robots ("index" or "noindex"), locale (nullable), is_default and article_count, in snake_case JSON
|
||||
And exactly one site is the default at any time, enforced by the use case inside a transaction and not by a partial index
|
||||
And every article has a site_id referencing an existing site
|
||||
And the routes live under /v1/site, mounted inside the JWT group: GET /, POST /, PATCH /{id}, PATCH /{id}/default, DELETE /{id}?reassign_to={id}
|
||||
And GET /v1/site/ accepts a session or an API key; every write is session-only and goes through RequireOwner, like PATCH /v1/settings
|
||||
And PATCH /v1/article/{id} with site_id stays callable with an API key
|
||||
And error responses are plain text from http.Error whose body is exactly the code token: site_key_taken, site_has_articles, default_site, key_immutable, invalid_site_url, invalid_locale, site_not_found, image_not_found, use_set_default, invalid_reassign
|
||||
And a non-owner write answers 403 with the existing RequireOwner body "Only the owner can do this." (apperr.OwnerRequiredErrorMessage), with no owner_only token
|
||||
And a request body that cannot be decoded answers 400 with apperr.BodyErrorMessage ("The request cannot be processed due to a mismatch in the format of the body."), a malformed id answers 400 with apperr.IdUint32ErrorMessage, and a validate-tag failure answers 400 with the validator error text, like POST /v1/article
|
||||
And a missing article answers 404 "Article not found" (apperr.ArticleNotFoundErrorMessage)
|
||||
And the roles are "owner" and "admin" only, and a "verified" account is one with is_verified true
|
||||
And success responses are JSON with snake_case fields
|
||||
And request validation goes through validate tags and validator.Validate.Struct
|
||||
And the key matches ^[a-z0-9]+(-[a-z0-9]+)*$ with 2 to 32 characters, the name has 1 to 100 characters, the locale matches ^[a-z]{2,3}(-[A-Za-z0-9]{2,8})*$ and an empty or null locale means none
|
||||
And base_url must be https, except http for localhost, 127.0.0.1 and [::1], with no path, query or userinfo; a trailing slash is stripped; uniqueness is not enforced
|
||||
And handlers reach sites only through use cases and domain interfaces, and no comment is added anywhere
|
||||
|
||||
Rule: Reading sites
|
||||
|
||||
Scenario: The list puts the default site first and then orders by name
|
||||
Given the sites "Zeta" (key "zeta"), "Alpha" (key "alpha") and "Main" (key "main", default)
|
||||
When a verified account sends GET /v1/site/
|
||||
Then the status is 200
|
||||
And the body lists "Main", "Alpha", "Zeta" in that order
|
||||
And every site carries article_count
|
||||
|
||||
Scenario Outline: Who can read the list
|
||||
Given at least one site exists
|
||||
When GET /v1/site/ is sent with <credentials>
|
||||
Then the status is <status>
|
||||
|
||||
Examples:
|
||||
| credentials | status |
|
||||
| the owner's jwt cookie | 200 |
|
||||
| a verified admin's jwt cookie | 200 |
|
||||
| a valid API key | 200 |
|
||||
| an unverified account's jwt cookie | 403 |
|
||||
| no credentials | 401 |
|
||||
|
||||
Scenario: A site without image or locale returns nulls
|
||||
Given the site "Blog" has no default social image and no locale
|
||||
When a verified account sends GET /v1/site/
|
||||
Then "Blog" has default_social_image_id null and locale null
|
||||
|
||||
Rule: Creating a site is owner only
|
||||
|
||||
Scenario: The owner creates a site
|
||||
When the owner sends POST /v1/site/ with {"name": "Shop", "key": "shop", "base_url": "https://shop.example.com", "default_robots": "noindex", "locale": "fr-CA"}
|
||||
Then the status is 201
|
||||
And the body is the site with a new id, is_default false, article_count 0 and the given values
|
||||
And the site is stored
|
||||
|
||||
Scenario: Optional fields default
|
||||
When the owner sends POST /v1/site/ with {"name": "Shop", "key": "shop", "base_url": "https://shop.example.com"}
|
||||
Then the site has default_robots "index", locale null, default_social_image_id null and is_default false
|
||||
|
||||
Scenario: A new site can become the default at creation
|
||||
Given the site "Main" is the default
|
||||
When the owner sends POST /v1/site/ with {"name": "Shop", "key": "shop", "base_url": "https://shop.example.com", "is_default": true}
|
||||
Then "Shop" is the default and "Main" is not
|
||||
And exactly one site is the default
|
||||
|
||||
Scenario Outline: The base URL is normalised
|
||||
When the owner creates a site with base_url "<sent>"
|
||||
Then the stored base_url is "<stored>"
|
||||
|
||||
Examples:
|
||||
| sent | stored |
|
||||
| https://shop.example.com/ | https://shop.example.com |
|
||||
| https://Shop.Example.com | https://shop.example.com |
|
||||
| http://localhost:5173/ | http://localhost:5173 |
|
||||
|
||||
Scenario Outline: The base URL must be https except loopback and carry no path
|
||||
When the owner creates a site with base_url "<sent>"
|
||||
Then the status is <status>
|
||||
And the body is "<body>"
|
||||
|
||||
Examples:
|
||||
| sent | status | body |
|
||||
| https://shop.example.com | 201 | |
|
||||
| http://localhost:8080 | 201 | |
|
||||
| http://127.0.0.1:8080 | 201 | |
|
||||
| http://[::1]:8080 | 201 | |
|
||||
| http://shop.example.com | 400 | invalid_site_url |
|
||||
| https://shop.example.com/blog | 400 | invalid_site_url |
|
||||
| https://shop.example.com/?a=1 | 400 | invalid_site_url |
|
||||
| https://user@shop.example.com | 400 | invalid_site_url |
|
||||
| ftp://shop.example.com | 400 | invalid_site_url |
|
||||
| shop.example.com | 400 | invalid_site_url |
|
||||
|
||||
Scenario Outline: The key format
|
||||
When the owner creates a site with key "<key>"
|
||||
Then the status is <status>
|
||||
|
||||
Examples:
|
||||
| key | status |
|
||||
| shop | 201 |
|
||||
| my-shop-2 | 201 |
|
||||
| ab | 201 |
|
||||
| a | 400 |
|
||||
| Shop | 400 |
|
||||
| -shop | 400 |
|
||||
| shop- | 400 |
|
||||
| my--shop | 400 |
|
||||
| my_shop | 400 |
|
||||
| aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa | 400 |
|
||||
| (empty) | 400 |
|
||||
|
||||
Scenario: A taken key is refused
|
||||
Given the site with key "shop" exists
|
||||
When the owner sends POST /v1/site/ with key "shop"
|
||||
Then the status is 409
|
||||
And the body is "site_key_taken"
|
||||
And no site is added
|
||||
|
||||
Scenario Outline: Other fields are validated
|
||||
When the owner sends POST /v1/site/ with <field> <value>
|
||||
Then the status is <status>
|
||||
And the body is "<body>"
|
||||
And no site is added
|
||||
|
||||
Examples:
|
||||
| field | value | status | body |
|
||||
| name | (empty) | 400 | the validator error text |
|
||||
| name | 101 characters | 400 | the validator error text |
|
||||
| default_robots | "follow" | 400 | the validator error text |
|
||||
| locale | "english" | 400 | invalid_locale |
|
||||
| locale | "fr_FR" | 400 | invalid_locale |
|
||||
| default_social_image_id | 999 (no such image) | 400 | image_not_found |
|
||||
|
||||
Scenario: A malformed body is refused
|
||||
When the owner sends POST /v1/site/ with the body "{not json"
|
||||
Then the status is 400
|
||||
And the body is apperr.BodyErrorMessage
|
||||
And no site is added
|
||||
|
||||
Scenario Outline: A valid locale is accepted and an empty one clears it
|
||||
When the owner creates a site with locale <locale>
|
||||
Then the status is 201
|
||||
And the stored locale is <stored>
|
||||
|
||||
Examples:
|
||||
| locale | stored |
|
||||
| "en" | "en" |
|
||||
| "fr-CA" | "fr-CA" |
|
||||
| "zh-Hant-TW" | "zh-Hant-TW" |
|
||||
| "" | null |
|
||||
| null | null |
|
||||
|
||||
Rule: Editing a site is owner only
|
||||
|
||||
Scenario: The owner edits a site
|
||||
Given the site 2 "Shop" with key "shop"
|
||||
When the owner sends PATCH /v1/site/2 with {"name": "Boutique", "base_url": "https://boutique.example.com", "default_robots": "noindex", "locale": "fr"}
|
||||
Then the status is 200
|
||||
And the body is the site with the new values and the key "shop"
|
||||
|
||||
Scenario: Absent fields are untouched
|
||||
Given the site 2 has locale "fr" and default_robots "noindex"
|
||||
When the owner sends PATCH /v1/site/2 with {"name": "Boutique"}
|
||||
Then only the name changed
|
||||
|
||||
Scenario: The default social image is set and cleared
|
||||
Given the image 5 exists
|
||||
When the owner sends PATCH /v1/site/2 with {"default_social_image_id": 5}
|
||||
Then the site 2 has default_social_image_id 5
|
||||
When the owner sends PATCH /v1/site/2 with {"default_social_image_id": null}
|
||||
Then the site 2 has default_social_image_id null
|
||||
|
||||
Scenario Outline: The key never changes
|
||||
Given the site 2 has key "shop"
|
||||
When the owner sends PATCH /v1/site/2 with {"key": "<key>"}
|
||||
Then the status is <status>
|
||||
And the body is "<body>"
|
||||
And the key of site 2 is still "shop"
|
||||
|
||||
Examples:
|
||||
| key | status | body |
|
||||
| shop | 200 | |
|
||||
| store | 400 | key_immutable |
|
||||
|
||||
Scenario: A rejected key change leaves every other field unchanged
|
||||
Given the site 2 "Shop"
|
||||
When the owner sends PATCH /v1/site/2 with {"name": "Boutique", "key": "store"}
|
||||
Then the status is 400 with body "key_immutable"
|
||||
And the name of site 2 is still "Shop"
|
||||
|
||||
Scenario: The default flag is not editable here
|
||||
When the owner sends PATCH /v1/site/2 with {"is_default": true}
|
||||
Then the status is 400
|
||||
And the body is "use_set_default"
|
||||
And the default site did not change
|
||||
|
||||
Scenario Outline: Editing is validated like creation
|
||||
When the owner sends PATCH /v1/site/2 with <field> <value>
|
||||
Then the status is 400
|
||||
And the body is "<body>"
|
||||
And the site 2 is unchanged
|
||||
|
||||
Examples:
|
||||
| field | value | body |
|
||||
| base_url | "http://shop.example.com" | invalid_site_url |
|
||||
| base_url | "https://shop.example.com/x" | invalid_site_url |
|
||||
| locale | "fr_FR" | invalid_locale |
|
||||
| default_social_image_id | 999 | image_not_found |
|
||||
| name | (empty) | the validator error text |
|
||||
| default_robots | "follow" | the validator error text |
|
||||
|
||||
Scenario: A missing site is not found
|
||||
When the owner sends PATCH /v1/site/999 with {"name": "X"}
|
||||
Then the status is 404
|
||||
And the body is "site_not_found"
|
||||
|
||||
Scenario: A no-op edit records nothing
|
||||
When the owner sends PATCH /v1/site/2 with the values it already has
|
||||
Then the status is 200
|
||||
And no activity event is recorded
|
||||
|
||||
Scenario: A malformed id is refused
|
||||
When the owner sends PATCH /v1/site/abc with {"name": "X"}
|
||||
Then the status is 400
|
||||
And the body is the uint32 id format error
|
||||
|
||||
Rule: The default site
|
||||
|
||||
Scenario: The owner makes another site the default
|
||||
Given "Main" is the default and "Shop" is not
|
||||
When the owner sends PATCH /v1/site/2/default
|
||||
Then the status is 200
|
||||
And the body is "Shop" with is_default true
|
||||
And "Main" is no longer the default
|
||||
|
||||
Scenario: Setting the current default is a no-op
|
||||
When the owner sends PATCH /v1/site/1/default on the current default
|
||||
Then the status is 200
|
||||
And no activity event is recorded
|
||||
|
||||
Scenario: A missing site cannot become the default
|
||||
When the owner sends PATCH /v1/site/999/default
|
||||
Then the status is 404
|
||||
And the body is "site_not_found"
|
||||
|
||||
Scenario: The swap is atomic
|
||||
Given the repository fails while flagging the new default
|
||||
When the owner sends PATCH /v1/site/2/default
|
||||
Then the previous default is still the only default
|
||||
|
||||
Scenario: New articles start on the new default
|
||||
Given "Shop" became the default
|
||||
When an article is created without a site
|
||||
Then its site_id is the id of "Shop"
|
||||
|
||||
Rule: Deleting a site is owner only
|
||||
|
||||
Scenario: A site without articles is deleted
|
||||
Given the site 2 has no articles and is not the default
|
||||
When the owner sends DELETE /v1/site/2
|
||||
Then the status is 204
|
||||
And the site 2 no longer exists
|
||||
|
||||
Scenario: A site with articles needs a destination
|
||||
Given the site 2 has 3 articles
|
||||
When the owner sends DELETE /v1/site/2
|
||||
Then the status is 409
|
||||
And the body is "site_has_articles"
|
||||
And the site and its articles are unchanged
|
||||
|
||||
Scenario: The articles move in one transaction
|
||||
Given the site 2 has 3 articles and the site 3 exists
|
||||
When the owner sends DELETE /v1/site/2?reassign_to=3
|
||||
Then the status is 204
|
||||
And the 3 articles now have site_id 3
|
||||
And the site 2 no longer exists
|
||||
|
||||
Scenario: Reassign and delete are all-or-nothing
|
||||
Given the repository fails while deleting the site 2
|
||||
When the owner sends DELETE /v1/site/2?reassign_to=3
|
||||
Then the articles of the site 2 still have site_id 2
|
||||
And the site 2 still exists
|
||||
|
||||
Scenario: The articles are moved by one repository operation
|
||||
When the owner deletes a site with articles and a valid reassign_to
|
||||
Then the use case calls a single repository operation that moves the articles and deletes the site
|
||||
|
||||
Scenario Outline: An unusable destination
|
||||
Given the site 2 has 3 articles and is not the default
|
||||
When the owner sends DELETE /v1/site/2?reassign_to=<reassign_to>
|
||||
Then the status is <status>
|
||||
And the body is "<body>"
|
||||
And nothing changed
|
||||
|
||||
Examples:
|
||||
| reassign_to | status | body |
|
||||
| 999 | 404 | site_not_found |
|
||||
| 2 | 400 | invalid_reassign |
|
||||
| abc | 400 | invalid_reassign |
|
||||
| -1 | 400 | invalid_reassign |
|
||||
|
||||
Scenario: The default site cannot be deleted
|
||||
When the owner sends DELETE /v1/site/1 on the default site
|
||||
Then the status is 403
|
||||
And the body is "default_site"
|
||||
|
||||
Scenario: The default check comes before the articles check
|
||||
Given the default site has 5 articles
|
||||
When the owner sends DELETE /v1/site/1 without reassign_to
|
||||
Then the status is 403 with body "default_site"
|
||||
|
||||
Scenario: A missing site is not found
|
||||
When the owner sends DELETE /v1/site/999
|
||||
Then the status is 404
|
||||
And the body is "site_not_found"
|
||||
|
||||
Scenario: An unused reassign_to is ignored
|
||||
Given the site 2 has no articles
|
||||
When the owner sends DELETE /v1/site/2?reassign_to=3
|
||||
Then the status is 204
|
||||
And the site 3 is unchanged
|
||||
|
||||
Rule: Only the owner writes
|
||||
|
||||
Scenario Outline: Other roles and keys are refused
|
||||
When <request> is sent with <credentials>
|
||||
Then the status is 403
|
||||
And the body is "<body>"
|
||||
And no site changed
|
||||
|
||||
Examples:
|
||||
| request | credentials | body |
|
||||
| POST /v1/site/ | a verified admin's jwt cookie | Only the owner can do this. |
|
||||
| PATCH /v1/site/2 | a verified admin's jwt cookie | Only the owner can do this. |
|
||||
| PATCH /v1/site/2/default | a verified admin's jwt cookie | Only the owner can do this. |
|
||||
| DELETE /v1/site/2 | a verified admin's jwt cookie | Only the owner can do this. |
|
||||
| POST /v1/site/ | a valid API key | This action needs a real session. |
|
||||
| PATCH /v1/site/2 | a valid API key | This action needs a real session. |
|
||||
| PATCH /v1/site/2/default | a valid API key | This action needs a real session. |
|
||||
| DELETE /v1/site/2 | a valid API key | This action needs a real session. |
|
||||
|
||||
Scenario: The role is checked before the body
|
||||
When an admin sends POST /v1/site/ with the body "{not json"
|
||||
Then the status is 403 with body "Only the owner can do this."
|
||||
|
||||
Rule: Seed and migration
|
||||
|
||||
Scenario: A fresh database gets one default site from PUBLIC_URL
|
||||
Given an empty database and PUBLIC_URL "https://www.example.com/blog"
|
||||
When database.Migrate runs with that PUBLIC_URL
|
||||
Then one site exists with name "Default", key "default", base_url "https://www.example.com", default_robots "index", locale null and is_default true
|
||||
|
||||
Scenario Outline: The seed follows the base URL rule
|
||||
Given an empty database
|
||||
When database.Migrate runs with PUBLIC_URL "<public_url>"
|
||||
Then the seeded base_url is "<base_url>"
|
||||
|
||||
Examples:
|
||||
| public_url | base_url |
|
||||
| https://www.example.com/ | https://www.example.com |
|
||||
| https://www.example.com/a/b | https://www.example.com |
|
||||
| http://www.example.com | https://www.example.com |
|
||||
| http://localhost:8080 | http://localhost:8080 |
|
||||
| http://127.0.0.1:8080/x | http://127.0.0.1:8080 |
|
||||
|
||||
Scenario: An unparseable PUBLIC_URL stops the migration
|
||||
Given an empty database
|
||||
When database.Migrate runs with PUBLIC_URL "://not a url"
|
||||
Then it returns an error naming PUBLIC_URL
|
||||
And no site is created
|
||||
|
||||
Scenario: Existing articles are backfilled
|
||||
Given a database from before this slice holding 4 articles
|
||||
When database.Migrate runs
|
||||
Then all 4 articles have the seeded default site as site_id
|
||||
|
||||
Scenario: The seed runs once
|
||||
Given the sites table already holds a site
|
||||
When database.Migrate runs again with another PUBLIC_URL
|
||||
Then no site is added and no site is changed
|
||||
|
||||
Scenario: PUBLIC_URL is not used afterwards
|
||||
Given the owner edited the default site base_url
|
||||
When the process restarts with the same PUBLIC_URL
|
||||
Then the default site keeps the owner's base_url
|
||||
|
||||
Scenario: It works on every database driver
|
||||
When the repository contract suite runs
|
||||
Then the site repository behaves the same on SQLite, MySQL and PostgreSQL
|
||||
And the SQLite schema test accounts for the new table and column
|
||||
|
||||
Rule: Articles belong to a site
|
||||
|
||||
Scenario: A new article starts on the default site
|
||||
Given "Main" is the default site with id 1
|
||||
When the owner sends POST /v1/article with {"title": "Spring release", "body": "Hello"}
|
||||
Then the stored article has site_id 1
|
||||
And the article is offline
|
||||
|
||||
Scenario Outline: Article reads carry site_id
|
||||
Given the article 8 belongs to the site 2
|
||||
When <request> is sent
|
||||
Then the article in the response has "site_id": 2
|
||||
|
||||
Examples:
|
||||
| request |
|
||||
| GET /v1/article/8 |
|
||||
| GET /v1/article/ (each item of items) |
|
||||
| POST /v1/article |
|
||||
| PATCH /v1/article/8/publish |
|
||||
| PATCH /v1/article/8 |
|
||||
|
||||
Scenario: The list filters by site key
|
||||
Given the site "shop" has 2 articles and "main" has 3
|
||||
When a verified account sends GET /v1/article/?site=shop
|
||||
Then only the 2 articles of "shop" are listed
|
||||
|
||||
Scenario Outline: The filter composes with the other parameters
|
||||
Given the site "shop" has articles of mixed status and titles
|
||||
When GET /v1/article/?site=shop&<params> is sent
|
||||
Then every returned article belongs to "shop" and satisfies <params>
|
||||
|
||||
Examples:
|
||||
| params |
|
||||
| status=online |
|
||||
| status=draft |
|
||||
| q=spring |
|
||||
| sort=title:asc |
|
||||
| size=5&page=2 |
|
||||
| status=draft&q=launch |
|
||||
|
||||
Scenario Outline: Unknown or empty site keys
|
||||
When GET /v1/article/?site=<key> is sent
|
||||
Then the status is <status>
|
||||
And <result>
|
||||
And the counts stay global
|
||||
|
||||
Examples:
|
||||
| key | status | result |
|
||||
| nope | 200 | the list is empty |
|
||||
| (empty) | 400 | the body is apperr.BodyErrorMessage |
|
||||
|
||||
Scenario: An anonymous or unverified list is filtered by site and shows online articles only
|
||||
Given "shop" has one online and one offline article
|
||||
When a caller without a verified account sends GET /v1/article/?site=shop
|
||||
Then only the online article is returned
|
||||
|
||||
Scenario: An offline article is still not found publicly
|
||||
Given the article 9 is offline on any site
|
||||
When a caller without a verified account sends GET /v1/article/9
|
||||
Then the status is 404
|
||||
And the body is "Article not found"
|
||||
|
||||
Scenario: An article moves to another site
|
||||
Given the article 8 is on the site 1 and the site 2 exists
|
||||
When the user sends PATCH /v1/article/8 with {"site_id": 2}
|
||||
Then the status is 200
|
||||
And the article has site_id 2
|
||||
|
||||
Scenario Outline: Any role that can edit the article may choose its site
|
||||
Given the article 8 is editable by <credentials>
|
||||
When PATCH /v1/article/8 is sent with {"site_id": 2} and <credentials>
|
||||
Then the status is 200
|
||||
|
||||
Examples:
|
||||
| credentials |
|
||||
| the owner's jwt cookie |
|
||||
| a verified admin's jwt cookie |
|
||||
| a valid API key |
|
||||
|
||||
Scenario: The body and the site change together
|
||||
When the user sends PATCH /v1/article/8 with {"title": "New", "site_id": 2}
|
||||
Then both the title and the site_id are updated
|
||||
|
||||
Scenario: An update without site_id keeps the site
|
||||
Given the article 8 is on the site 2
|
||||
When the user sends PATCH /v1/article/8 with {"title": "New"}
|
||||
Then the article is still on the site 2
|
||||
|
||||
Scenario Outline: An unusable site_id is refused
|
||||
When the user sends PATCH /v1/article/8 with {"site_id": <value>}
|
||||
Then the status is <status>
|
||||
And the body is "<body>"
|
||||
And the article is unchanged
|
||||
|
||||
Examples:
|
||||
| value | status | body |
|
||||
| 999 | 404 | site_not_found |
|
||||
| 0 | 400 | the validator error text |
|
||||
| -1 | 400 | apperr.BodyErrorMessage |
|
||||
| "a" | 400 | apperr.BodyErrorMessage |
|
||||
|
||||
Scenario: A site cannot be removed from an article
|
||||
When the user sends PATCH /v1/article/8 with {"site_id": null}
|
||||
Then the status is 400
|
||||
And the body is apperr.BodyErrorMessage
|
||||
And the article is unchanged
|
||||
|
||||
Scenario: Moving to the same site records nothing
|
||||
Given the article 8 is on the site 2
|
||||
When the user sends PATCH /v1/article/8 with {"site_id": 2}
|
||||
Then the status is 200
|
||||
And no activity event is recorded
|
||||
|
||||
Scenario Outline: An empty or unknown update is refused
|
||||
When the user sends PATCH /v1/article/8 with <body>
|
||||
Then the status is 400
|
||||
And the body is apperr.BodyErrorMessage
|
||||
And the article is unchanged
|
||||
|
||||
Examples:
|
||||
| body |
|
||||
| {} |
|
||||
| {"colour": "x"} |
|
||||
|
||||
Scenario: is_online is independent of the site
|
||||
Given the article 8 is online
|
||||
When the user moves it to the site 2
|
||||
Then it is still online
|
||||
|
||||
Scenario: Articles keep working after a site rename
|
||||
Given the article 8 is on the site 2
|
||||
When the owner renames the site 2
|
||||
Then GET /v1/article/8 still returns the article with site_id 2
|
||||
|
||||
Scenario: A site change is recorded in article.edit with site names
|
||||
Given the article 8 "Spring release" is on "Main" and "Shop" exists
|
||||
When the user sends PATCH /v1/article/8 with {"site_id": 2}
|
||||
Then one event "article.edit" exists with changes [{"field": "site", "from": "Main", "to": "Shop"}]
|
||||
|
||||
Rule: Media usage by default social images
|
||||
|
||||
Scenario: An image used as a default social image is counted as used
|
||||
Given the image 5 is the default social image of the site 2 and appears in no article
|
||||
When a verified account looks up the usage of the image 5
|
||||
Then used_in counts the site and the image is not "Unused"
|
||||
|
||||
Scenario: Deleting the image clears the site's field
|
||||
When the owner deletes the image 5
|
||||
Then the status is 204
|
||||
And the site 2 has default_social_image_id null
|
||||
|
||||
Scenario: Merging copies repoints the site
|
||||
Given the image 6 is a copy of the image 5 and the site 2 uses the image 6
|
||||
When the copies are merged into the image 5
|
||||
Then the site 2 has default_social_image_id 5
|
||||
And the merge response reports sites_updated 1
|
||||
|
||||
Scenario: Purge repoints sites the same way
|
||||
Given a purge group whose kept image is 5 and whose duplicate 6 is used by the site 2
|
||||
When the purge runs
|
||||
Then the site 2 has default_social_image_id 5
|
||||
And the purge result reports sites_updated 1
|
||||
|
||||
Scenario: A failed purge group leaves the site pointing at an existing image
|
||||
Given the purge of a group fails midway
|
||||
Then every site default_social_image_id refers to an image that still exists
|
||||
|
||||
Scenario: The usage lookup stays an array and later gains additive keys
|
||||
When a verified account looks up the usage of an image
|
||||
Then the response is a JSON array whose article items keep id, title and published
|
||||
And features/seo_data_backend.feature adds type and fields to every item and lists authors and sites, without removing any key
|
||||
|
||||
Rule: Every site write is recorded in the activity log
|
||||
|
||||
Scenario Outline: A successful write is recorded once after the change
|
||||
When the owner performs <request>
|
||||
Then one event exists with action "<action>", category "sites", target {"type": "site", "id": "<id>", "name": "<name>"}, outcome "success", actor the owner and source "web"
|
||||
And the event was recorded after the change was applied
|
||||
|
||||
Examples:
|
||||
| request | action | id | name |
|
||||
| POST /v1/site/ for "Shop" | site.create | 2 | Shop |
|
||||
| PATCH /v1/site/2 renaming it | site.edit | 2 | Shop |
|
||||
| PATCH /v1/site/2/default | site.set_default | 2 | Shop |
|
||||
| DELETE /v1/site/2 | site.delete | 2 | Shop |
|
||||
|
||||
Scenario Outline: A refused write is recorded as failed with a plain reason
|
||||
When the owner performs <request> which is refused with <code>
|
||||
Then one event exists with action "<action>", outcome "failed" and failure_reason "<reason>"
|
||||
|
||||
Examples:
|
||||
| request | code | action | reason |
|
||||
| POST /v1/site/ with a taken key | site_key_taken | site.create | A site with that key already exists. |
|
||||
| PATCH /v1/site/2 changing the key | key_immutable | site.edit | The key of a site cannot be changed. |
|
||||
| DELETE /v1/site/1 on the default site | default_site | site.delete | The default site cannot be deleted. |
|
||||
| DELETE /v1/site/2 with articles | site_has_articles | site.delete | The site still has articles. |
|
||||
| POST /v1/site/ with an invalid base URL | invalid_site_url | site.create | The site address is not valid. |
|
||||
| PATCH /v1/site/2 with an invalid locale | invalid_locale | site.edit | The locale is not valid. |
|
||||
| PATCH /v1/site/2 with is_default | use_set_default | site.edit | Use the default site action to change the default. |
|
||||
| DELETE /v1/site/2 reassigned to itself | invalid_reassign | site.delete | The destination site is not valid. |
|
||||
| POST /v1/site/ when the repository fails with "db is locked" | 500 | site.create | Something went wrong on our side. Please try again. |
|
||||
| PATCH /v1/site/2/default when the repository fails | 500 | site.set_default | Something went wrong on our side. Please try again. |
|
||||
|
||||
Scenario Outline: Nothing is recorded when there is nothing to attribute
|
||||
When <request> is sent
|
||||
Then no activity event is recorded
|
||||
|
||||
Examples:
|
||||
| request |
|
||||
| PATCH /v1/site/999 as the owner |
|
||||
| DELETE /v1/site/999 as the owner |
|
||||
| POST /v1/site/ with an unknown image (image_not_found) |
|
||||
| POST /v1/site/ as an admin (403) |
|
||||
| POST /v1/site/ with no credentials (401) |
|
||||
| PATCH /v1/site/abc as the owner |
|
||||
| POST /v1/site/ with a malformed body |
|
||||
|
||||
Scenario: A failing audit repository never changes the response
|
||||
Given the audit repository fails on Append
|
||||
When the owner sends POST /v1/site/ with valid values
|
||||
Then the response equals that of a healthy repository
|
||||
And the site was created
|
||||
|
||||
Scenario: Reads are never recorded
|
||||
When GET /v1/site/ is sent
|
||||
Then no activity event is recorded
|
||||
|
||||
Scenario: The key is never a change field
|
||||
When the owner edits a site name, base URL, robots, locale and image
|
||||
Then the changes use only the fields name, base_url, default_robots, locale and default_social_image
|
||||
And no change has the field "key"
|
||||
|
||||
Scenario: The activity API lists site events
|
||||
Given site events were recorded
|
||||
When a verified account sends GET /v1/activity/?category=sites
|
||||
Then the site events are returned with category "sites"
|
||||
|
||||
Rule: Pagination and search of the site list
|
||||
|
||||
Background:
|
||||
Given GET /v1/site/ accepts q, page and size, keeps the body a JSON array, and sends the number of matching sites in the X-Total-Count header on every 200
|
||||
And when neither page nor size is sent, every matching site is returned
|
||||
And when page or size is sent, size is one of 5, 25, 50 or 100 (default 25 if only page is sent) and page is a positive integer (default 1 if only size is sent)
|
||||
And q is at most 200 characters and matches name, key or base_url as a case- and accent-insensitive substring
|
||||
And the order is unchanged and applied before paging: the default site first, then by name, then by id
|
||||
And X-Total-Count is already in the CORS ExposedHeaders, so the router needs no change
|
||||
And an invalid page, size or q answers 400 with apperr.BodyErrorMessage and sends no X-Total-Count, like GET /v1/article/
|
||||
And access is unchanged: a verified session or an API key reads, an unverified account gets 403, no credentials get 401
|
||||
And the body is [] and never null when nothing matches
|
||||
|
||||
Scenario: With no paging parameter every site is returned
|
||||
Given 61 sites of which "Renew" is the default
|
||||
When a verified account sends GET /v1/site/
|
||||
Then the status is 200
|
||||
And the body is an array of 61 sites starting with "Renew"
|
||||
And X-Total-Count is "61"
|
||||
|
||||
Scenario: q alone returns every match
|
||||
Given 61 sites of which 40 match "shop"
|
||||
When a verified account sends GET /v1/site/?q=shop
|
||||
Then the body holds 40 sites and X-Total-Count is "40"
|
||||
|
||||
Scenario Outline: Paging and sizes
|
||||
Given 61 sites
|
||||
When a verified account sends GET /v1/site/?<params>
|
||||
Then the body holds <count> sites
|
||||
And X-Total-Count is "61"
|
||||
|
||||
Examples:
|
||||
| params | count |
|
||||
| page=1 | 25 |
|
||||
| page=2 | 25 |
|
||||
| page=3 | 11 |
|
||||
| size=5 | 5 |
|
||||
| size=25 | 25 |
|
||||
| size=50&page=2 | 11 |
|
||||
| size=100 | 61 |
|
||||
|
||||
Scenario: Pages never overlap and keep the order
|
||||
Given 61 sites
|
||||
When pages 1 to 3 are read with the default size
|
||||
Then the ids are all distinct, the default site is first on page 1, and the concatenation equals the unpaged list
|
||||
|
||||
Scenario: A page past the end is an empty array with the total
|
||||
Given 61 sites
|
||||
When a verified account sends GET /v1/site/?page=99
|
||||
Then the status is 200 and the body is []
|
||||
And X-Total-Count is "61"
|
||||
|
||||
Scenario: No match is an empty array
|
||||
When a verified account sends GET /v1/site/?q=nomatch
|
||||
Then the status is 200 and the body is [] and not null
|
||||
And X-Total-Count is "0"
|
||||
|
||||
Scenario Outline: Search matches name, key and base URL
|
||||
Given the sites "Renew" (key "renew", https://renew.example.com), "Journal" (key "blog", https://journal.example.org) and "Archive" (key "archive", https://old.example.net)
|
||||
When a verified account sends GET /v1/site/?q=<q>
|
||||
Then the names are <names>
|
||||
And X-Total-Count is "<total>"
|
||||
|
||||
Examples:
|
||||
| q | names | total |
|
||||
| renew | "Renew" | 1 |
|
||||
| JOURNAL | "Journal" | 1 |
|
||||
| blog | "Journal" | 1 |
|
||||
| example.org | "Journal" | 1 |
|
||||
| example | "Renew", "Journal", "Archive" | 3 |
|
||||
| nobody | none | 0 |
|
||||
|
||||
Scenario: Search ignores accents
|
||||
Given the site "Café" with key "cafe"
|
||||
When a verified account sends GET /v1/site/?q=cafe and GET /v1/site/?q=CAFÉ
|
||||
Then both answer "Café" with X-Total-Count "1"
|
||||
|
||||
Scenario: Search and paging compose and the total follows the search
|
||||
Given 61 sites of which 27 match "shop"
|
||||
When a verified account sends GET /v1/site/?q=shop&page=2
|
||||
Then the body holds 2 sites and X-Total-Count is "27"
|
||||
|
||||
Scenario: The default site is not forced into the results
|
||||
Given the default site "Renew" and the site "Journal"
|
||||
When a verified account sends GET /v1/site/?q=journal
|
||||
Then the body is "Journal" only
|
||||
|
||||
Scenario: A wildcard in q is literal
|
||||
Given the site "100% Shop" and the site "Main"
|
||||
When a verified account sends GET /v1/site/?q=%25
|
||||
Then the body is "100% Shop" only
|
||||
|
||||
Scenario Outline: Invalid page, size or q
|
||||
When a verified account sends GET /v1/site/?<params>
|
||||
Then the status is 400
|
||||
And the body is apperr.BodyErrorMessage
|
||||
And no X-Total-Count header is sent
|
||||
|
||||
Examples:
|
||||
| params |
|
||||
| page=0 |
|
||||
| page=-1 |
|
||||
| page=abc |
|
||||
| page= |
|
||||
| size=0 |
|
||||
| size=30 |
|
||||
| size=101 |
|
||||
| size=abc |
|
||||
| size= |
|
||||
| q=(201 characters) |
|
||||
|
||||
Scenario: q at the limit is accepted
|
||||
When a verified account sends GET /v1/site/?q=(200 characters)
|
||||
Then the status is 200 and the body is [] and X-Total-Count is "0"
|
||||
|
||||
Scenario: The other fields are unchanged
|
||||
When a verified account sends GET /v1/site/?size=5
|
||||
Then every site carries the same fields as before, article_count included, and the owner-only writes are unchanged
|
||||
|
||||
Scenario Outline: Every reader gets the header
|
||||
When GET /v1/site/?size=5 is sent with <credentials>
|
||||
Then the status is 200 and X-Total-Count is present
|
||||
|
||||
Examples:
|
||||
| credentials |
|
||||
| the owner's jwt cookie |
|
||||
| a verified admin's jwt cookie |
|
||||
| a valid API key |
|
||||
|
||||
Scenario Outline: Refused readers get no header
|
||||
When GET /v1/site/?size=5 is sent with <credentials>
|
||||
Then the status is <status> and no X-Total-Count is sent
|
||||
|
||||
Examples:
|
||||
| credentials | status |
|
||||
| an unverified account's jwt cookie | 403 |
|
||||
| no credentials | 401 |
|
||||
|
||||
Scenario: CORS exposes the header
|
||||
Given CORS_ALLOWED_ORIGINS includes "https://app.example.com"
|
||||
When a preflighted GET /v1/site/?page=2 comes from that origin
|
||||
Then Access-Control-Expose-Headers lists X-Total-Count and Link
|
||||
|
||||
Rule: Documentation
|
||||
|
||||
Scenario: The docs describe the new surface
|
||||
Then docs/api.md documents the /v1/site routes, their errors, article site_id, the ?site= filter and the media sites_updated field
|
||||
And docs/api.md documents q, page, size, the all-sites default without paging parameters, the 400, the past-the-end page and X-Total-Count on GET /v1/site/
|
||||
And docs/configuration.md states that PUBLIC_URL seeds the first site once at migration
|
||||
And docs/architecture.md mentions the site aggregate, its repository and its use cases
|
||||
@@ -0,0 +1,114 @@
|
||||
# QA procedure: Sites backend
|
||||
|
||||
Spec: `features/sites_backend.feature`. Go tests only, in `test/` (package `test`), run with `task test`. No live server, no real SMTP, no real SQLite file outside the temp-dir repository-contract harness. Call `validator.InitValidator()` before any handler call. Every error assertion compares the plain-text body to the exact code token.
|
||||
|
||||
## Setup
|
||||
|
||||
- New files `test/site_*_test.go`. Fakes have unique names: `mockSiteRepo` (sites, default flag, article counts, transactional reassign-and-delete as one operation, failure injection), `mockSiteImageRepo` (images and usage), and an extended `mockArticleRepo` (site_id, site filter, move). A fake audit repository with fail and panic switches is reused.
|
||||
- Routers mirror `api/router.go`: a new `NewSiteRouter`, plus the article and media routers. Protected routes sit behind `jwtauth.Verifier` + `jwtauth.Authenticator` with a test `jwtauth.New("HS256", ...)`. Requests carry real signed `jwt` cookies carrying the `user_id` claim for an owner, an admin and an unverified account (roles are only owner and admin); an API key request uses the key authentication path.
|
||||
|
||||
## A. Reading (Rule: Reading sites)
|
||||
|
||||
1. GET /v1/site/ with three sites: 200, order default first then name, `article_count` on each.
|
||||
2. GET /v1/site/ credentials table: owner, admin, API key give 200; unverified gives 403; none gives 401.
|
||||
3. A site without image and locale returns `default_social_image_id` null and `locale` null.
|
||||
|
||||
## B. Creating
|
||||
|
||||
4. POST creates a site: 201, full body, stored, `is_default` false, `article_count` 0.
|
||||
5. Optional fields default to `default_robots` "index", locale null, image null.
|
||||
6. POST with `is_default` true: the new site is the only default.
|
||||
7. Base URL normalisation table (trailing slash, host case, loopback http).
|
||||
8. Base URL rule table (all rows, `invalid_site_url`).
|
||||
9. Key format table (valid and invalid rows) and `site_key_taken` 409 with nothing stored.
|
||||
10. Other fields table: name, robots, locale (`invalid_locale`), unknown image (`image_not_found`), malformed JSON gives 400 and nothing stored.
|
||||
11. Locale table: valid values stored, empty and null stored as null.
|
||||
|
||||
## C. Editing
|
||||
|
||||
12. PATCH edits name, base_url, robots, locale and returns the site with the unchanged key.
|
||||
13. Absent fields stay untouched.
|
||||
14. Image set to 5 then cleared with null.
|
||||
15. Key table: same key 200, different key 400 `key_immutable`, key unchanged.
|
||||
16. A rejected key change leaves the name unchanged.
|
||||
17. `is_default` in the body: 400 `use_set_default`, default unchanged.
|
||||
18. Validation table (base_url, locale, image, name, robots), site unchanged.
|
||||
19. Missing site 404 `site_not_found`; malformed id gives the uint32 format error.
|
||||
20. No-op edit: 200 and no audit event.
|
||||
|
||||
## D. Default site
|
||||
|
||||
21. PATCH /{id}/default swaps the default; exactly one default remains.
|
||||
22. Current default: 200, no event. Missing site: 404.
|
||||
23. Fault injected on the second step of the swap: the previous default is still the only default (the fake mimics the transaction rollback).
|
||||
24. A subsequently created article gets the new default's id.
|
||||
|
||||
## E. Deleting
|
||||
|
||||
25. Empty site: 204, gone.
|
||||
26. Site with articles and no `reassign_to`: 409 `site_has_articles`, unchanged.
|
||||
27. With a valid `reassign_to`: 204, articles moved, site gone, via a single repository operation (assert the fake records one call).
|
||||
28. Failure injected in that operation: articles and site unchanged.
|
||||
29. `reassign_to` table: 999 gives 404 `site_not_found`; the site's own id and a non-numeric value give 400 `invalid_reassign`.
|
||||
30. Default site: 403 `default_site`, also when it has articles and no `reassign_to`. Missing site: 404. Unused `reassign_to` on an empty site: 204, destination untouched.
|
||||
|
||||
## F. Owner-only writes
|
||||
|
||||
31. Role table for POST, PATCH, PATCH default, DELETE: admin gives 403 "Only the owner can do this."; API key gives 403 "This action needs a real session."; nothing changes.
|
||||
32. Admin with a malformed body still gets 403 "Only the owner can do this.".
|
||||
|
||||
## G. Articles
|
||||
|
||||
33. New article is offline and on the default site; reads (GET one, GET list, publish, PATCH) carry `site_id`.
|
||||
34. `GET /v1/article/?site=shop` filters; composes with status (online, draft), q, sort (for example `title:asc`), size and page; `?site=nope` gives 200 empty with global `counts`; `?site=` gives 400 `apperr.BodyErrorMessage`.
|
||||
35. Without a verified account, `GET /v1/article/?site=shop` returns online articles only (there is no separate public route); `GET /v1/article/{offline id}` is 404 "Article not found".
|
||||
36. PATCH `site_id` moves the article for owner, admin and an API key; title plus `site_id` change together; omission keeps the site; `is_online` unaffected; rename of the site leaves the article readable.
|
||||
37. Unusable `site_id` table, one case each: 999 gives 404 `site_not_found`; 0 gives 400 with the validator error text; -1 and "a" give 400 `apperr.BodyErrorMessage` (decode failure); null gives 400 `apperr.BodyErrorMessage`; `{}` and an unknown-only object give 400 `apperr.BodyErrorMessage`; in every case the article is unchanged and no event is recorded. A same-site move returns 200 and records nothing.
|
||||
|
||||
## H. Media
|
||||
|
||||
38. Usage lookup counts a site's default social image, stays a JSON array whose article items keep id, title and published (additive keys are specified in seo_data_backend), image not "Unused".
|
||||
39. Deleting the image succeeds (204) and nulls the site's `default_social_image_id`.
|
||||
40. Merge repoints sites and reports `sites_updated`; purge does the same; a failed purge group leaves every site pointing at an existing image.
|
||||
|
||||
## I. Activity log
|
||||
|
||||
41. Success table: one event per write with action, category "sites", target, actor, source, recorded after the change.
|
||||
42. Failed table with the plain reasons; unknown ids, 403, 401, malformed requests record nothing; reads record nothing.
|
||||
43. Failing and panicking audit repository leave the response and the change as with a healthy one.
|
||||
44. After recording site events, a verified session GET /v1/activity/?category=sites returns the create, edit, set default and delete events with category "sites" and no events of other categories (an API key gets the route's existing session refusal). Failure reasons use the style of `auditFailures.go`: the four site sentinels map to the plain sentences of the feature and any other error gives `GenericFailureReason`. The change fields are limited to name, base_url, default_robots, locale, default_social_image, site and never "key"; article.edit with a site change holds `{"field":"site","from":"Main","to":"Shop"}`.
|
||||
|
||||
## J. Persistence and migration
|
||||
|
||||
45. Repository-contract harness (temp-dir SQLite, MySQL and Postgres opt-in through the existing env switches): site repository contract, transactional default swap, reassign-and-delete, backfill. `database.Migrate` is called with PUBLIC_URL at every caller, including `test/sqlite_schema_unchanged_test.go`, which is updated for the new table and column. Seed table (path dropped, http rewritten to https, loopback kept), unparseable value returns an error naming PUBLIC_URL and creates no site, backfill of existing articles, second run changes nothing, owner-edited base URL survives a restart.
|
||||
|
||||
## K. Quality gates
|
||||
|
||||
46. Layering guard: the use cases import no persistence, mailer, models, gorm, net/http or chi; the domain site package imports no GORM or HTTP; handlers import no persistence; no comments added.
|
||||
47. Scoped mutation run through `task mutate` only, for example `MUTATE_FILES=<site and article use case files> MUTATE_RUN='TestSite' MUTATE_WORKERS=2 task mutate -- <use case package path>`; report LIVED and NOT COVERED mutants; re-check filtered suspects without `MUTATE_RUN`. Also run `task lint:go` and `task fmt`.
|
||||
48. Docs (Rule: Documentation), checked by reading the files: docs/api.md documents the five /v1/site routes with auth, error tokens, article `site_id`, the `?site=` filter, `sites_updated` on media merge and purge; docs/configuration.md says PUBLIC_URL seeds the first site once at migration; docs/architecture.md names the site aggregate, repository and use cases. No comment is added to any file.
|
||||
|
||||
## L. Pagination and search of the list (Go, `test/`, `task test`)
|
||||
|
||||
Build `site.NewHandler(...)` over `mockSiteRepo` extended with `q`, paging and a total, mounted on a `chi.NewRouter()` mirroring `NewSiteRouter`, with the same jwtauth setup and cookies as above. Call `validator.InitValidator()`. Add the CORS options of `enableCorsIfConfigured` to one test router to check the exposed header (pattern: `test/seo_output_sitemap_http_test.go`).
|
||||
|
||||
49. 61 sites, no parameter: 61 items, default first, `X-Total-Count` "61". `q=shop` alone returns every match with the matching count.
|
||||
50. Page/size table (page=1/2/3, size=5/25, size=50&page=2, size=100): count of items and `X-Total-Count` "61" each time.
|
||||
51. Pages 1-3 have distinct ids; their concatenation equals the unpaged list; the default site is first on page 1.
|
||||
52. `page=99` gives 200, body exactly `[]` (raw-bytes check, not `null`) and the real total. `q=nomatch` gives `[]` and "0".
|
||||
53. The `q` table (name, key, base URL, uppercase, accent folding, partial host, no match), search plus paging, the default site not forced into a non-matching result, and `%` and `_` in `q` matched literally.
|
||||
54. The invalid table (page 0, -1, abc, empty; size 0, 30, 101, abc, empty; q of 201 characters): 400 `apperr.BodyErrorMessage` and no `X-Total-Count`. q of 200 characters is 200 with `[]`.
|
||||
55. Credentials table: owner, admin, API key give 200 with the header; unverified 403 and none 401 give no header. The existing section F owner-only write table is rerun and stays green.
|
||||
56. CORS preflight from an allowed origin exposes `X-Total-Count`.
|
||||
57. Repository (real SQLite in the temp-dir harness, same file as the contract suite): ordering across the page boundary, `q` over the three fields, total equals matches, `article_count` correct on each page. MySQL and Postgres run the same cases through `task test:mysql` and `task test:postgres`, which use the opt-in switches `RENEWCMS_TEST_MYSQL_DSN` and `RENEWCMS_TEST_POSTGRES_DSN`.
|
||||
58. Docs, read by hand: `docs/api.md` (the `GET /v1/site/` row), `web/src/data/apiCatalogue.ts` (query parameters q/page/size and the `X-Total-Count` response header, no-paging default) with `apiCatalogue.spec.ts`, and the Integration reference counts in `IntegrationView.spec.ts`. No comment added anywhere.
|
||||
59. Scoped `task mutate` only: `MUTATE_FILES=<site list use case and repository files> MUTATE_RUN='TestSite' MUTATE_WORKERS=2 task mutate -- ./internal/infrastructure/useCases`. Report LIVED and NOT COVERED, and re-check filtered suspects without `MUTATE_RUN`. Then `task lint:go` and `task fmt`.
|
||||
|
||||
## Manual
|
||||
|
||||
- `curl -i -b <cookie> 'http://localhost:8080/v1/site/?q=ren&size=5&page=2'` against `task dev`; a browser cross-origin read with `CORS_ALLOWED_ORIGINS` set; the editor's Site select and the Articles Site filter still list all sites (they send no paging parameter).
|
||||
- MySQL and Postgres: run the contract suite with the opt-in env vars against real servers.
|
||||
- Real boot with an old database copy and PUBLIC_URL set: one "Default" site appears, articles backfilled, second boot changes nothing.
|
||||
- Docker with the `/data` volume: boot an existing database and confirm the same.
|
||||
- Read the activity log screen and the CSV export: site events show names and failure reasons, and no key change.
|
||||
- Not covered here: the SPA (a later slice).
|
||||
@@ -0,0 +1,216 @@
|
||||
Feature: Hardening after the Sites, Authors and SEO slices
|
||||
|
||||
As the maintainer of a RenewCMS installation
|
||||
I want the SEO panel, the SEO check cache, the chunked lookups and the slug backfill to hold on large data
|
||||
So that behaviour stays correct beyond the first page of media, on every database, and on every boot
|
||||
|
||||
Background:
|
||||
Given this file covers four items; items 4, 8 and 9 are behaviour-preserving and item 3 adds one read endpoint, GET /v1/media/{id}
|
||||
And every existing scenario stays green without edits to its assertions
|
||||
And no comment is added to any file
|
||||
|
||||
Rule: The SEO panel names its images by id (item 3)
|
||||
|
||||
Background:
|
||||
Given GET /v1/media/{id} is mounted in NewMediaRouter behind the same middleware as GET /v1/media/: jwtauth.Verifier, the API key authentication, AuditContext, RequireSignedIn, jwtauth.Authenticator, RequireCurrentToken and RequireVerifiedUser
|
||||
And it reads one image and writes nothing, so it records no activity event
|
||||
And it answers 200 with the same JSON item shape as one element of items in GET /v1/media/
|
||||
And a missing image answers 404 with apperr.ImageNotFoundErrorMessage ("Image not found")
|
||||
And a malformed id answers 400 with apperr.IdUint32ErrorMessage
|
||||
And the SPA useMediaNames resolves the wanted ids with GET /v1/media/{id} and no longer reads the first 100 items of the list
|
||||
|
||||
Scenario Outline: Who can read one image
|
||||
Given the image 5 exists
|
||||
When GET /v1/media/5 is sent with <credentials>
|
||||
Then the status is <status>
|
||||
|
||||
Examples:
|
||||
| credentials | status |
|
||||
| the owner's jwt cookie | 200 |
|
||||
| a verified admin's jwt cookie | 200 |
|
||||
| a verified account with another role | 200 |
|
||||
| a valid API key | 200 |
|
||||
| an unverified account's jwt cookie | 403 |
|
||||
| no credentials | 401 |
|
||||
|
||||
Scenario: The item has the shape of the list
|
||||
Given the image 5 exists with a name, a hash, a size, dimensions, a used_in count and variants information
|
||||
When a verified account sends GET /v1/media/5
|
||||
Then the body is the JSON object equal to the element of items for the image 5 in GET /v1/media/
|
||||
And no other field is added or removed
|
||||
|
||||
Scenario: A missing image is not found
|
||||
When a verified account sends GET /v1/media/999
|
||||
Then the status is 404 and the body is "Image not found"
|
||||
|
||||
Scenario Outline: A malformed id is refused
|
||||
When a verified account sends GET /v1/media/<id>
|
||||
Then the status is 400 and the body is apperr.IdUint32ErrorMessage
|
||||
|
||||
Examples:
|
||||
| id |
|
||||
| abc |
|
||||
| -1 |
|
||||
| 4294967296 |
|
||||
| 1.5 |
|
||||
|
||||
Scenario: The route does not shadow the existing media routes
|
||||
When GET /v1/media/5/usage and GET /v1/media/5/variants are sent as before
|
||||
Then they answer exactly as before this change
|
||||
|
||||
Scenario: A non-GET method keeps its meaning
|
||||
When PATCH /v1/media/5 and DELETE /v1/media/5 are sent as before
|
||||
Then they behave exactly as before this change
|
||||
|
||||
Scenario: Reading one image records nothing
|
||||
When a verified account sends GET /v1/media/5
|
||||
Then no activity event is recorded
|
||||
|
||||
Scenario: A selected image outside the first 100 media items is named
|
||||
Given the article's cover image has id 150 and is not among the first 100 media items
|
||||
When the SEO panel opens
|
||||
Then the panel requests GET /v1/media/150 and shows the name and thumbnail of the image 150
|
||||
And the same holds for the social image
|
||||
|
||||
Scenario: Images already known are not fetched again
|
||||
Given the panel has resolved the images 150 and 151
|
||||
When the panel re-renders with the same selection
|
||||
Then no lookup request is sent
|
||||
|
||||
Scenario: An image that no longer exists
|
||||
Given GET /v1/media/150 answers 404
|
||||
Then the panel shows its existing "unknown image" fallback and no error notice
|
||||
|
||||
Scenario: A failing lookup never blocks the panel
|
||||
Given GET /v1/media/150 fails with a 500 or a network error
|
||||
Then the panel stays usable, shows the existing fallback and raises no notice
|
||||
|
||||
Scenario: Behaviour with fewer than 100 media items is unchanged
|
||||
Given the library holds 12 media items
|
||||
Then the names shown are the same as before
|
||||
|
||||
Scenario: The list is no longer requested for names
|
||||
When the SEO panel resolves any selected image
|
||||
Then no GET /v1/media/?page=1&size=100&sort=newest request is sent for names
|
||||
|
||||
Scenario: The docs describe the route
|
||||
Then docs/api.md documents GET /v1/media/{id} with its auth, the 200 shape, the 404 and the 400
|
||||
And web/src/data/apiCatalogue.ts lists GET /v1/media/{id} in the Media group, with its spec and the Integration reference counts updated
|
||||
|
||||
Rule: The SEO check answer cache (item 4)
|
||||
|
||||
Scenario: The same effective input is checked once
|
||||
Given a check was answered for an article body and fields
|
||||
When the same fields are checked again with a different but irrelevant difference in the request (key order or whitespace of the JSON)
|
||||
Then no second POST /v1/article/{id}/seo/check is sent and the cached answer is shown
|
||||
|
||||
Scenario Outline: A field that affects the result invalidates the cache
|
||||
Given a check was answered
|
||||
When <field> changes and the check runs again
|
||||
Then POST /v1/article/{id}/seo/check is sent again
|
||||
|
||||
Examples:
|
||||
| field |
|
||||
| the title |
|
||||
| the body |
|
||||
| the description |
|
||||
| the excerpt |
|
||||
| the slug |
|
||||
| the cover image |
|
||||
| the social image |
|
||||
| the noindex switch |
|
||||
| the site |
|
||||
| the canonical URL |
|
||||
|
||||
Scenario: A field that does not affect the result does not invalidate it
|
||||
Given a check was answered
|
||||
When only a field the check ignores changes
|
||||
Then the cached answer is reused
|
||||
|
||||
Scenario: A failed check is not cached
|
||||
Given a check failed with a 500
|
||||
When the same input is checked again
|
||||
Then the request is sent again
|
||||
|
||||
Scenario: The cache stays bounded
|
||||
Given 200 distinct inputs were checked
|
||||
Then the cache holds no more than its existing limit and a repeated recent input is still a hit
|
||||
|
||||
Rule: Chunked IN lookups on a real database (item 8)
|
||||
|
||||
Background:
|
||||
Given the article repository looks ids up in batches of 500 (articles by id, article_authors by article id, authors by id)
|
||||
|
||||
Scenario: A page-sized lookup keeps every row once and in order
|
||||
Given 1,200 articles, so the lookup spans 3 batches
|
||||
When the repository loads all 1,200 ids
|
||||
Then 1,200 articles come back, each once, in the requested order
|
||||
|
||||
Scenario Outline: Batch boundaries
|
||||
Given <n> ids are requested and all exist
|
||||
Then exactly <n> rows come back
|
||||
|
||||
Examples:
|
||||
| n |
|
||||
| 0 |
|
||||
| 1 |
|
||||
| 499 |
|
||||
| 500 |
|
||||
| 501 |
|
||||
| 1000 |
|
||||
| 1001 |
|
||||
|
||||
Scenario: Missing ids are absent
|
||||
Given 600 ids of which 100 do not exist
|
||||
Then 500 rows come back and none is invented
|
||||
|
||||
Scenario: Credits keep their order across batches
|
||||
Given 700 articles each crediting 3 authors in a chosen order
|
||||
When the credits are loaded
|
||||
Then every article lists its authors in its stored order (position, then id)
|
||||
|
||||
Scenario: Soft-deleted rows follow the existing rule
|
||||
Given 3 of the 1,200 articles are soft-deleted
|
||||
Then the lookup returns the same rows as the single-query path would
|
||||
|
||||
Scenario: It works on every supported database
|
||||
When the tests run against SQLite, MySQL/MariaDB and PostgreSQL
|
||||
Then the results are identical
|
||||
|
||||
Rule: The article slug backfill (item 9)
|
||||
|
||||
Scenario: A large database is filled in batches
|
||||
Given a database from before slugs holding 5,000 articles with empty slugs
|
||||
When the backfill runs
|
||||
Then every article has a non-empty slug unique within its site
|
||||
And the writes were made in several transactions of bounded size and not in one
|
||||
And the batch size is a named constant chosen by the implementation
|
||||
|
||||
Scenario: The second boot changes nothing
|
||||
Given the backfill already ran
|
||||
When it runs again
|
||||
Then no row is written, no slug changes and updated_at is untouched
|
||||
|
||||
Scenario: A crashed backfill resumes
|
||||
Given the backfill stopped after its first batch
|
||||
When it runs again
|
||||
Then the remaining articles are filled and the already filled ones keep their slugs
|
||||
|
||||
Scenario: Duplicates get the first free suffix
|
||||
Given 3 articles with the same title in one site and 1 in another site
|
||||
When the backfill runs
|
||||
Then the first keeps the plain slug, the others get -2 and -3, and the other site's article keeps the plain slug
|
||||
|
||||
Scenario: Soft-deleted rows get their tombstone once
|
||||
Given 2 soft-deleted articles
|
||||
When the backfill runs twice
|
||||
Then each has the tombstone slug after the first run and is not rewritten by the second
|
||||
|
||||
Scenario: Existing slugs are kept
|
||||
Given an article whose slug was set by the owner
|
||||
When the backfill runs
|
||||
Then its slug is unchanged
|
||||
|
||||
Scenario: The unique index exists afterwards and a repeat does not fail
|
||||
When the backfill and index creation run on a second boot
|
||||
Then idx_articles_site_slug exists and no error is returned
|
||||
@@ -0,0 +1,63 @@
|
||||
# QA procedure: Hardening after the Sites, Authors and SEO slices
|
||||
|
||||
Spec: `features/tech_debt_hardening.feature`. The Go part is in `test/` (package `test`, `task test`); the web part is Vitest (`task test:web`). Constraints: no commits; no comments in code; scoped `task mutate` only for the Go files of items 3, 8 and 9 (and of items 5 and 6 per their own QA files); `task visual:check` only on `articles`, `sites` and `integration` to confirm no regression, with no new `approvedBy` exception and the waived screens untouched; `docs/design` read-only.
|
||||
|
||||
## Item 3: GET /v1/media/{id} (Go, `test/`, `task test`)
|
||||
|
||||
Build `media.NewHandler(...)` over the real media use cases and the existing fake image repository and storage fakes used by the media tests (unique fake type names across files). Mount on a fresh `chi.NewRouter()` that mirrors `NewMediaRouter` in `api/router.go`, behind `jwtauth.Verifier`, the API key authentication path, `middleware.RequireSignedIn`, `jwtauth.Authenticator` and `RequireVerifiedUser`, with a test `jwtauth.New("HS256", ...)`. Requests carry signed `jwt` cookies with the `user_id` claim for an owner, an admin, a verified account with another role and an unverified account. Call `validator.InitValidator()`.
|
||||
|
||||
1. Credentials table on an existing image 5: owner, admin, other verified role and a valid API key give 200; an unverified account gives 403; no credentials give 401.
|
||||
2. Shape: decode `GET /v1/media/5` and the matching element of `items` from `GET /v1/media/` into maps; assert the key sets and values are equal.
|
||||
3. `GET /v1/media/999` gives 404 with the exact plain-text body "Image not found" (`apperr.ImageNotFoundErrorMessage`).
|
||||
4. Malformed ids `abc`, `-1`, `4294967296`, `1.5` give 400 with `apperr.IdUint32ErrorMessage`.
|
||||
5. Regression: `GET /{id}/usage`, `GET /{id}/variants`, `PATCH /{id}` and `DELETE /{id}` still answer as before (the existing tests stay green without edits), and the variant routes keep their `RejectAPIKey` and owner/admin rule.
|
||||
6. No activity event is recorded by the read (the fake audit repository stays empty).
|
||||
7. Docs, read by hand: `docs/api.md` documents `GET /v1/media/{id}` (auth, 200 shape, 404, 400); `web/src/data/apiCatalogue.ts` lists it in the Media group, and its spec and `IntegrationView.spec.ts` counts are updated; `docs/release-notes.md` line.
|
||||
8. Scoped mutation through `task mutate` only, for the media files touched by the change: `MUTATE_FILES=<the GetMedia use case file and any media file touched> MUTATE_RUN='TestMedia' MUTATE_WORKERS=2 task mutate -- ./internal/infrastructure/useCases`. Report LIVED and NOT COVERED; re-check filtered suspects without `MUTATE_RUN`. Then `task lint:go` and `task fmt`.
|
||||
|
||||
## Item 3: media names (Vitest, `web/`)
|
||||
|
||||
Mock `useApi`'s `request` for `GET /v1/media/{id}` per case.
|
||||
|
||||
9. Open the SEO panel with cover id 150 and social id 151 (neither in any first page of the library). Mock `GET /v1/media/150` and `GET /v1/media/151` to return items. Assert the panel shows their names and thumbnails, and that no `GET /v1/media/?page=1&size=100&sort=newest` request is made.
|
||||
10. Re-render with the same selection: assert no new request (the mocked call count stays).
|
||||
11. `GET /v1/media/150` answers 404: the fallback is shown, no notice. A 500 and a network error: panel usable, fallback, no notice.
|
||||
12. A library of 12 items: the same names as before.
|
||||
13. The existing `useMediaNames` and SEO-panel specs pass; the assertions that depended on the list lookup are amended only where they mock the old request, and that diff is listed in the report.
|
||||
|
||||
## Item 4: SEO check cache (Vitest)
|
||||
|
||||
14. Same fields, different key order: one POST (assert the mocked call count).
|
||||
15. Table, one case per result-affecting field (title, body, description, excerpt, slug, cover image, social image, noindex, site, canonical URL): a second POST is sent.
|
||||
16. A field the check ignores changes: no second POST.
|
||||
17. A 500 is not cached: the retry POSTs.
|
||||
18. 200 distinct inputs: the cache size stays at its existing limit and the most recent input is a hit.
|
||||
19. The existing editor SEO specs pass unchanged.
|
||||
|
||||
## Item 8: chunked lookups (Go, `test/`)
|
||||
|
||||
20. Temp-dir SQLite (never the real database file): seed 1,200 articles; load all ids; assert 1,200 rows, no duplicates, requested order.
|
||||
21. Boundary table 0, 1, 499, 500, 501, 1000, 1001 ids.
|
||||
22. 600 ids with 100 missing gives 500 rows. 700 articles with 3 ordered credits each come back in stored order across batches (including the `position ASC, id ASC` rule). Soft-deleted rows match the single-query path.
|
||||
23. Name the MySQL and Postgres variants so the existing filters match them: `TestMySQLChunkedLookups` (run by `-run MySQL`) and `TestPostgresChunkedLookups` (run by `-run Postgres`). They skip when `RENEWCMS_TEST_MYSQL_DSN` or `RENEWCMS_TEST_POSTGRES_DSN` is unset, like the existing contract tests.
|
||||
|
||||
## Item 9: slug backfill (Go, `test/`, temp-dir SQLite)
|
||||
|
||||
24. Seed 5,000 articles with empty slugs across two sites; run `database.BackfillArticleSlugs`; assert unique non-empty slugs within each site; assert the writes ran in several bounded transactions (the batch size is a named constant chosen by the coder; assert through a counting hook or a GORM callback counter in the test, not a log).
|
||||
25. Second boot: record every row's `slug` and `updated_at` and the DB write count (callback), run again, and assert the values are identical and the write count is 0. Also call `database.Migrate` twice.
|
||||
26. Interrupted run: stop after the first batch (failure injection on the second batch), assert the first batch is committed, rerun, and assert the rest are filled and the first batch's slugs unchanged.
|
||||
27. Suffix table (3 same-title articles in one site plus 1 in another), tombstones for soft-deleted rows written once, owner-set slugs kept, index `idx_articles_site_slug` present and a repeated `ensureArticleSlugIndex` returns nil.
|
||||
28. Existing slug migration tests (`planSlugAssignments`) stay green.
|
||||
|
||||
## Quality gates
|
||||
|
||||
29. Layering guard: use cases import no persistence, mailer, models, gorm, net/http or chi; the domain package imports no GORM or HTTP; handlers import no persistence; no comment added.
|
||||
30. Scoped mutation for items 3, 8 and 9 only, through `task mutate`: `MUTATE_FILES=articleRepository.go,articleSlugBackfill.go,<item 3 media files> MUTATE_RUN='TestChunked|TestBackfill|TestMedia' MUTATE_WORKERS=2 task mutate -- ./internal/infrastructure/persistence/repositories ./internal/infrastructure/persistence/database ./internal/infrastructure/useCases`. Report LIVED and NOT COVERED; re-check filtered suspects without `MUTATE_RUN`. Then `task lint:go`, `task fmt`, `task test` and `task test:web`.
|
||||
31. `task visual:check -- articles`, `-- sites` and `-- integration`: all captures pass at 10 %; no exception added.
|
||||
|
||||
## Manual
|
||||
|
||||
- MySQL and PostgreSQL (item 8, and the repository cases of items 5 and 6): run `task test:mysql` (mysql:8.4 then mariadb:11) and `task test:postgres` (postgres:16 then 17). Docker is required; the tasks start and remove the containers. Extra arguments go after `--`, for example `task test:postgres -- -run Postgres.*Chunked -v`. To use your own server instead: `RENEWCMS_TEST_MYSQL_DSN='user:pass@tcp(host:3306)/db' go test -tags nofrontend ./test/... -run MySQL -count=1` and `RENEWCMS_TEST_POSTGRES_DSN='postgres://user:pass@host:5432/db?sslmode=disable' go test -tags nofrontend ./test/... -run Postgres -count=1`. Use a scratch database. No CI exists, so this is run by hand.
|
||||
- Item 3 on a live app: with more than 100 media items, open an article whose cover is an old image; the SEO panel shows its name. `curl -i -b <cookie> http://localhost:8080/v1/media/<id>` returns the item, 404 for a missing id and 400 for `abc`.
|
||||
- Slug backfill on a real file: copy an old database, boot with `task dev`, confirm slugs and that a second boot changes no row (compare `updated_at` before and after).
|
||||
- Item 7 (the `?seo=` measurement) is a measurement with its result recorded in `docs/`, so it has no Gherkin.
|
||||
@@ -12,13 +12,13 @@ require (
|
||||
github.com/glebarez/sqlite v1.11.0
|
||||
github.com/go-chi/chi/v5 v5.2.3
|
||||
github.com/go-chi/cors v1.2.2
|
||||
github.com/go-chi/jwtauth/v5 v5.3.3
|
||||
github.com/go-chi/jwtauth/v5 v5.4.0
|
||||
github.com/go-playground/validator/v10 v10.28.0
|
||||
github.com/go-sql-driver/mysql v1.8.1
|
||||
github.com/google/uuid v1.6.0
|
||||
github.com/jackc/pgx/v5 v5.10.0
|
||||
github.com/joho/godotenv v1.5.1
|
||||
github.com/lestrrat-go/jwx/v2 v2.1.6
|
||||
github.com/lestrrat-go/jwx/v3 v3.3.0
|
||||
golang.org/x/crypto v0.57.0
|
||||
golang.org/x/image v0.46.0
|
||||
golang.org/x/net v0.59.0
|
||||
@@ -47,7 +47,7 @@ require (
|
||||
github.com/aws/aws-sdk-go-v2/service/ssooidc v1.43.1 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/sts v1.51.1 // indirect
|
||||
github.com/aws/smithy-go v1.28.1 // indirect
|
||||
github.com/decred/dcrd/dcrec/secp256k1/v4 v4.4.0 // indirect
|
||||
github.com/decred/dcrd/dcrec/secp256k1/v4 v4.4.1 // indirect
|
||||
github.com/dustin/go-humanize v1.0.1 // indirect
|
||||
github.com/ebitengine/purego v0.10.1 // indirect
|
||||
github.com/fatih/color v1.18.0 // indirect
|
||||
@@ -55,7 +55,7 @@ require (
|
||||
github.com/glebarez/go-sqlite v1.22.0 // indirect
|
||||
github.com/go-playground/locales v0.14.1 // indirect
|
||||
github.com/go-playground/universal-translator v0.18.1 // indirect
|
||||
github.com/goccy/go-json v0.10.5 // indirect
|
||||
github.com/goccy/go-json v0.10.6 // indirect
|
||||
github.com/jackc/pgpassfile v1.0.0 // indirect
|
||||
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect
|
||||
github.com/jackc/puddle/v2 v2.2.2 // indirect
|
||||
@@ -63,15 +63,17 @@ require (
|
||||
github.com/jinzhu/now v1.1.5 // indirect
|
||||
github.com/leodido/go-urn v1.4.0 // indirect
|
||||
github.com/lestrrat-go/blackmagic v1.0.4 // indirect
|
||||
github.com/lestrrat-go/dsig v1.4.0 // indirect
|
||||
github.com/lestrrat-go/dsig-secp256k1 v1.0.0 // indirect
|
||||
github.com/lestrrat-go/httpcc v1.0.1 // indirect
|
||||
github.com/lestrrat-go/httprc v1.0.6 // indirect
|
||||
github.com/lestrrat-go/iter v1.0.2 // indirect
|
||||
github.com/lestrrat-go/option v1.0.1 // indirect
|
||||
github.com/lestrrat-go/httprc/v3 v3.0.6 // indirect
|
||||
github.com/lestrrat-go/option/v2 v2.0.0 // indirect
|
||||
github.com/mattn/go-colorable v0.1.14 // indirect
|
||||
github.com/mattn/go-isatty v0.0.20 // indirect
|
||||
github.com/ncruces/go-strftime v1.0.0 // indirect
|
||||
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect
|
||||
github.com/segmentio/asm v1.2.1 // indirect
|
||||
github.com/valyala/fastjson v1.6.10 // indirect
|
||||
golang.org/x/exp v0.0.0-20251113190631-e25ba8c21ef6 // indirect
|
||||
golang.org/x/sys v0.48.0 // indirect
|
||||
gopkg.in/alexcesaro/quotedprintable.v3 v3.0.0-20150716171945-2caba252f4dc // indirect
|
||||
|
||||
@@ -41,10 +41,8 @@ github.com/aws/aws-sdk-go-v2/service/sts v1.51.1/go.mod h1:26zA0GhDrLo+yiLI2yXWx
|
||||
github.com/aws/smithy-go v1.28.1 h1:R/nXH00c8qcfCzQVELtRw+eLQWtzv+VAIEFJ1/xxXlQ=
|
||||
github.com/aws/smithy-go v1.28.1/go.mod h1:YE2RhdIuDbA5E5bTdciG9KrW3+TiEONeUWCqxX9i1Fc=
|
||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/decred/dcrd/dcrec/secp256k1/v4 v4.4.0 h1:NMZiJj8QnKe1LgsbDayM4UoHwbvwDRwnI3hwNaAHRnc=
|
||||
github.com/decred/dcrd/dcrec/secp256k1/v4 v4.4.0/go.mod h1:ZXNYxsqcloTdSy/rNShjYzMhyjf0LaoftYK0p+A3h40=
|
||||
github.com/decred/dcrd/dcrec/secp256k1/v4 v4.4.1 h1:5RVFMOWjMyRy8cARdy79nAmgYw3hK/4HUq48LQ6Wwqo=
|
||||
github.com/decred/dcrd/dcrec/secp256k1/v4 v4.4.1/go.mod h1:ZXNYxsqcloTdSy/rNShjYzMhyjf0LaoftYK0p+A3h40=
|
||||
github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY=
|
||||
github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto=
|
||||
github.com/ebitengine/purego v0.10.1 h1:dewVBCBT2GaMu1SrNTYxQhgQBethzfhiwvZiLGP/qyY=
|
||||
@@ -63,8 +61,8 @@ github.com/go-chi/chi/v5 v5.2.3 h1:WQIt9uxdsAbgIYgid+BpYc+liqQZGMHRaUwp0JUcvdE=
|
||||
github.com/go-chi/chi/v5 v5.2.3/go.mod h1:L2yAIGWB3H+phAw1NxKwWM+7eUH/lU8pOMm5hHcoops=
|
||||
github.com/go-chi/cors v1.2.2 h1:Jmey33TE+b+rB7fT8MUy1u0I4L+NARQlK6LhzKPSyQE=
|
||||
github.com/go-chi/cors v1.2.2/go.mod h1:sSbTewc+6wYHBBCW7ytsFSn836hqM7JxpglAy2Vzc58=
|
||||
github.com/go-chi/jwtauth/v5 v5.3.3 h1:50Uzmacu35/ZP9ER2Ht6SazwPsnLQ9LRJy6zTZJpHEo=
|
||||
github.com/go-chi/jwtauth/v5 v5.3.3/go.mod h1:O4QvPRuZLZghl9WvfVaON+ARfGzpD2PBX/QY5vUz7aQ=
|
||||
github.com/go-chi/jwtauth/v5 v5.4.0 h1:Ieh0xMJsFvqylqJ02/mQHKzbbKO9DYNBh4DPKCwTwYI=
|
||||
github.com/go-chi/jwtauth/v5 v5.4.0/go.mod h1:w6yjqUUXz1b8+oiJel64Sz1KJwduQM6qUA5QNzO5+bQ=
|
||||
github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s=
|
||||
github.com/go-playground/assert/v2 v2.2.0/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4=
|
||||
github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA=
|
||||
@@ -75,8 +73,8 @@ github.com/go-playground/validator/v10 v10.28.0 h1:Q7ibns33JjyW48gHkuFT91qX48KG0
|
||||
github.com/go-playground/validator/v10 v10.28.0/go.mod h1:GoI6I1SjPBh9p7ykNE/yj3fFYbyDOpwMn5KXd+m2hUU=
|
||||
github.com/go-sql-driver/mysql v1.8.1 h1:LedoTUt/eveggdHS9qUFC1EFSa8bU2+1pZjSRpvNJ1Y=
|
||||
github.com/go-sql-driver/mysql v1.8.1/go.mod h1:wEBSXgmK//2ZFJyE+qWnIsVGmvmEKlqwuVSjsCm7DZg=
|
||||
github.com/goccy/go-json v0.10.5 h1:Fq85nIqj+gXn/S5ahsiTlK3TmC85qgirsdTP/+DeaC4=
|
||||
github.com/goccy/go-json v0.10.5/go.mod h1:oq7eo15ShAhp70Anwd5lgX2pLfOS3QCiwU/PULtXL6M=
|
||||
github.com/goccy/go-json v0.10.6 h1:p8HrPJzOakx/mn/bQtjgNjdTcN+/S6FcG2CTtQOrHVU=
|
||||
github.com/goccy/go-json v0.10.6/go.mod h1:oq7eo15ShAhp70Anwd5lgX2pLfOS3QCiwU/PULtXL6M=
|
||||
github.com/google/pprof v0.0.0-20250317173921-a4b03ec1a45e h1:ijClszYn+mADRFY17kjQEVQ1XRhq2/JR1M3sGqeJoxs=
|
||||
github.com/google/pprof v0.0.0-20250317173921-a4b03ec1a45e/go.mod h1:boTsfXsheKC2y+lKOCMpSfarhxDeIzfZG1jqGcPl3cA=
|
||||
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
|
||||
@@ -103,16 +101,18 @@ github.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ=
|
||||
github.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI=
|
||||
github.com/lestrrat-go/blackmagic v1.0.4 h1:IwQibdnf8l2KoO+qC3uT4OaTWsW7tuRQXy9TRN9QanA=
|
||||
github.com/lestrrat-go/blackmagic v1.0.4/go.mod h1:6AWFyKNNj0zEXQYfTMPfZrAXUWUfTIZ5ECEUEJaijtw=
|
||||
github.com/lestrrat-go/dsig v1.4.0 h1:g7LUjK8cT74A5DzBXJI5HzsJuLhoYN0Wzj4nuOMIrH8=
|
||||
github.com/lestrrat-go/dsig v1.4.0/go.mod h1:I8Nddg/vN2cUl/h8N7SRRApLnNNeyZPIqLYpvpOtGGo=
|
||||
github.com/lestrrat-go/dsig-secp256k1 v1.0.0 h1:JpDe4Aybfl0soBvoVwjqDbp+9S1Y2OM7gcrVVMFPOzY=
|
||||
github.com/lestrrat-go/dsig-secp256k1 v1.0.0/go.mod h1:CxUgAhssb8FToqbL8NjSPoGQlnO4w3LG1P0qPWQm/NU=
|
||||
github.com/lestrrat-go/httpcc v1.0.1 h1:ydWCStUeJLkpYyjLDHihupbn2tYmZ7m22BGkcvZZrIE=
|
||||
github.com/lestrrat-go/httpcc v1.0.1/go.mod h1:qiltp3Mt56+55GPVCbTdM9MlqhvzyuL6W/NMDA8vA5E=
|
||||
github.com/lestrrat-go/httprc v1.0.6 h1:qgmgIRhpvBqexMJjA/PmwSvhNk679oqD1RbovdCGW8k=
|
||||
github.com/lestrrat-go/httprc v1.0.6/go.mod h1:mwwz3JMTPBjHUkkDv/IGJ39aALInZLrhBp0X7KGUZlo=
|
||||
github.com/lestrrat-go/iter v1.0.2 h1:gMXo1q4c2pHmC3dn8LzRhJfP1ceCbgSiT9lUydIzltI=
|
||||
github.com/lestrrat-go/iter v1.0.2/go.mod h1:Momfcq3AnRlRjI5b5O8/G5/BvpzrhoFTZcn06fEOPt4=
|
||||
github.com/lestrrat-go/jwx/v2 v2.1.6 h1:hxM1gfDILk/l5ylers6BX/Eq1m/pnxe9NBwW6lVfecA=
|
||||
github.com/lestrrat-go/jwx/v2 v2.1.6/go.mod h1:Y722kU5r/8mV7fYDifjug0r8FK8mZdw0K0GpJw/l8pU=
|
||||
github.com/lestrrat-go/option v1.0.1 h1:oAzP2fvZGQKWkvHa1/SAcFolBEca1oN+mQ7eooNBEYU=
|
||||
github.com/lestrrat-go/option v1.0.1/go.mod h1:5ZHFbivi4xwXxhxY9XHDe2FHo6/Z7WWmtT7T5nBBp3I=
|
||||
github.com/lestrrat-go/httprc/v3 v3.0.6 h1:4FpLQ18KK/ypPbVU3NLWJNRvH3kcYiqKqWfKGqNWxxI=
|
||||
github.com/lestrrat-go/httprc/v3 v3.0.6/go.mod h1:mSMtkZW92Z98M5YoNNztbRGxbXHql7tSitCvaxvo9l0=
|
||||
github.com/lestrrat-go/jwx/v3 v3.3.0 h1:OXcYvQOQ7cxWzeZ/Q9sYk8ABe/kCSI371WmuACiCT+4=
|
||||
github.com/lestrrat-go/jwx/v3 v3.3.0/go.mod h1:eIJhDcKHBwcgxqv8RiIylV67TVl1wJp/265IAHY1Db8=
|
||||
github.com/lestrrat-go/option/v2 v2.0.0 h1:XxrcaJESE1fokHy3FpaQ/cXW8ZsIdWcdFzzLOcID3Ss=
|
||||
github.com/lestrrat-go/option/v2 v2.0.0/go.mod h1:oSySsmzMoR0iRzCDCaUfsCzxQHUEuhOViQObyy7S6Vg=
|
||||
github.com/mattn/go-colorable v0.1.14 h1:9A9LHSqF/7dyVVX6g0U9cwm9pG3kP9gSzcuIPHPsaIE=
|
||||
github.com/mattn/go-colorable v0.1.14/go.mod h1:6LmQG8QLFO4G5z1gPvYEzlUgJ2wF+stgPZH1UqBm1s8=
|
||||
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
|
||||
@@ -121,7 +121,6 @@ github.com/mattn/go-sqlite3 v1.14.22 h1:2gZY6PC6kBnID23Tichd1K+Z0oS6nE/XwU+Vz/5o
|
||||
github.com/mattn/go-sqlite3 v1.14.22/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y=
|
||||
github.com/ncruces/go-strftime v1.0.0 h1:HMFp8mLCTPp341M/ZnA4qaf7ZlsbTc+miZjCLOFAw7w=
|
||||
github.com/ncruces/go-strftime v1.0.0/go.mod h1:Fwc5htZGVVkseilnfgOVb9mKy6w1naJmn9CehxcKcls=
|
||||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE=
|
||||
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=
|
||||
@@ -129,11 +128,14 @@ github.com/segmentio/asm v1.2.1 h1:DTNbBqs57ioxAD4PrArqftgypG4/qNpXoJx8TVXxPR0=
|
||||
github.com/segmentio/asm v1.2.1/go.mod h1:BqMnlJP91P8d+4ibuonYZw9mfnzI9HfxselHZr5aAcs=
|
||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
|
||||
github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
|
||||
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
|
||||
github.com/stretchr/testify v1.12.1 h1:EuwCh5fleGS7H32xRwO3wRGT7DxrDhLAT6FF8MpWDWE=
|
||||
github.com/stretchr/testify v1.12.1/go.mod h1:MDEgiDPPsNp5cuIrHPPCyornHKgEVbtFUmoNlxoYthg=
|
||||
github.com/valyala/fastjson v1.6.10 h1:/yjJg8jaVQdYR3arGxPE2X5z89xrlhS0eGXdv+ADTh4=
|
||||
github.com/valyala/fastjson v1.6.10/go.mod h1:e6FubmQouUNP73jtMLmcbxS6ydWIpOfhz34TSfO3JaE=
|
||||
go.yaml.in/yaml/v3 v3.0.5 h1:N6y/pJk8buWs9NY5ERU2HSMfm+IuD/OtfdAnq6kESPw=
|
||||
go.yaml.in/yaml/v3 v3.0.5/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg=
|
||||
golang.org/x/crypto v0.57.0 h1:3ZVCjf8Ggz7zneR/EHRVx68Ctf+2pmIMP2UFhh9cC6M=
|
||||
golang.org/x/crypto v0.57.0/go.mod h1:Fdz0i5U6CoizGwLda9DttjSk6qlZo25zYNtR+ycvuZA=
|
||||
golang.org/x/exp v0.0.0-20251113190631-e25ba8c21ef6 h1:zfMcR1Cs4KNuomFFgGefv5N0czO2XZpUbxGUy8i8ug0=
|
||||
@@ -159,8 +161,6 @@ gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8
|
||||
gopkg.in/gomail.v2 v2.0.0-20160411212932-81ebce5c23df h1:n7WqCuqOuCbNr617RXOY0AWRXxgwEyPp2z+p0+hgMuE=
|
||||
gopkg.in/gomail.v2 v2.0.0-20160411212932-81ebce5c23df/go.mod h1:LRQQ+SO6ZHR7tOkpBDuZnXENFzX8qRjMDMyPD6BRkCw=
|
||||
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
gorm.io/driver/mysql v1.6.0 h1:eNbLmNTpPpTOVZi8MMxCi2aaIm0ZpInbORNXDwyLGvg=
|
||||
gorm.io/driver/mysql v1.6.0/go.mod h1:D/oCC2GWK3M/dqoLxnOlaNKmXz8WNTfcS9y5ovaSqKo=
|
||||
gorm.io/driver/postgres v1.6.3 h1:bAn6O2pUa8LtpWEvL5NFU4+52Tfx8Ut7IVaIacCLcI0=
|
||||
|
||||
@@ -1,7 +1,12 @@
|
||||
package article
|
||||
|
||||
import (
|
||||
"RenewCMS/internal/domain/author"
|
||||
"RenewCMS/internal/domain/slug"
|
||||
"errors"
|
||||
"net/url"
|
||||
"slices"
|
||||
"strconv"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
)
|
||||
@@ -10,13 +15,95 @@ var (
|
||||
ErrInvalidTitle = errors.New("article's title length should be between 3 and 200 caracters")
|
||||
ErrArticleNotFound = errors.New("article not found")
|
||||
ErrArticleOffline = errors.New("article is offline")
|
||||
|
||||
ErrInvalidSlug = errors.New("invalid slug")
|
||||
ErrSlugTaken = errors.New("another article on this site already uses that slug")
|
||||
ErrInvalidCanonicalURL = errors.New("invalid canonical url")
|
||||
)
|
||||
|
||||
type SlugTakenError struct {
|
||||
Suggestion string
|
||||
}
|
||||
|
||||
func (e *SlugTakenError) Error() string {
|
||||
return ErrSlugTaken.Error()
|
||||
}
|
||||
|
||||
func (e *SlugTakenError) Is(target error) bool {
|
||||
return target == ErrSlugTaken
|
||||
}
|
||||
|
||||
const (
|
||||
MinTitleRunes = 3
|
||||
MaxTitleRunes = 200
|
||||
|
||||
MaxCanonicalURLRunes = 2048
|
||||
|
||||
FallbackSlug = "article"
|
||||
DeletedSlug = "#deleted-"
|
||||
|
||||
DismissTitleLong = "title_long"
|
||||
DismissTitleEmpty = "title_empty"
|
||||
DismissDescShort = "desc_short"
|
||||
DismissDescLong = "desc_long"
|
||||
DismissCoverAlt = "cover_alt"
|
||||
DismissCoverNone = "cover_none"
|
||||
DismissSlugLong = "slug_long"
|
||||
DismissNoAuthor = "no_au"
|
||||
DismissNoHeading = "no_h"
|
||||
DismissBodyAlt = "body_alt"
|
||||
DismissShort = "short"
|
||||
)
|
||||
|
||||
var dismissCodes = []string{
|
||||
DismissTitleLong, DismissTitleEmpty, DismissDescShort, DismissDescLong, DismissCoverAlt, DismissCoverNone,
|
||||
DismissSlugLong, DismissNoAuthor, DismissNoHeading, DismissBodyAlt, DismissShort,
|
||||
}
|
||||
|
||||
func DismissCodes() []string {
|
||||
return slices.Clone(dismissCodes)
|
||||
}
|
||||
|
||||
func NormalizeDismissed(codes []string) []string {
|
||||
normalized := make([]string, 0, len(codes))
|
||||
for _, code := range codes {
|
||||
if !slices.Contains(normalized, code) {
|
||||
normalized = append(normalized, code)
|
||||
}
|
||||
}
|
||||
return normalized
|
||||
}
|
||||
|
||||
func IsValidSlug(candidate string) bool {
|
||||
return slug.IsValid(candidate)
|
||||
}
|
||||
|
||||
func Tombstone(id uint32) string {
|
||||
return DeletedSlug + strconv.FormatUint(uint64(id), 10)
|
||||
}
|
||||
|
||||
func GenerateSlug(title string) string {
|
||||
return slug.Generate(title, FallbackSlug)
|
||||
}
|
||||
|
||||
func SlugWithSuffix(base string, attempt int) string {
|
||||
return slug.WithSuffix(base, attempt)
|
||||
}
|
||||
|
||||
func ValidateCanonicalURL(raw string) error {
|
||||
if raw == "" {
|
||||
return nil
|
||||
}
|
||||
if utf8.RuneCountInString(raw) > MaxCanonicalURLRunes {
|
||||
return ErrInvalidCanonicalURL
|
||||
}
|
||||
parsed, err := url.Parse(raw)
|
||||
if err != nil || parsed.Scheme != "https" || parsed.Hostname() == "" {
|
||||
return ErrInvalidCanonicalURL
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func ValidateTitle(title string) error {
|
||||
runeCount := utf8.RuneCountInString(title)
|
||||
if runeCount < MinTitleRunes || runeCount > MaxTitleRunes {
|
||||
@@ -26,10 +113,28 @@ func ValidateTitle(title string) error {
|
||||
}
|
||||
|
||||
type Article struct {
|
||||
ID uint32 `json:"id"`
|
||||
Title string `json:"title"`
|
||||
Body string `json:"body"`
|
||||
IsOnline bool `json:"is_online"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
ID uint32 `json:"id"`
|
||||
Title string `json:"title"`
|
||||
Body string `json:"body"`
|
||||
IsOnline bool `json:"is_online"`
|
||||
SiteID uint32 `json:"site_id"`
|
||||
Authors []author.Byline `json:"authors"`
|
||||
Slug string `json:"slug"`
|
||||
Excerpt string `json:"excerpt"`
|
||||
SEOTitle string `json:"seo_title"`
|
||||
SEODescription string `json:"seo_description"`
|
||||
CoverImageID *uint32 `json:"cover_image_id"`
|
||||
CoverImageAlt string `json:"cover_image_alt"`
|
||||
SocialTitle string `json:"social_title"`
|
||||
SocialDescription string `json:"social_description"`
|
||||
SocialImageID *uint32 `json:"social_image_id"`
|
||||
CanonicalURL string `json:"canonical_url"`
|
||||
Noindex bool `json:"noindex"`
|
||||
SEODismissed []string `json:"seo_dismissed"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
func (a Article) UsesImage(imageID uint32) bool {
|
||||
return a.CoverImageID != nil && *a.CoverImageID == imageID || a.SocialImageID != nil && *a.SocialImageID == imageID
|
||||
}
|
||||
@@ -14,6 +14,7 @@ const (
|
||||
SortByStatus SortField = "status"
|
||||
SortByCreatedAt SortField = "created_at"
|
||||
SortByUpdatedAt SortField = "updated_at"
|
||||
SortByID SortField = "id"
|
||||
|
||||
SortAsc SortDirection = "asc"
|
||||
SortDesc SortDirection = "desc"
|
||||
@@ -30,17 +31,53 @@ func DefaultSort() Sort {
|
||||
|
||||
type Filters struct {
|
||||
IsOnline *bool
|
||||
SiteID *uint32
|
||||
Page int
|
||||
Size int
|
||||
Q string
|
||||
Status string
|
||||
Sort Sort
|
||||
Unpaged bool
|
||||
}
|
||||
|
||||
type Nullable[T any] struct {
|
||||
Set bool
|
||||
Value *T
|
||||
}
|
||||
|
||||
type Update struct {
|
||||
Body *string
|
||||
SiteID *uint32
|
||||
AuthorIDs *[]uint32
|
||||
Slug *string
|
||||
Excerpt *string
|
||||
SEOTitle *string
|
||||
SEODescription *string
|
||||
CoverImageID Nullable[uint32]
|
||||
CoverImageAlt *string
|
||||
SocialTitle *string
|
||||
SocialDescription *string
|
||||
SocialImageID Nullable[uint32]
|
||||
CanonicalURL *string
|
||||
Noindex *bool
|
||||
SEODismissed *[]string
|
||||
}
|
||||
|
||||
type ImageReferences struct {
|
||||
Cover []uint32
|
||||
Social []uint32
|
||||
}
|
||||
|
||||
func (r ImageReferences) Empty() bool {
|
||||
return len(r.Cover) == 0 && len(r.Social) == 0
|
||||
}
|
||||
|
||||
type Counts struct {
|
||||
All int `json:"all"`
|
||||
Online int `json:"online"`
|
||||
Draft int `json:"draft"`
|
||||
|
||||
Suggestions int `json:"suggestions"`
|
||||
}
|
||||
|
||||
type PageResult struct {
|
||||
@@ -57,7 +94,13 @@ type Repository interface {
|
||||
GetAll() []Article
|
||||
Create(post Article) (Article, error)
|
||||
UpdateBody(id uint32, body string) (Article, error)
|
||||
Update(id uint32, update Update) (Article, error)
|
||||
UpdateIsOnline(id uint32, isOnline bool) (Article, error)
|
||||
Delete(id uint32) error
|
||||
FindByBodyContaining(filename string) ([]Article, error)
|
||||
FindByImage(imageID uint32) ([]Article, error)
|
||||
SlugTaken(siteID uint32, slug string, exceptID uint32) (bool, error)
|
||||
ClearImage(imageID uint32) (ImageReferences, error)
|
||||
RestoreImage(references ImageReferences, imageID uint32) error
|
||||
RepointImage(fromImageIDs []uint32, toImageID uint32) ([]uint32, error)
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
package article
|
||||
|
||||
const (
|
||||
SEOSourceSEOTitle = "seo_title"
|
||||
SEOSourceTitle = "title"
|
||||
SEOSourceSEODescription = "seo_description"
|
||||
SEOSourceExcerpt = "excerpt"
|
||||
SEOSourceBody = "body"
|
||||
SEOSourceSite = "site"
|
||||
SEOSourceNone = "none"
|
||||
SEOSourceSocial = "social"
|
||||
SEOSourceCover = "cover"
|
||||
SEOSourceCanonicalURL = "canonical_url"
|
||||
)
|
||||
|
||||
type SEOOpenGraph struct {
|
||||
Type string `json:"type"`
|
||||
Title string `json:"title"`
|
||||
Description string `json:"description"`
|
||||
Image string `json:"image"`
|
||||
ImageAlt string `json:"image_alt"`
|
||||
URL string `json:"url"`
|
||||
SiteName string `json:"site_name"`
|
||||
Locale string `json:"locale"`
|
||||
}
|
||||
|
||||
type SEOTwitter struct {
|
||||
Card string `json:"card"`
|
||||
Title string `json:"title"`
|
||||
Description string `json:"description"`
|
||||
Image string `json:"image"`
|
||||
ImageAlt string `json:"image_alt"`
|
||||
}
|
||||
|
||||
type SEOImage struct {
|
||||
URL string `json:"url"`
|
||||
Alt string `json:"alt"`
|
||||
Source string `json:"source"`
|
||||
}
|
||||
|
||||
type SEOAuthor struct {
|
||||
Name string `json:"name"`
|
||||
URL string `json:"url"`
|
||||
SameAs []string `json:"same_as"`
|
||||
}
|
||||
|
||||
type SEOFallbacks struct {
|
||||
Title string `json:"title"`
|
||||
Description string `json:"description"`
|
||||
Image string `json:"image"`
|
||||
Canonical string `json:"canonical"`
|
||||
}
|
||||
|
||||
type SEOJSONLDPerson struct {
|
||||
Type string `json:"@type"`
|
||||
Name string `json:"name"`
|
||||
URL string `json:"url"`
|
||||
SameAs []string `json:"sameAs"`
|
||||
}
|
||||
|
||||
type SEOJSONLDPage struct {
|
||||
Type string `json:"@type"`
|
||||
ID string `json:"@id"`
|
||||
}
|
||||
|
||||
type SEOJSONLD struct {
|
||||
Context string `json:"@context"`
|
||||
Type string `json:"@type"`
|
||||
Headline string `json:"headline"`
|
||||
Description string `json:"description,omitempty"`
|
||||
Image []string `json:"image,omitempty"`
|
||||
Author []SEOJSONLDPerson `json:"author,omitempty"`
|
||||
DatePublished string `json:"datePublished,omitempty"`
|
||||
DateModified string `json:"dateModified"`
|
||||
MainEntityOfPage SEOJSONLDPage `json:"mainEntityOfPage"`
|
||||
}
|
||||
|
||||
type ResolvedSEO struct {
|
||||
Title string `json:"title"`
|
||||
Description string `json:"description"`
|
||||
CanonicalURL string `json:"canonical_url"`
|
||||
Robots string `json:"robots"`
|
||||
OG SEOOpenGraph `json:"og"`
|
||||
Twitter SEOTwitter `json:"twitter"`
|
||||
Image SEOImage `json:"image"`
|
||||
Authors []SEOAuthor `json:"authors"`
|
||||
PublishedAt *string `json:"published_at"`
|
||||
ModifiedAt string `json:"modified_at"`
|
||||
Fallbacks SEOFallbacks `json:"fallbacks"`
|
||||
JSONLD SEOJSONLD `json:"json_ld"`
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
package article
|
||||
|
||||
const (
|
||||
SEOStatusReady = "ready"
|
||||
SEOStatusSuggestions = "suggestions"
|
||||
SEOStatusHidden = "hidden"
|
||||
|
||||
SEOTitleMaxRunes = 60
|
||||
SEODescriptionMinRunes = 70
|
||||
SEODescriptionMaxRunes = 160
|
||||
SEOSlugMaxRunes = 75
|
||||
SEOHeadingMinTextRunes = 1000
|
||||
SEOShortBodyRunes = 300
|
||||
|
||||
SEOFieldTitle = "seo_title"
|
||||
SEOFieldDescription = "seo_description"
|
||||
SEOFieldCoverAlt = "cover_image_alt"
|
||||
SEOFieldCoverID = "cover_image_id"
|
||||
SEOFieldSlug = "slug"
|
||||
SEOFieldAuthors = "author_ids"
|
||||
SEOFieldBody = "body"
|
||||
)
|
||||
|
||||
type SEOSuggestion struct {
|
||||
Code string `json:"code"`
|
||||
Field string `json:"field"`
|
||||
Params map[string]int `json:"params"`
|
||||
}
|
||||
|
||||
type SEOAssessment struct {
|
||||
Status string `json:"status"`
|
||||
Suggestions []SEOSuggestion `json:"suggestions"`
|
||||
}
|
||||
|
||||
type SEOSummary struct {
|
||||
Status string
|
||||
Suggestions int
|
||||
}
|
||||
|
||||
func (a SEOAssessment) Summary() SEOSummary {
|
||||
return SEOSummary{Status: a.Status, Suggestions: len(a.Suggestions)}
|
||||
}
|
||||
|
||||
type SEOSlugCheck struct {
|
||||
Available bool `json:"available"`
|
||||
Suggestion *string `json:"suggestion"`
|
||||
}
|
||||
|
||||
type SEOCheck struct {
|
||||
Status string `json:"status"`
|
||||
Suggestions []SEOSuggestion `json:"suggestions"`
|
||||
Slug SEOSlugCheck `json:"slug"`
|
||||
}
|
||||
@@ -12,8 +12,33 @@ func TextChange(field string, before string, after string) Change {
|
||||
}
|
||||
|
||||
func BodyChange(before string, after string) Change {
|
||||
return SizeChange(FieldBody, before, after)
|
||||
}
|
||||
|
||||
func SizeChange(field string, before string, after string) Change {
|
||||
delta := utf8.RuneCountInString(after) - utf8.RuneCountInString(before)
|
||||
return Change{Field: FieldBody, Kind: ChangeBody, Delta: &delta}
|
||||
return Change{Field: field, Kind: ChangeBody, Delta: &delta}
|
||||
}
|
||||
|
||||
func appendSizeChange(changes []Change, field string, before string, after string) []Change {
|
||||
if before == after {
|
||||
return changes
|
||||
}
|
||||
return append(changes, SizeChange(field, before, after))
|
||||
}
|
||||
|
||||
func SEOChanges(before article.Article, after article.Article) []Change {
|
||||
changes := []Change{}
|
||||
changes = AppendTextChange(changes, FieldSlug, before.Slug, after.Slug)
|
||||
changes = AppendTextChange(changes, FieldCanonicalURL, before.CanonicalURL, after.CanonicalURL)
|
||||
changes = AppendTextChange(changes, FieldNoindex, strconv.FormatBool(before.Noindex), strconv.FormatBool(after.Noindex))
|
||||
changes = appendSizeChange(changes, FieldExcerpt, before.Excerpt, after.Excerpt)
|
||||
changes = appendSizeChange(changes, FieldSEOTitle, before.SEOTitle, after.SEOTitle)
|
||||
changes = appendSizeChange(changes, FieldSEODescription, before.SEODescription, after.SEODescription)
|
||||
changes = appendSizeChange(changes, FieldCoverImageAlt, before.CoverImageAlt, after.CoverImageAlt)
|
||||
changes = appendSizeChange(changes, FieldSocialTitle, before.SocialTitle, after.SocialTitle)
|
||||
changes = appendSizeChange(changes, FieldSocialDescription, before.SocialDescription, after.SocialDescription)
|
||||
return changes
|
||||
}
|
||||
|
||||
func ArticleChanges(before article.Article, after article.Article) []Change {
|
||||
@@ -32,15 +57,15 @@ func ArticleChanges(before article.Article, after article.Article) []Change {
|
||||
|
||||
func VariantChanges(before image.VariantSettings, after image.VariantSettings) []Change {
|
||||
changes := []Change{}
|
||||
changes = appendChange(changes, FieldWidth, image.DimensionText(before.Width), image.DimensionText(after.Width))
|
||||
changes = appendChange(changes, FieldHeight, image.DimensionText(before.Height), image.DimensionText(after.Height))
|
||||
changes = appendChange(changes, FieldFit, string(before.Fit), string(after.Fit))
|
||||
changes = appendChange(changes, FieldFormat, string(before.Format), string(after.Format))
|
||||
changes = appendChange(changes, FieldQuality, image.QualityText(before.Quality), image.QualityText(after.Quality))
|
||||
changes = AppendTextChange(changes, FieldWidth, image.DimensionText(before.Width), image.DimensionText(after.Width))
|
||||
changes = AppendTextChange(changes, FieldHeight, image.DimensionText(before.Height), image.DimensionText(after.Height))
|
||||
changes = AppendTextChange(changes, FieldFit, string(before.Fit), string(after.Fit))
|
||||
changes = AppendTextChange(changes, FieldFormat, string(before.Format), string(after.Format))
|
||||
changes = AppendTextChange(changes, FieldQuality, image.QualityText(before.Quality), image.QualityText(after.Quality))
|
||||
return changes
|
||||
}
|
||||
|
||||
func appendChange(changes []Change, field string, before string, after string) []Change {
|
||||
func AppendTextChange(changes []Change, field string, before string, after string) []Change {
|
||||
if before == after {
|
||||
return changes
|
||||
}
|
||||
|
||||
@@ -32,6 +32,8 @@ const (
|
||||
CategoryAPIKeys Category = "api_keys"
|
||||
CategoryAuth Category = "auth"
|
||||
CategorySystem Category = "system"
|
||||
CategorySites Category = "sites"
|
||||
CategoryAuthors Category = "authors"
|
||||
)
|
||||
|
||||
type Outcome string
|
||||
@@ -71,6 +73,13 @@ const (
|
||||
ActionArticlePublish = "article.publish"
|
||||
ActionArticleUnpublish = "article.unpublish"
|
||||
ActionArticleDelete = "article.delete"
|
||||
ActionSiteCreate = "site.create"
|
||||
ActionSiteEdit = "site.edit"
|
||||
ActionSiteSetDefault = "site.set_default"
|
||||
ActionSiteDelete = "site.delete"
|
||||
ActionAuthorCreate = "author.create"
|
||||
ActionAuthorEdit = "author.edit"
|
||||
ActionAuthorDelete = "author.delete"
|
||||
ActionMediaUpload = "media.upload"
|
||||
ActionMediaRename = "media.rename"
|
||||
ActionMediaDelete = "media.delete"
|
||||
@@ -107,48 +116,76 @@ const (
|
||||
TargetVariant = "image_variant"
|
||||
TargetInvite = "invite"
|
||||
TargetRelease = "release"
|
||||
TargetSite = "site"
|
||||
TargetAuthor = "author"
|
||||
)
|
||||
|
||||
const (
|
||||
SystemActorName = "System"
|
||||
ReasonWrongLogin = "Wrong username or password."
|
||||
MaxUserAgentLength = 255
|
||||
ParamRemoved = "removed"
|
||||
ParamFrom = "from"
|
||||
ParamTo = "to"
|
||||
ParamMaxGBFrom = "max_gb_from"
|
||||
ParamMaxGBTo = "max_gb_to"
|
||||
ParamMerged = "merged"
|
||||
ParamArticlesUpdated = "articles_updated"
|
||||
ParamFailedGroups = "failed_groups"
|
||||
ParamUpdateAvailable = "update_available"
|
||||
ParamKind = "kind"
|
||||
ParamPurgedFiles = "purged_files"
|
||||
ParamPurgedBytes = "purged_bytes"
|
||||
ParamFailedFiles = "failed_files"
|
||||
ParamOlderThanDays = "older_than_days"
|
||||
ParamGenerated = "generated"
|
||||
ParamFailed = "failed"
|
||||
ParamCauses = "causes"
|
||||
ParamWidth = "width"
|
||||
ParamHeight = "height"
|
||||
ParamFit = "fit"
|
||||
ParamFormat = "format"
|
||||
ParamQuality = "quality"
|
||||
ParamTag = "tag"
|
||||
FieldTitle = "title"
|
||||
FieldOnline = "online"
|
||||
FieldBody = "body"
|
||||
FieldFilename = "filename"
|
||||
FieldDisplayName = "display_name"
|
||||
FieldWidth = "width"
|
||||
FieldHeight = "height"
|
||||
FieldFit = "fit"
|
||||
FieldFormat = "format"
|
||||
FieldQuality = "quality"
|
||||
maxNameLength = 255
|
||||
maxActionLength = 64
|
||||
maxFailureReasonSize = 255
|
||||
SystemActorName = "System"
|
||||
ReasonWrongLogin = "Wrong username or password."
|
||||
MaxUserAgentLength = 255
|
||||
ParamRemoved = "removed"
|
||||
ParamFrom = "from"
|
||||
ParamTo = "to"
|
||||
ParamMaxGBFrom = "max_gb_from"
|
||||
ParamMaxGBTo = "max_gb_to"
|
||||
ParamMerged = "merged"
|
||||
ParamArticlesUpdated = "articles_updated"
|
||||
ParamFailedGroups = "failed_groups"
|
||||
ParamUpdateAvailable = "update_available"
|
||||
ParamKind = "kind"
|
||||
ParamPurgedFiles = "purged_files"
|
||||
ParamPurgedBytes = "purged_bytes"
|
||||
ParamFailedFiles = "failed_files"
|
||||
ParamOlderThanDays = "older_than_days"
|
||||
ParamGenerated = "generated"
|
||||
ParamFailed = "failed"
|
||||
ParamCauses = "causes"
|
||||
ParamWidth = "width"
|
||||
ParamHeight = "height"
|
||||
ParamFit = "fit"
|
||||
ParamFormat = "format"
|
||||
ParamQuality = "quality"
|
||||
ParamTag = "tag"
|
||||
FieldTitle = "title"
|
||||
FieldOnline = "online"
|
||||
FieldBody = "body"
|
||||
FieldFilename = "filename"
|
||||
FieldDisplayName = "display_name"
|
||||
FieldWidth = "width"
|
||||
FieldHeight = "height"
|
||||
FieldFit = "fit"
|
||||
FieldFormat = "format"
|
||||
FieldQuality = "quality"
|
||||
FieldName = "name"
|
||||
FieldBaseURL = "base_url"
|
||||
FieldDefaultRobots = "default_robots"
|
||||
FieldLocale = "locale"
|
||||
FieldSocialImage = "default_social_image"
|
||||
FieldSite = "site"
|
||||
FieldSlug = "slug"
|
||||
FieldBio = "bio"
|
||||
FieldWebsite = "website"
|
||||
FieldSocialLinks = "social_links"
|
||||
FieldAvatar = "avatar"
|
||||
FieldUser = "user"
|
||||
FieldAuthors = "authors"
|
||||
FieldCanonicalURL = "canonical_url"
|
||||
FieldNoindex = "noindex"
|
||||
FieldCoverImage = "cover_image"
|
||||
FieldArticleSocialImage = "social_image"
|
||||
FieldExcerpt = "excerpt"
|
||||
FieldSEOTitle = "seo_title"
|
||||
FieldSEODescription = "seo_description"
|
||||
FieldSocialTitle = "social_title"
|
||||
FieldSocialDescription = "social_description"
|
||||
FieldCoverImageAlt = "cover_image_alt"
|
||||
FieldSiteName = "site_name"
|
||||
FieldTitleTemplate = "title_template"
|
||||
FieldDefaultDescription = "default_description"
|
||||
maxNameLength = 255
|
||||
maxActionLength = 64
|
||||
maxFailureReasonSize = 255
|
||||
)
|
||||
|
||||
func ActorTypes() []ActorType {
|
||||
@@ -156,7 +193,7 @@ func ActorTypes() []ActorType {
|
||||
}
|
||||
|
||||
func Categories() []Category {
|
||||
return []Category{CategoryArticles, CategoryMedia, CategoryUsers, CategoryAPIKeys, CategoryAuth, CategorySystem}
|
||||
return []Category{CategoryArticles, CategoryMedia, CategoryUsers, CategoryAPIKeys, CategoryAuth, CategorySystem, CategorySites, CategoryAuthors}
|
||||
}
|
||||
|
||||
func Outcomes() []Outcome {
|
||||
|
||||
@@ -0,0 +1,180 @@
|
||||
package author
|
||||
|
||||
import (
|
||||
"RenewCMS/internal/domain/slug"
|
||||
"errors"
|
||||
"net/url"
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrAuthorNotFound = errors.New("author not found")
|
||||
ErrSlugTaken = errors.New("an author with that slug already exists")
|
||||
ErrAuthorHasArticles = errors.New("the author is still credited on articles")
|
||||
ErrUserAlreadyLinked = errors.New("the user already has an author")
|
||||
ErrAuthorAlreadyLinked = errors.New("the author is already linked to a user")
|
||||
ErrAuthorRights = errors.New("only an owner or admin can change this author")
|
||||
ErrBioTooLong = errors.New("the bio is too long")
|
||||
ErrInvalidURL = errors.New("invalid url")
|
||||
ErrTooManyLinks = errors.New("too many social links")
|
||||
ErrInvalidSlug = errors.New("invalid slug")
|
||||
ErrInvalidReassign = errors.New("invalid reassign destination")
|
||||
ErrInvalidSocialType = errors.New("invalid social link type")
|
||||
)
|
||||
|
||||
const (
|
||||
MinNameRunes = 1
|
||||
MaxNameRunes = 100
|
||||
MaxSlugRunes = 100
|
||||
MaxBioRunes = 280
|
||||
MaxURLLength = 2048
|
||||
MaxLinks = 5
|
||||
|
||||
FallbackSlug = "author"
|
||||
|
||||
SocialX = "x"
|
||||
SocialLinkedIn = "linkedin"
|
||||
SocialGitHub = "github"
|
||||
SocialMastodon = "mastodon"
|
||||
SocialCustom = "custom"
|
||||
)
|
||||
|
||||
type SocialLink struct {
|
||||
Type string `json:"type"`
|
||||
URL string `json:"url"`
|
||||
}
|
||||
|
||||
type Author struct {
|
||||
ID uint32 `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Slug string `json:"slug"`
|
||||
Bio string `json:"bio"`
|
||||
AvatarID *uint32 `json:"avatar_id"`
|
||||
Website *string `json:"website"`
|
||||
SocialLinks []SocialLink `json:"social_links"`
|
||||
UserID *uint32 `json:"user_id"`
|
||||
IsLinked bool `json:"is_linked"`
|
||||
ArticleCount int `json:"article_count"`
|
||||
UserEmail *string `json:"user_email,omitempty"`
|
||||
}
|
||||
|
||||
type Byline struct {
|
||||
ID uint32 `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Slug string `json:"slug"`
|
||||
Bio string `json:"bio"`
|
||||
AvatarID *uint32 `json:"avatar_id"`
|
||||
Website *string `json:"website"`
|
||||
SocialLinks []SocialLink `json:"social_links"`
|
||||
}
|
||||
|
||||
func (a Author) Byline() Byline {
|
||||
links := a.SocialLinks
|
||||
if links == nil {
|
||||
links = []SocialLink{}
|
||||
}
|
||||
return Byline{ID: a.ID, Name: a.Name, Slug: a.Slug, Bio: a.Bio, AvatarID: a.AvatarID, Website: a.Website, SocialLinks: links}
|
||||
}
|
||||
|
||||
func BylineIDs(bylines []Byline) []uint32 {
|
||||
ids := make([]uint32, 0, len(bylines))
|
||||
for _, byline := range bylines {
|
||||
ids = append(ids, byline.ID)
|
||||
}
|
||||
return ids
|
||||
}
|
||||
|
||||
type Nullable[T any] struct {
|
||||
Set bool
|
||||
Value *T
|
||||
}
|
||||
|
||||
type Patch struct {
|
||||
Name *string
|
||||
Slug *string
|
||||
Bio *string
|
||||
AvatarID Nullable[uint32]
|
||||
Website Nullable[string]
|
||||
SocialLinks *[]SocialLink
|
||||
UserID Nullable[uint32]
|
||||
}
|
||||
|
||||
type ListQuery struct {
|
||||
Q string
|
||||
Page int
|
||||
Size int
|
||||
}
|
||||
|
||||
type Page struct {
|
||||
Items []Author
|
||||
Total int
|
||||
}
|
||||
|
||||
func IsValidSlug(candidate string) bool {
|
||||
return slug.IsValid(candidate)
|
||||
}
|
||||
|
||||
func IsValidName(name string) bool {
|
||||
length := utf8.RuneCountInString(strings.TrimSpace(name))
|
||||
return length >= MinNameRunes && length <= MaxNameRunes
|
||||
}
|
||||
|
||||
func ValidateBio(bio string) error {
|
||||
if utf8.RuneCountInString(bio) > MaxBioRunes {
|
||||
return ErrBioTooLong
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func ValidateURL(raw string) error {
|
||||
if raw == "" || len(raw) > MaxURLLength {
|
||||
return ErrInvalidURL
|
||||
}
|
||||
parsed, err := url.Parse(raw)
|
||||
if err != nil || parsed.Scheme != "https" || parsed.Hostname() == "" {
|
||||
return ErrInvalidURL
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func NormalizeWebsite(website *string) (*string, error) {
|
||||
if website == nil || *website == "" {
|
||||
return nil, nil
|
||||
}
|
||||
if err := ValidateURL(*website); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return website, nil
|
||||
}
|
||||
|
||||
func IsValidSocialType(linkType string) bool {
|
||||
switch linkType {
|
||||
case SocialX, SocialLinkedIn, SocialGitHub, SocialMastodon, SocialCustom:
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func ValidateLinks(links []SocialLink) error {
|
||||
if len(links) > MaxLinks {
|
||||
return ErrTooManyLinks
|
||||
}
|
||||
for _, link := range links {
|
||||
if !IsValidSocialType(link.Type) {
|
||||
return ErrInvalidSocialType
|
||||
}
|
||||
if err := ValidateURL(link.URL); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func GenerateSlug(name string) string {
|
||||
return slug.Generate(name, FallbackSlug)
|
||||
}
|
||||
|
||||
func SlugWithSuffix(base string, attempt int) string {
|
||||
return slug.WithSuffix(base, attempt)
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
package author
|
||||
|
||||
type Repository interface {
|
||||
List(query ListQuery) (Page, error)
|
||||
Get(id uint32) (Author, error)
|
||||
GetBySlug(slug string) (Author, error)
|
||||
GetByUserID(userID uint32) (Author, error)
|
||||
Create(author Author) (Author, error)
|
||||
Update(author Author) (Author, error)
|
||||
DeleteMovingCredits(id uint32, reassignTo *uint32) error
|
||||
DeleteUncrediting(id uint32) error
|
||||
AvatarUsage() (map[uint32]int, error)
|
||||
FindByAvatar(imageID uint32) ([]Author, error)
|
||||
ClearAvatar(imageID uint32) ([]uint32, error)
|
||||
AssignAvatar(authorIDs []uint32, imageID uint32) error
|
||||
RepointAvatar(fromImageIDs []uint32, toImageID uint32) (int, error)
|
||||
}
|
||||
@@ -52,5 +52,7 @@ type RunResult struct {
|
||||
GroupsPurged int
|
||||
Merged int
|
||||
ArticlesUpdated int
|
||||
SitesUpdated int
|
||||
AuthorsUpdated int
|
||||
FailedGroups int
|
||||
}
|
||||
@@ -0,0 +1,167 @@
|
||||
package site
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/url"
|
||||
"regexp"
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrSiteNotFound = errors.New("site not found")
|
||||
ErrSiteKeyTaken = errors.New("a site with that key already exists")
|
||||
ErrSiteHasArticles = errors.New("the site still has articles")
|
||||
ErrDefaultSite = errors.New("the default site cannot be deleted")
|
||||
ErrKeyImmutable = errors.New("the key of a site cannot be changed")
|
||||
ErrInvalidSiteURL = errors.New("invalid site url")
|
||||
ErrInvalidLocale = errors.New("invalid locale")
|
||||
ErrUseSetDefault = errors.New("the default flag is changed through the default route")
|
||||
ErrInvalidReassign = errors.New("invalid reassign destination")
|
||||
|
||||
ErrInvalidTitleTemplate = errors.New("the title template must contain %title%")
|
||||
)
|
||||
|
||||
const (
|
||||
RobotsIndex = "index"
|
||||
RobotsNoIndex = "noindex"
|
||||
|
||||
DefaultName = "Default"
|
||||
DefaultKey = "default"
|
||||
|
||||
MinNameRunes = 1
|
||||
MaxNameRunes = 100
|
||||
|
||||
MaxLocaleRunes = 35
|
||||
MaxBaseURLRunes = 255
|
||||
|
||||
MinKeyRunes = 2
|
||||
MaxKeyRunes = 32
|
||||
|
||||
TitlePlaceholder = "%title%"
|
||||
DefaultTitleTemplate = "%title% | %site%"
|
||||
)
|
||||
|
||||
var keyPattern = regexp.MustCompile(`^[a-z0-9]+(-[a-z0-9]+)*$`)
|
||||
var localePattern = regexp.MustCompile(`^[a-z]{2,3}(-[A-Za-z0-9]{2,8})*$`)
|
||||
|
||||
var loopbackHosts = []string{"localhost", "127.0.0.1", "::1"}
|
||||
|
||||
type Site struct {
|
||||
ID uint32 `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Key string `json:"key"`
|
||||
BaseURL string `json:"base_url"`
|
||||
DefaultSocialImageID *uint32 `json:"default_social_image_id"`
|
||||
DefaultRobots string `json:"default_robots"`
|
||||
Locale *string `json:"locale"`
|
||||
IsDefault bool `json:"is_default"`
|
||||
ArticleCount int `json:"article_count"`
|
||||
SiteName string `json:"site_name"`
|
||||
TitleTemplate string `json:"title_template"`
|
||||
DefaultDescription string `json:"default_description"`
|
||||
}
|
||||
|
||||
type Nullable[T any] struct {
|
||||
Set bool
|
||||
Value *T
|
||||
}
|
||||
|
||||
type Patch struct {
|
||||
Name *string
|
||||
Key *string
|
||||
BaseURL *string
|
||||
DefaultRobots *string
|
||||
Locale Nullable[string]
|
||||
DefaultSocialImageID Nullable[uint32]
|
||||
IsDefault *bool
|
||||
SiteName *string
|
||||
TitleTemplate *string
|
||||
DefaultDescription *string
|
||||
}
|
||||
|
||||
func IsValidKey(key string) bool {
|
||||
length := utf8.RuneCountInString(key)
|
||||
return length >= MinKeyRunes && length <= MaxKeyRunes && keyPattern.MatchString(key)
|
||||
}
|
||||
|
||||
func IsValidName(name string) bool {
|
||||
length := utf8.RuneCountInString(name)
|
||||
return length >= MinNameRunes && length <= MaxNameRunes
|
||||
}
|
||||
|
||||
func ValidateTitleTemplate(template string) error {
|
||||
if !strings.Contains(template, TitlePlaceholder) {
|
||||
return ErrInvalidTitleTemplate
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func NormalizeLocale(locale *string) (*string, error) {
|
||||
if locale == nil || *locale == "" {
|
||||
return nil, nil
|
||||
}
|
||||
if utf8.RuneCountInString(*locale) > MaxLocaleRunes || !localePattern.MatchString(*locale) {
|
||||
return nil, ErrInvalidLocale
|
||||
}
|
||||
return locale, nil
|
||||
}
|
||||
|
||||
func isLoopback(hostname string) bool {
|
||||
for _, loopback := range loopbackHosts {
|
||||
if hostname == loopback {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
type origin struct {
|
||||
scheme string
|
||||
host string
|
||||
hostname string
|
||||
parsed *url.URL
|
||||
}
|
||||
|
||||
func parseOrigin(raw string) (origin, error) {
|
||||
parsed, err := url.Parse(strings.TrimSpace(raw))
|
||||
if err != nil || parsed.Host == "" || parsed.Hostname() == "" {
|
||||
return origin{}, ErrInvalidSiteURL
|
||||
}
|
||||
scheme := strings.ToLower(parsed.Scheme)
|
||||
if scheme != "http" && scheme != "https" {
|
||||
return origin{}, ErrInvalidSiteURL
|
||||
}
|
||||
return origin{scheme: scheme, host: strings.ToLower(parsed.Host), hostname: strings.ToLower(parsed.Hostname()), parsed: parsed}, nil
|
||||
}
|
||||
|
||||
func NormalizeBaseURL(raw string) (string, error) {
|
||||
found, err := parseOrigin(raw)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
parsed := found.parsed
|
||||
if parsed.User != nil || parsed.RawQuery != "" || parsed.ForceQuery || parsed.Fragment != "" || (parsed.Path != "" && parsed.Path != "/") {
|
||||
return "", ErrInvalidSiteURL
|
||||
}
|
||||
if found.scheme == "http" && !isLoopback(found.hostname) {
|
||||
return "", ErrInvalidSiteURL
|
||||
}
|
||||
normalized := found.scheme + "://" + found.host
|
||||
if utf8.RuneCountInString(normalized) > MaxBaseURLRunes {
|
||||
return "", ErrInvalidSiteURL
|
||||
}
|
||||
return normalized, nil
|
||||
}
|
||||
|
||||
func SeedBaseURL(publicURL string) (string, error) {
|
||||
found, err := parseOrigin(publicURL)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
scheme := found.scheme
|
||||
if scheme == "http" && !isLoopback(found.hostname) {
|
||||
scheme = "https"
|
||||
}
|
||||
return scheme + "://" + found.host, nil
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package site
|
||||
|
||||
type ListQuery struct {
|
||||
Q string
|
||||
Page int
|
||||
Size int
|
||||
}
|
||||
|
||||
type Page struct {
|
||||
Items []Site
|
||||
Total int
|
||||
}
|
||||
|
||||
type Repository interface {
|
||||
List() ([]Site, error)
|
||||
Find(query ListQuery) (Page, error)
|
||||
Get(id uint32) (Site, error)
|
||||
GetByKey(key string) (Site, error)
|
||||
GetDefault() (Site, error)
|
||||
Create(site Site) (Site, error)
|
||||
Update(site Site) (Site, error)
|
||||
SetDefault(id uint32) (Site, error)
|
||||
DeleteMovingArticles(id uint32, reassignTo *uint32) error
|
||||
ClearImage(imageID uint32) ([]uint32, error)
|
||||
AssignImage(siteIDs []uint32, imageID uint32) error
|
||||
RepointImage(fromImageIDs []uint32, toImageID uint32) (int, error)
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
package slug
|
||||
|
||||
import (
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
)
|
||||
|
||||
const MaxRunes = 100
|
||||
|
||||
var pattern = regexp.MustCompile(`^[a-z0-9]+(-[a-z0-9]+)*$`)
|
||||
|
||||
var nonSlugRun = regexp.MustCompile(`[^a-z0-9]+`)
|
||||
|
||||
var diacriticFolder = strings.NewReplacer(
|
||||
"à", "a", "á", "a", "â", "a", "ã", "a", "ä", "a", "å", "a", "ā", "a", "ă", "a", "ą", "a",
|
||||
"æ", "ae",
|
||||
"ç", "c", "ć", "c", "č", "c", "ĉ", "c",
|
||||
"ď", "d", "đ", "d",
|
||||
"è", "e", "é", "e", "ê", "e", "ë", "e", "ē", "e", "ė", "e", "ę", "e", "ě", "e",
|
||||
"ğ", "g",
|
||||
"ì", "i", "í", "i", "î", "i", "ï", "i", "ī", "i", "į", "i", "ı", "i",
|
||||
"ł", "l", "ľ", "l",
|
||||
"ñ", "n", "ń", "n", "ň", "n",
|
||||
"ò", "o", "ó", "o", "ô", "o", "õ", "o", "ö", "o", "ø", "o", "ō", "o", "ő", "o",
|
||||
"œ", "oe",
|
||||
"ř", "r",
|
||||
"ś", "s", "š", "s", "ş", "s", "ș", "s",
|
||||
"ß", "ss",
|
||||
"ť", "t", "ț", "t", "ţ", "t",
|
||||
"ù", "u", "ú", "u", "û", "u", "ü", "u", "ū", "u", "ů", "u", "ű", "u", "ų", "u",
|
||||
"ý", "y", "ÿ", "y",
|
||||
"ź", "z", "ż", "z", "ž", "z",
|
||||
)
|
||||
|
||||
func IsValid(candidate string) bool {
|
||||
length := utf8.RuneCountInString(candidate)
|
||||
return length >= 1 && length <= MaxRunes && pattern.MatchString(candidate)
|
||||
}
|
||||
|
||||
func Generate(text string, fallback string) string {
|
||||
folded := diacriticFolder.Replace(strings.ToLower(text))
|
||||
generated := strings.Trim(nonSlugRun.ReplaceAllString(folded, "-"), "-")
|
||||
generated = truncate(generated, MaxRunes)
|
||||
if generated == "" {
|
||||
return fallback
|
||||
}
|
||||
return generated
|
||||
}
|
||||
|
||||
func WithSuffix(base string, attempt int) string {
|
||||
if attempt <= 1 {
|
||||
return base
|
||||
}
|
||||
suffix := "-" + strconv.Itoa(attempt)
|
||||
return truncate(base, MaxRunes-len(suffix)) + suffix
|
||||
}
|
||||
|
||||
func truncate(candidate string, limit int) string {
|
||||
if len(candidate) <= limit {
|
||||
return candidate
|
||||
}
|
||||
return strings.TrimRight(candidate[:limit], "-")
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
package database
|
||||
|
||||
import (
|
||||
"RenewCMS/internal/domain/article"
|
||||
entity "RenewCMS/internal/infrastructure/persistence/models"
|
||||
"slices"
|
||||
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
const (
|
||||
articleSlugIndexName = "idx_articles_site_slug"
|
||||
articleSlugBackfillBatchSize = 500
|
||||
articleSlugIndexStatement = "CREATE UNIQUE INDEX idx_articles_site_slug ON articles (site_id, slug)"
|
||||
)
|
||||
|
||||
type slugOwner struct {
|
||||
siteID uint32
|
||||
slug string
|
||||
}
|
||||
|
||||
type slugAssignment struct {
|
||||
id uint32
|
||||
slug string
|
||||
}
|
||||
|
||||
func BackfillArticleSlugs(db *gorm.DB) error {
|
||||
var rows []entity.Article
|
||||
if err := db.Unscoped().Select("id", "site_id", "title", "slug", "deleted_at").Order("id ASC").Find(&rows).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
assignments := planSlugAssignments(rows)
|
||||
for batch := range slices.Chunk(assignments, articleSlugBackfillBatchSize) {
|
||||
if err := writeSlugAssignments(db, batch); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func writeSlugAssignments(db *gorm.DB, batch []slugAssignment) error {
|
||||
return db.Transaction(func(tx *gorm.DB) error {
|
||||
for _, assignment := range batch {
|
||||
if err := tx.Unscoped().Model(&entity.Article{}).Where("id = ?", assignment.id).UpdateColumn("slug", assignment.slug).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
func planSlugAssignments(rows []entity.Article) []slugAssignment {
|
||||
assignments := []slugAssignment{}
|
||||
claimed := map[slugOwner]bool{}
|
||||
pending := []entity.Article{}
|
||||
for _, row := range rows {
|
||||
if row.DeletedAt.Valid {
|
||||
if tombstone := article.Tombstone(row.ID); row.Slug != tombstone {
|
||||
assignments = append(assignments, slugAssignment{row.ID, tombstone})
|
||||
}
|
||||
continue
|
||||
}
|
||||
owner := slugOwner{row.SiteID, row.Slug}
|
||||
if row.Slug == "" || claimed[owner] {
|
||||
pending = append(pending, row)
|
||||
continue
|
||||
}
|
||||
claimed[owner] = true
|
||||
}
|
||||
for _, row := range pending {
|
||||
base := row.Slug
|
||||
attempt := 2
|
||||
if base == "" {
|
||||
base = snapshotSlug(row.Title)
|
||||
attempt = 1
|
||||
}
|
||||
slug := firstFreeSnapshotSlug(claimed, row.SiteID, base, attempt)
|
||||
claimed[slugOwner{row.SiteID, slug}] = true
|
||||
assignments = append(assignments, slugAssignment{row.ID, slug})
|
||||
}
|
||||
return assignments
|
||||
}
|
||||
|
||||
func firstFreeSnapshotSlug(claimed map[slugOwner]bool, siteID uint32, base string, attempt int) string {
|
||||
for ; ; attempt++ {
|
||||
candidate := snapshotSlugWithSuffix(base, attempt)
|
||||
if !claimed[slugOwner{siteID, candidate}] {
|
||||
return candidate
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func ensureArticleSlugIndex(db *gorm.DB) error {
|
||||
if db.Migrator().HasIndex(&entity.Article{}, articleSlugIndexName) {
|
||||
return nil
|
||||
}
|
||||
return db.Exec(articleSlugIndexStatement).Error
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
package database
|
||||
|
||||
import (
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
const (
|
||||
snapshotMaxRunes = 100
|
||||
snapshotFallbackSlug = "article"
|
||||
)
|
||||
|
||||
var snapshotNonSlugRun = regexp.MustCompile(`[^a-z0-9]+`)
|
||||
|
||||
var snapshotFolder = strings.NewReplacer(
|
||||
"à", "a", "á", "a", "â", "a", "ã", "a", "ä", "a", "å", "a", "ā", "a", "ă", "a", "ą", "a",
|
||||
"æ", "ae",
|
||||
"ç", "c", "ć", "c", "č", "c", "ĉ", "c",
|
||||
"ď", "d", "đ", "d",
|
||||
"è", "e", "é", "e", "ê", "e", "ë", "e", "ē", "e", "ė", "e", "ę", "e", "ě", "e",
|
||||
"ğ", "g",
|
||||
"ì", "i", "í", "i", "î", "i", "ï", "i", "ī", "i", "į", "i", "ı", "i",
|
||||
"ł", "l", "ľ", "l",
|
||||
"ñ", "n", "ń", "n", "ň", "n",
|
||||
"ò", "o", "ó", "o", "ô", "o", "õ", "o", "ö", "o", "ø", "o", "ō", "o", "ő", "o",
|
||||
"œ", "oe",
|
||||
"ř", "r",
|
||||
"ś", "s", "š", "s", "ş", "s", "ș", "s",
|
||||
"ß", "ss",
|
||||
"ť", "t", "ț", "t", "ţ", "t",
|
||||
"ù", "u", "ú", "u", "û", "u", "ü", "u", "ū", "u", "ů", "u", "ű", "u", "ų", "u",
|
||||
"ý", "y", "ÿ", "y",
|
||||
"ź", "z", "ż", "z", "ž", "z",
|
||||
)
|
||||
|
||||
func snapshotSlug(text string) string {
|
||||
folded := snapshotFolder.Replace(strings.ToLower(text))
|
||||
generated := strings.Trim(snapshotNonSlugRun.ReplaceAllString(folded, "-"), "-")
|
||||
generated = snapshotTruncate(generated, snapshotMaxRunes)
|
||||
if generated == "" {
|
||||
return snapshotFallbackSlug
|
||||
}
|
||||
return generated
|
||||
}
|
||||
|
||||
func snapshotSlugWithSuffix(base string, attempt int) string {
|
||||
if attempt <= 1 {
|
||||
return base
|
||||
}
|
||||
suffix := "-" + strconv.Itoa(attempt)
|
||||
return snapshotTruncate(base, snapshotMaxRunes-len(suffix)) + suffix
|
||||
}
|
||||
|
||||
func snapshotTruncate(candidate string, limit int) string {
|
||||
if len(candidate) <= limit {
|
||||
return candidate
|
||||
}
|
||||
return strings.TrimRight(candidate[:limit], "-")
|
||||
}
|
||||
@@ -6,15 +6,27 @@ import (
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
func Migrate(db *gorm.DB) error {
|
||||
err := tableOptionsFor(db).AutoMigrate(&models.Article{}, &models.Image{}, &models.User{}, &models.Invite{}, &models.APIKey{}, &models.PurgeSettings{}, &models.AuditEvent{}, &models.AuditSettings{}, &models.ImageVariant{}, &models.ImageVariantFile{}, &models.ImageVariantRejectionDay{})
|
||||
func Migrate(db *gorm.DB, publicURL string) error {
|
||||
err := tableOptionsFor(db).AutoMigrate(&models.Article{}, &models.Image{}, &models.User{}, &models.Invite{}, &models.APIKey{}, &models.PurgeSettings{}, &models.AuditEvent{}, &models.AuditSettings{}, &models.ImageVariant{}, &models.ImageVariantFile{}, &models.ImageVariantRejectionDay{}, &models.Site{}, &models.Author{}, &models.ArticleAuthor{})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := ensureImagePathIndex(db); err != nil {
|
||||
return err
|
||||
}
|
||||
return BackfillUserRoles(db)
|
||||
if err := BackfillUserRoles(db); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := SeedDefaultSite(db, publicURL); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := BackfillSiteTitleTemplates(db); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := BackfillArticleSlugs(db); err != nil {
|
||||
return err
|
||||
}
|
||||
return ensureArticleSlugIndex(db)
|
||||
}
|
||||
|
||||
const (
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
package database
|
||||
|
||||
import (
|
||||
domainSite "RenewCMS/internal/domain/site"
|
||||
entity "RenewCMS/internal/infrastructure/persistence/models"
|
||||
"fmt"
|
||||
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
func SeedDefaultSite(db *gorm.DB, publicURL string) error {
|
||||
return db.Transaction(func(tx *gorm.DB) error {
|
||||
defaultSite, err := ensureDefaultSite(tx, publicURL)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return tx.Unscoped().Model(&entity.Article{}).Where("site_id IS NULL OR site_id = 0").UpdateColumn("site_id", defaultSite.ID).Error
|
||||
})
|
||||
}
|
||||
|
||||
func ensureDefaultSite(tx *gorm.DB, publicURL string) (entity.Site, error) {
|
||||
var total int64
|
||||
if err := tx.Model(&entity.Site{}).Count(&total).Error; err != nil {
|
||||
return entity.Site{}, err
|
||||
}
|
||||
if total > 0 {
|
||||
return firstDefaultSite(tx)
|
||||
}
|
||||
baseURL, err := domainSite.SeedBaseURL(publicURL)
|
||||
if err != nil {
|
||||
return entity.Site{}, fmt.Errorf("PUBLIC_URL %q cannot seed the first site: %w", publicURL, err)
|
||||
}
|
||||
seeded := entity.Site{
|
||||
Name: domainSite.DefaultName,
|
||||
Key: domainSite.DefaultKey,
|
||||
BaseURL: baseURL,
|
||||
DefaultRobots: domainSite.RobotsIndex,
|
||||
IsDefault: true,
|
||||
TitleTemplate: domainSite.DefaultTitleTemplate,
|
||||
}
|
||||
if err := tx.Create(&seeded).Error; err != nil {
|
||||
return entity.Site{}, err
|
||||
}
|
||||
return seeded, nil
|
||||
}
|
||||
|
||||
func firstDefaultSite(tx *gorm.DB) (entity.Site, error) {
|
||||
var found entity.Site
|
||||
if err := tx.Order("is_default DESC, id ASC").First(&found).Error; err != nil {
|
||||
return entity.Site{}, err
|
||||
}
|
||||
return found, nil
|
||||
}
|
||||
|
||||
func BackfillSiteTitleTemplates(db *gorm.DB) error {
|
||||
return db.Model(&entity.Site{}).Where("title_template IS NULL OR title_template = ''").UpdateColumn("title_template", domainSite.DefaultTitleTemplate).Error
|
||||
}
|
||||
@@ -3,25 +3,76 @@ package mappers
|
||||
import (
|
||||
"RenewCMS/internal/domain/article"
|
||||
"RenewCMS/internal/infrastructure/persistence/models"
|
||||
"encoding/json"
|
||||
)
|
||||
|
||||
const emptyDismissed = "[]"
|
||||
|
||||
func decodeDismissed(raw string) []string {
|
||||
codes := []string{}
|
||||
if raw == "" {
|
||||
return codes
|
||||
}
|
||||
if err := json.Unmarshal([]byte(raw), &codes); err != nil || codes == nil {
|
||||
return []string{}
|
||||
}
|
||||
return codes
|
||||
}
|
||||
|
||||
func encodeDismissed(codes []string) string {
|
||||
if len(codes) == 0 {
|
||||
return emptyDismissed
|
||||
}
|
||||
encoded, err := json.Marshal(codes)
|
||||
if err != nil {
|
||||
return emptyDismissed
|
||||
}
|
||||
return string(encoded)
|
||||
}
|
||||
|
||||
func ArticleToDomain(m models.Article) article.Article {
|
||||
return article.Article{
|
||||
ID: m.ID,
|
||||
Title: m.Title,
|
||||
Body: m.Body,
|
||||
IsOnline: m.IsOnline,
|
||||
CreatedAt: m.CreatedAt,
|
||||
UpdatedAt: m.UpdatedAt,
|
||||
ID: m.ID,
|
||||
Title: m.Title,
|
||||
Body: m.Body,
|
||||
IsOnline: m.IsOnline,
|
||||
SiteID: m.SiteID,
|
||||
Slug: m.Slug,
|
||||
Excerpt: m.Excerpt,
|
||||
SEOTitle: m.SEOTitle,
|
||||
SEODescription: m.SEODescription,
|
||||
CoverImageID: m.CoverImageID,
|
||||
CoverImageAlt: m.CoverImageAlt,
|
||||
SocialTitle: m.SocialTitle,
|
||||
SocialDescription: m.SocialDescription,
|
||||
SocialImageID: m.SocialImageID,
|
||||
CanonicalURL: m.CanonicalURL,
|
||||
Noindex: m.Noindex,
|
||||
SEODismissed: decodeDismissed(m.SEODismissed),
|
||||
CreatedAt: m.CreatedAt,
|
||||
UpdatedAt: m.UpdatedAt,
|
||||
}
|
||||
}
|
||||
|
||||
func ArticleToModel(a article.Article) models.Article {
|
||||
return models.Article{
|
||||
Title: a.Title,
|
||||
Body: a.Body,
|
||||
IsOnline: a.IsOnline,
|
||||
CreatedAt: a.CreatedAt,
|
||||
UpdatedAt: a.UpdatedAt,
|
||||
Title: a.Title,
|
||||
Body: a.Body,
|
||||
IsOnline: a.IsOnline,
|
||||
SiteID: a.SiteID,
|
||||
Slug: a.Slug,
|
||||
Excerpt: a.Excerpt,
|
||||
SEOTitle: a.SEOTitle,
|
||||
SEODescription: a.SEODescription,
|
||||
CoverImageID: a.CoverImageID,
|
||||
CoverImageAlt: a.CoverImageAlt,
|
||||
SocialTitle: a.SocialTitle,
|
||||
SocialDescription: a.SocialDescription,
|
||||
SocialImageID: a.SocialImageID,
|
||||
CanonicalURL: a.CanonicalURL,
|
||||
Noindex: a.Noindex,
|
||||
SEODismissed: encodeDismissed(a.SEODismissed),
|
||||
CreatedAt: a.CreatedAt,
|
||||
UpdatedAt: a.UpdatedAt,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
package mappers
|
||||
|
||||
import (
|
||||
"RenewCMS/internal/domain/author"
|
||||
"RenewCMS/internal/infrastructure/persistence/models"
|
||||
"encoding/json"
|
||||
)
|
||||
|
||||
const emptyLinks = "[]"
|
||||
|
||||
func decodeLinks(raw string) []author.SocialLink {
|
||||
links := []author.SocialLink{}
|
||||
if raw == "" {
|
||||
return links
|
||||
}
|
||||
if err := json.Unmarshal([]byte(raw), &links); err != nil || links == nil {
|
||||
return []author.SocialLink{}
|
||||
}
|
||||
return links
|
||||
}
|
||||
|
||||
func encodeLinks(links []author.SocialLink) string {
|
||||
if len(links) == 0 {
|
||||
return emptyLinks
|
||||
}
|
||||
encoded, err := json.Marshal(links)
|
||||
if err != nil {
|
||||
return emptyLinks
|
||||
}
|
||||
return string(encoded)
|
||||
}
|
||||
|
||||
func AuthorToDomain(m models.Author, articleCount int) author.Author {
|
||||
return author.Author{
|
||||
ID: m.ID,
|
||||
Name: m.Name,
|
||||
Slug: m.Slug,
|
||||
Bio: m.Bio,
|
||||
AvatarID: m.AvatarID,
|
||||
Website: m.Website,
|
||||
SocialLinks: decodeLinks(m.SocialLinks),
|
||||
UserID: m.UserID,
|
||||
IsLinked: m.UserID != nil,
|
||||
ArticleCount: articleCount,
|
||||
}
|
||||
}
|
||||
|
||||
func AuthorToModel(a author.Author) models.Author {
|
||||
return models.Author{
|
||||
ID: a.ID,
|
||||
Name: a.Name,
|
||||
Slug: a.Slug,
|
||||
Bio: a.Bio,
|
||||
AvatarID: a.AvatarID,
|
||||
Website: a.Website,
|
||||
SocialLinks: encodeLinks(a.SocialLinks),
|
||||
UserID: a.UserID,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
package mappers
|
||||
|
||||
import (
|
||||
"RenewCMS/internal/domain/site"
|
||||
"RenewCMS/internal/infrastructure/persistence/models"
|
||||
)
|
||||
|
||||
func SiteToDomain(m models.Site, articleCount int) site.Site {
|
||||
titleTemplate := m.TitleTemplate
|
||||
if titleTemplate == "" {
|
||||
titleTemplate = site.DefaultTitleTemplate
|
||||
}
|
||||
return site.Site{
|
||||
ID: m.ID,
|
||||
Name: m.Name,
|
||||
Key: m.Key,
|
||||
BaseURL: m.BaseURL,
|
||||
DefaultSocialImageID: m.DefaultSocialImageID,
|
||||
DefaultRobots: m.DefaultRobots,
|
||||
Locale: m.Locale,
|
||||
IsDefault: m.IsDefault,
|
||||
ArticleCount: articleCount,
|
||||
SiteName: m.SiteName,
|
||||
TitleTemplate: titleTemplate,
|
||||
DefaultDescription: m.DefaultDescription,
|
||||
}
|
||||
}
|
||||
|
||||
func SiteToModel(s site.Site) models.Site {
|
||||
return models.Site{
|
||||
ID: s.ID,
|
||||
Name: s.Name,
|
||||
Key: s.Key,
|
||||
BaseURL: s.BaseURL,
|
||||
DefaultSocialImageID: s.DefaultSocialImageID,
|
||||
DefaultRobots: s.DefaultRobots,
|
||||
Locale: s.Locale,
|
||||
IsDefault: s.IsDefault,
|
||||
SiteName: s.SiteName,
|
||||
TitleTemplate: s.TitleTemplate,
|
||||
DefaultDescription: s.DefaultDescription,
|
||||
}
|
||||
}
|
||||
@@ -8,10 +8,23 @@ import (
|
||||
|
||||
type Article struct {
|
||||
gorm.Model
|
||||
ID uint32 `gorm:"primary_key;auto_increment;not_null"`
|
||||
Title string
|
||||
Body string
|
||||
IsOnline bool `gorm:"not_null;default:false"`
|
||||
CreatedAt time.Time `gorm:"autoCreateTime"`
|
||||
UpdatedAt time.Time `gorm:"autoUpdateTime"`
|
||||
ID uint32 `gorm:"primary_key;auto_increment;not_null"`
|
||||
Title string
|
||||
Body string
|
||||
IsOnline bool `gorm:"not_null;default:false"`
|
||||
SiteID uint32 `gorm:"index"`
|
||||
Slug string `gorm:"size:100;not null;default:''"`
|
||||
Excerpt string `gorm:"size:300;not null;default:''"`
|
||||
SEOTitle string `gorm:"column:seo_title;size:120;not null;default:''"`
|
||||
SEODescription string `gorm:"column:seo_description;size:320;not null;default:''"`
|
||||
CoverImageID *uint32 `gorm:"index"`
|
||||
CoverImageAlt string `gorm:"size:200;not null;default:''"`
|
||||
SocialTitle string `gorm:"size:120;not null;default:''"`
|
||||
SocialDescription string `gorm:"size:320;not null;default:''"`
|
||||
SocialImageID *uint32 `gorm:"index"`
|
||||
CanonicalURL string `gorm:"column:canonical_url;size:2048;not null;default:''"`
|
||||
Noindex bool `gorm:"not null;default:false"`
|
||||
SEODismissed string `gorm:"column:seo_dismissed;type:text"`
|
||||
CreatedAt time.Time `gorm:"autoCreateTime"`
|
||||
UpdatedAt time.Time `gorm:"autoUpdateTime"`
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package models
|
||||
|
||||
import "time"
|
||||
|
||||
type Author struct {
|
||||
ID uint32 `gorm:"primaryKey;autoIncrement"`
|
||||
Name string `gorm:"size:100;not null"`
|
||||
Slug string `gorm:"size:100;not null;uniqueIndex"`
|
||||
Bio string `gorm:"size:280;not null"`
|
||||
AvatarID *uint32 `gorm:"index"`
|
||||
Website *string `gorm:"size:2048"`
|
||||
SocialLinks string `gorm:"type:text;not null"`
|
||||
UserID *uint32 `gorm:"uniqueIndex"`
|
||||
CreatedAt time.Time `gorm:"autoCreateTime"`
|
||||
UpdatedAt time.Time `gorm:"autoUpdateTime"`
|
||||
}
|
||||
|
||||
type ArticleAuthor struct {
|
||||
ID uint32 `gorm:"primaryKey;autoIncrement"`
|
||||
ArticleID uint32 `gorm:"not null;uniqueIndex:idx_article_authors_pair"`
|
||||
AuthorID uint32 `gorm:"not null;uniqueIndex:idx_article_authors_pair;index"`
|
||||
Position int `gorm:"not null"`
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package models
|
||||
|
||||
import "time"
|
||||
|
||||
type Site struct {
|
||||
ID uint32 `gorm:"primaryKey;autoIncrement"`
|
||||
Name string `gorm:"size:100;not null"`
|
||||
Key string `gorm:"column:site_key;size:32;not null;uniqueIndex"`
|
||||
BaseURL string `gorm:"size:255;not null"`
|
||||
DefaultSocialImageID *uint32
|
||||
DefaultRobots string `gorm:"size:16;not null"`
|
||||
Locale *string `gorm:"size:35"`
|
||||
IsDefault bool `gorm:"not null"`
|
||||
SiteName string `gorm:"size:100;not null;default:''"`
|
||||
TitleTemplate string `gorm:"size:200"`
|
||||
DefaultDescription string `gorm:"size:320;not null;default:''"`
|
||||
CreatedAt time.Time `gorm:"autoCreateTime"`
|
||||
UpdatedAt time.Time `gorm:"autoUpdateTime"`
|
||||
}
|
||||
@@ -2,8 +2,11 @@ package persistence
|
||||
|
||||
import (
|
||||
domain "RenewCMS/internal/domain/article"
|
||||
authordomain "RenewCMS/internal/domain/author"
|
||||
"RenewCMS/internal/infrastructure/persistence/mappers"
|
||||
entity "RenewCMS/internal/infrastructure/persistence/models"
|
||||
"errors"
|
||||
"sort"
|
||||
|
||||
"strings"
|
||||
"unicode"
|
||||
@@ -40,6 +43,9 @@ func (a *ArticleRepository) scoped(filters domain.Filters) *gorm.DB {
|
||||
if filters.IsOnline != nil {
|
||||
query = query.Where("is_online = ?", *filters.IsOnline)
|
||||
}
|
||||
if filters.SiteID != nil {
|
||||
query = query.Where("site_id = ?", *filters.SiteID)
|
||||
}
|
||||
switch filters.Status {
|
||||
case domain.StatusOnline:
|
||||
query = query.Where("is_online = ?", true)
|
||||
@@ -54,6 +60,7 @@ var sortColumns = map[domain.SortField]string{
|
||||
domain.SortByStatus: "is_online",
|
||||
domain.SortByCreatedAt: "created_at",
|
||||
domain.SortByUpdatedAt: "updated_at",
|
||||
domain.SortByID: "id",
|
||||
}
|
||||
|
||||
var sortDirections = map[domain.SortDirection]string{
|
||||
@@ -67,6 +74,9 @@ func orderClause(sort domain.Sort) string {
|
||||
if !ok || !directionOk {
|
||||
column, direction = sortColumns[domain.SortByUpdatedAt], sortDirections[domain.SortDesc]
|
||||
}
|
||||
if sort.Field == domain.SortByID {
|
||||
return column + " " + direction
|
||||
}
|
||||
return column + " " + direction + ", id DESC"
|
||||
}
|
||||
|
||||
@@ -82,11 +92,19 @@ func (a *ArticleRepository) FindPage(filters domain.Filters) (domain.PageResult,
|
||||
return domain.PageResult{}, err
|
||||
}
|
||||
var entityArticles []entity.Article
|
||||
err := a.scoped(filters).Order(orderClause(filters.Sort)).Limit(filters.Size).Offset((filters.Page - 1) * filters.Size).Find(&entityArticles).Error
|
||||
ordered := a.scoped(filters).Order(orderClause(filters.Sort))
|
||||
if !filters.Unpaged {
|
||||
ordered = ordered.Limit(filters.Size).Offset((filters.Page - 1) * filters.Size)
|
||||
}
|
||||
err := ordered.Find(&entityArticles).Error
|
||||
if err != nil {
|
||||
return domain.PageResult{}, err
|
||||
}
|
||||
return domain.PageResult{Items: toDomainArticles(entityArticles), Total: int(total)}, nil
|
||||
items, err := a.withAuthors(a.db, toDomainArticles(entityArticles))
|
||||
if err != nil {
|
||||
return domain.PageResult{}, err
|
||||
}
|
||||
return domain.PageResult{Items: items, Total: int(total)}, nil
|
||||
}
|
||||
|
||||
func (a *ArticleRepository) findMatchingTitle(filters domain.Filters) (domain.PageResult, error) {
|
||||
@@ -101,16 +119,23 @@ func (a *ArticleRepository) findMatchingTitle(filters domain.Filters) (domain.Pa
|
||||
matchingIds = append(matchingIds, candidate.ID)
|
||||
}
|
||||
}
|
||||
start := min((filters.Page-1)*filters.Size, len(matchingIds))
|
||||
end := min(start+filters.Size, len(matchingIds))
|
||||
pageIds := matchingIds[start:end]
|
||||
pageIds := matchingIds
|
||||
if !filters.Unpaged {
|
||||
start := min((filters.Page-1)*filters.Size, len(matchingIds))
|
||||
end := min(start+filters.Size, len(matchingIds))
|
||||
pageIds = matchingIds[start:end]
|
||||
}
|
||||
page := domain.PageResult{Items: []domain.Article{}, Total: len(matchingIds)}
|
||||
if len(pageIds) == 0 {
|
||||
return page, nil
|
||||
}
|
||||
var entityArticles []entity.Article
|
||||
if err := a.db.Model(&entity.Article{}).Where("id IN ?", pageIds).Find(&entityArticles).Error; err != nil {
|
||||
return domain.PageResult{}, err
|
||||
for _, chunk := range chunkIDs(pageIds) {
|
||||
var loaded []entity.Article
|
||||
if err := a.db.Model(&entity.Article{}).Where("id IN ?", chunk).Find(&loaded).Error; err != nil {
|
||||
return domain.PageResult{}, err
|
||||
}
|
||||
entityArticles = append(entityArticles, loaded...)
|
||||
}
|
||||
byId := make(map[uint32]entity.Article, len(entityArticles))
|
||||
for _, entityArticle := range entityArticles {
|
||||
@@ -122,7 +147,11 @@ func (a *ArticleRepository) findMatchingTitle(filters domain.Filters) (domain.Pa
|
||||
ordered = append(ordered, entityArticle)
|
||||
}
|
||||
}
|
||||
page.Items = toDomainArticles(ordered)
|
||||
items, err := a.withAuthors(a.db, toDomainArticles(ordered))
|
||||
if err != nil {
|
||||
return domain.PageResult{}, err
|
||||
}
|
||||
page.Items = items
|
||||
return page, nil
|
||||
}
|
||||
|
||||
@@ -147,6 +176,101 @@ func toDomainArticles(entityArticles []entity.Article) []domain.Article {
|
||||
return domainArticles
|
||||
}
|
||||
|
||||
func (a *ArticleRepository) withAuthors(db *gorm.DB, articles []domain.Article) ([]domain.Article, error) {
|
||||
ids := make([]uint32, 0, len(articles))
|
||||
for _, article := range articles {
|
||||
ids = append(ids, article.ID)
|
||||
}
|
||||
bylines, err := loadBylines(db, ids)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for index := range articles {
|
||||
articles[index].Authors = bylines[articles[index].ID]
|
||||
if articles[index].Authors == nil {
|
||||
articles[index].Authors = []authordomain.Byline{}
|
||||
}
|
||||
}
|
||||
return articles, nil
|
||||
}
|
||||
|
||||
func (a *ArticleRepository) withAuthorsOne(db *gorm.DB, article domain.Article) (domain.Article, error) {
|
||||
loaded, err := a.withAuthors(db, []domain.Article{article})
|
||||
if err != nil {
|
||||
return domain.Article{}, err
|
||||
}
|
||||
return loaded[0], nil
|
||||
}
|
||||
|
||||
const idChunkSize = 500
|
||||
|
||||
func chunkIDs(ids []uint32) [][]uint32 {
|
||||
chunks := make([][]uint32, 0, len(ids)/idChunkSize+1)
|
||||
for start := 0; start < len(ids); start += idChunkSize {
|
||||
chunks = append(chunks, ids[start:min(start+idChunkSize, len(ids))])
|
||||
}
|
||||
return chunks
|
||||
}
|
||||
|
||||
func loadBylines(db *gorm.DB, articleIDs []uint32) (map[uint32][]authordomain.Byline, error) {
|
||||
bylines := make(map[uint32][]authordomain.Byline, len(articleIDs))
|
||||
if len(articleIDs) == 0 {
|
||||
return bylines, nil
|
||||
}
|
||||
var credits []entity.ArticleAuthor
|
||||
for _, chunk := range chunkIDs(articleIDs) {
|
||||
var loaded []entity.ArticleAuthor
|
||||
if err := db.Where("article_id IN ?", chunk).Order("position ASC, id ASC").Find(&loaded).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
credits = append(credits, loaded...)
|
||||
}
|
||||
sort.SliceStable(credits, func(i, j int) bool {
|
||||
if credits[i].Position != credits[j].Position {
|
||||
return credits[i].Position < credits[j].Position
|
||||
}
|
||||
return credits[i].ID < credits[j].ID
|
||||
})
|
||||
if len(credits) == 0 {
|
||||
return bylines, nil
|
||||
}
|
||||
authorIDs := make([]uint32, 0, len(credits))
|
||||
for _, credit := range credits {
|
||||
authorIDs = append(authorIDs, credit.AuthorID)
|
||||
}
|
||||
var found []entity.Author
|
||||
for _, chunk := range chunkIDs(authorIDs) {
|
||||
var loaded []entity.Author
|
||||
if err := db.Where("id IN ?", chunk).Find(&loaded).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
found = append(found, loaded...)
|
||||
}
|
||||
byID := make(map[uint32]entity.Author, len(found))
|
||||
for _, model := range found {
|
||||
byID[model.ID] = model
|
||||
}
|
||||
for _, credit := range credits {
|
||||
if model, ok := byID[credit.AuthorID]; ok {
|
||||
bylines[credit.ArticleID] = append(bylines[credit.ArticleID], mappers.AuthorToDomain(model, 0).Byline())
|
||||
}
|
||||
}
|
||||
return bylines, nil
|
||||
}
|
||||
|
||||
func replaceCredits(tx *gorm.DB, articleID uint32, authorIDs []uint32) error {
|
||||
if err := tx.Where("article_id = ?", articleID).Delete(&entity.ArticleAuthor{}).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
for position, authorID := range authorIDs {
|
||||
credit := entity.ArticleAuthor{ArticleID: articleID, AuthorID: authorID, Position: position}
|
||||
if err := tx.Create(&credit).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func foldForSearch(value string) string {
|
||||
folder := transform.Chain(norm.NFD, runes.Remove(runes.In(unicode.Mn)), norm.NFC)
|
||||
folded, _, err := transform.String(folder, value)
|
||||
@@ -163,7 +287,7 @@ func (a *ArticleRepository) Get(id uint32) (domain.Article, error) {
|
||||
return domain.Article{}, mapNotFoundErr(err, domain.ErrArticleNotFound)
|
||||
}
|
||||
|
||||
return mappers.ArticleToDomain(article), nil
|
||||
return a.withAuthorsOne(a.db, mappers.ArticleToDomain(article))
|
||||
}
|
||||
|
||||
func (a *ArticleRepository) GetByName(name string) (domain.Article, error) {
|
||||
@@ -173,23 +297,63 @@ func (a *ArticleRepository) GetByName(name string) (domain.Article, error) {
|
||||
return domain.Article{}, mapNotFoundErr(err, domain.ErrArticleNotFound)
|
||||
}
|
||||
|
||||
return mappers.ArticleToDomain(article), nil
|
||||
return a.withAuthorsOne(a.db, mappers.ArticleToDomain(article))
|
||||
}
|
||||
|
||||
func (a *ArticleRepository) Create(article domain.Article) (domain.Article, error) {
|
||||
creationResult := a.db.Create(&entity.Article{
|
||||
Title: article.Title,
|
||||
Body: article.Body,
|
||||
IsOnline: article.IsOnline,
|
||||
created := mappers.ArticleToModel(article)
|
||||
err := a.db.Transaction(func(tx *gorm.DB) error {
|
||||
if article.SiteID != 0 {
|
||||
if _, err := lockSite(tx, article.SiteID); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if err := ensureSlugFree(tx, article.SiteID, article.Slug, 0); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := tx.Create(&created).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
return replaceCredits(tx, created.ID, authordomain.BylineIDs(article.Authors))
|
||||
})
|
||||
if creationResult.Error != nil {
|
||||
return domain.Article{}, creationResult.Error
|
||||
if err != nil {
|
||||
return domain.Article{}, a.explainSlugFailure(article.SiteID, article.Slug, 0, err)
|
||||
}
|
||||
return a.withAuthorsOne(a.db, mappers.ArticleToDomain(created))
|
||||
}
|
||||
|
||||
var createdArticle entity.Article
|
||||
creationResult.Scan(&createdArticle)
|
||||
func articleSlugInUse(db *gorm.DB, siteID uint32, slug string, exceptID uint32) (bool, error) {
|
||||
var total int64
|
||||
err := db.Model(&entity.Article{}).Where("site_id = ? AND slug = ? AND id <> ?", siteID, slug, exceptID).Count(&total).Error
|
||||
return total > 0, err
|
||||
}
|
||||
|
||||
return mappers.ArticleToDomain(createdArticle), nil
|
||||
func ensureSlugFree(db *gorm.DB, siteID uint32, slug string, exceptID uint32) error {
|
||||
if slug == "" {
|
||||
return nil
|
||||
}
|
||||
taken, err := articleSlugInUse(db, siteID, slug, exceptID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if taken {
|
||||
return domain.ErrSlugTaken
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (a *ArticleRepository) explainSlugFailure(siteID uint32, slug string, exceptID uint32, cause error) error {
|
||||
if errors.Is(cause, domain.ErrSlugTaken) {
|
||||
return cause
|
||||
}
|
||||
if err := ensureSlugFree(a.db, siteID, slug, exceptID); err != nil && errors.Is(err, domain.ErrSlugTaken) {
|
||||
return err
|
||||
}
|
||||
return cause
|
||||
}
|
||||
|
||||
func (a *ArticleRepository) SlugTaken(siteID uint32, slug string, exceptID uint32) (bool, error) {
|
||||
return articleSlugInUse(a.db, siteID, slug, exceptID)
|
||||
}
|
||||
|
||||
func (a *ArticleRepository) GetAll() []domain.Article {
|
||||
@@ -220,9 +384,76 @@ func (a *ArticleRepository) UpdateBody(id uint32, body string) (domain.Article,
|
||||
return domain.Article{}, err
|
||||
}
|
||||
|
||||
newArticle := mappers.ArticleToDomain(localArticle)
|
||||
return a.withAuthorsOne(a.db, mappers.ArticleToDomain(localArticle))
|
||||
}
|
||||
|
||||
return newArticle, nil
|
||||
func (a *ArticleRepository) Update(id uint32, update domain.Update) (domain.Article, error) {
|
||||
var localArticle entity.Article
|
||||
err := a.db.Transaction(func(tx *gorm.DB) error {
|
||||
if update.SiteID != nil {
|
||||
if _, err := lockSite(tx, *update.SiteID); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if err := tx.Model(&entity.Article{}).First(&localArticle, id).Error; err != nil {
|
||||
return mapNotFoundErr(err, domain.ErrArticleNotFound)
|
||||
}
|
||||
if update.SiteID == nil && update.Slug != nil {
|
||||
if _, err := lockSite(tx, localArticle.SiteID); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
applyUpdate(&localArticle, update)
|
||||
if update.Slug != nil || update.SiteID != nil {
|
||||
if err := ensureSlugFree(tx, localArticle.SiteID, localArticle.Slug, id); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if err := tx.Save(&localArticle).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
if update.AuthorIDs != nil {
|
||||
return replaceCredits(tx, id, *update.AuthorIDs)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return domain.Article{}, a.explainSlugFailure(localArticle.SiteID, localArticle.Slug, id, err)
|
||||
}
|
||||
return a.withAuthorsOne(a.db, mappers.ArticleToDomain(localArticle))
|
||||
}
|
||||
|
||||
func applyUpdate(target *entity.Article, update domain.Update) {
|
||||
setString(&target.Body, update.Body)
|
||||
setString(&target.Slug, update.Slug)
|
||||
setString(&target.Excerpt, update.Excerpt)
|
||||
setString(&target.SEOTitle, update.SEOTitle)
|
||||
setString(&target.SEODescription, update.SEODescription)
|
||||
setString(&target.CoverImageAlt, update.CoverImageAlt)
|
||||
setString(&target.SocialTitle, update.SocialTitle)
|
||||
setString(&target.SocialDescription, update.SocialDescription)
|
||||
setString(&target.CanonicalURL, update.CanonicalURL)
|
||||
if update.SiteID != nil {
|
||||
target.SiteID = *update.SiteID
|
||||
}
|
||||
if update.Noindex != nil {
|
||||
target.Noindex = *update.Noindex
|
||||
}
|
||||
if update.CoverImageID.Set {
|
||||
target.CoverImageID = update.CoverImageID.Value
|
||||
}
|
||||
if update.SocialImageID.Set {
|
||||
target.SocialImageID = update.SocialImageID.Value
|
||||
}
|
||||
if update.SEODismissed != nil {
|
||||
target.SEODismissed = mappers.ArticleToModel(domain.Article{SEODismissed: *update.SEODismissed}).SEODismissed
|
||||
}
|
||||
}
|
||||
|
||||
func setString(target *string, value *string) {
|
||||
if value != nil {
|
||||
*target = *value
|
||||
}
|
||||
}
|
||||
|
||||
func (a *ArticleRepository) UpdateIsOnline(id uint32, isOnline bool) (domain.Article, error) {
|
||||
@@ -238,12 +469,24 @@ func (a *ArticleRepository) UpdateIsOnline(id uint32, isOnline bool) (domain.Art
|
||||
return domain.Article{}, err
|
||||
}
|
||||
|
||||
return mappers.ArticleToDomain(localArticle), nil
|
||||
return a.withAuthorsOne(a.db, mappers.ArticleToDomain(localArticle))
|
||||
}
|
||||
|
||||
func (a *ArticleRepository) Delete(id uint32) error {
|
||||
result := a.db.Delete(&entity.Article{}, id)
|
||||
return deleteOrNotFound(result, domain.ErrArticleNotFound)
|
||||
return a.db.Transaction(func(tx *gorm.DB) error {
|
||||
var found entity.Article
|
||||
if err := tx.First(&found, id).Error; err != nil {
|
||||
return mapNotFoundErr(err, domain.ErrArticleNotFound)
|
||||
}
|
||||
tombstone := domain.Tombstone(id)
|
||||
if err := tx.Model(&entity.Article{}).Where("id = ?", id).UpdateColumn("slug", tombstone).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
if err := deleteOrNotFound(tx.Delete(&entity.Article{}, id), domain.ErrArticleNotFound); err != nil {
|
||||
return err
|
||||
}
|
||||
return tx.Where("article_id = ?", id).Delete(&entity.ArticleAuthor{}).Error
|
||||
})
|
||||
}
|
||||
|
||||
func (a *ArticleRepository) FindByBodyContaining(filename string) ([]domain.Article, error) {
|
||||
@@ -256,4 +499,73 @@ func (a *ArticleRepository) FindByBodyContaining(filename string) ([]domain.Arti
|
||||
return toDomainArticles(entityArticles), nil
|
||||
}
|
||||
|
||||
func (a *ArticleRepository) FindByImage(imageID uint32) ([]domain.Article, error) {
|
||||
var entityArticles []entity.Article
|
||||
err := a.db.Model(&entity.Article{}).Where("cover_image_id = ? OR social_image_id = ?", imageID, imageID).Order("id asc").Find(&entityArticles).Error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return toDomainArticles(entityArticles), nil
|
||||
}
|
||||
|
||||
func (a *ArticleRepository) ClearImage(imageID uint32) (domain.ImageReferences, error) {
|
||||
references := domain.ImageReferences{Cover: []uint32{}, Social: []uint32{}}
|
||||
err := a.db.Transaction(func(tx *gorm.DB) error {
|
||||
if err := clearColumn(tx, "cover_image_id", imageID, &references.Cover); err != nil {
|
||||
return err
|
||||
}
|
||||
return clearColumn(tx, "social_image_id", imageID, &references.Social)
|
||||
})
|
||||
if err != nil {
|
||||
return domain.ImageReferences{}, err
|
||||
}
|
||||
return references, nil
|
||||
}
|
||||
|
||||
func clearColumn(tx *gorm.DB, column string, imageID uint32, cleared *[]uint32) error {
|
||||
if err := tx.Model(&entity.Article{}).Where(column+" = ?", imageID).Order("id ASC").Pluck("id", cleared).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
if len(*cleared) == 0 {
|
||||
return nil
|
||||
}
|
||||
return tx.Model(&entity.Article{}).Where("id IN ?", *cleared).UpdateColumn(column, nil).Error
|
||||
}
|
||||
|
||||
func (a *ArticleRepository) RestoreImage(references domain.ImageReferences, imageID uint32) error {
|
||||
return a.db.Transaction(func(tx *gorm.DB) error {
|
||||
if err := assignColumn(tx, "cover_image_id", references.Cover, imageID); err != nil {
|
||||
return err
|
||||
}
|
||||
return assignColumn(tx, "social_image_id", references.Social, imageID)
|
||||
})
|
||||
}
|
||||
|
||||
func assignColumn(tx *gorm.DB, column string, articleIDs []uint32, imageID uint32) error {
|
||||
if len(articleIDs) == 0 {
|
||||
return nil
|
||||
}
|
||||
return tx.Model(&entity.Article{}).Where("id IN ?", articleIDs).UpdateColumn(column, imageID).Error
|
||||
}
|
||||
|
||||
func (a *ArticleRepository) RepointImage(fromImageIDs []uint32, toImageID uint32) ([]uint32, error) {
|
||||
changed := []uint32{}
|
||||
if len(fromImageIDs) == 0 {
|
||||
return changed, nil
|
||||
}
|
||||
err := a.db.Transaction(func(tx *gorm.DB) error {
|
||||
if err := tx.Model(&entity.Article{}).Where("cover_image_id IN ? OR social_image_id IN ?", fromImageIDs, fromImageIDs).Order("id ASC").Pluck("id", &changed).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
if err := tx.Model(&entity.Article{}).Where("cover_image_id IN ?", fromImageIDs).UpdateColumn("cover_image_id", toImageID).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
return tx.Model(&entity.Article{}).Where("social_image_id IN ?", fromImageIDs).UpdateColumn("social_image_id", toImageID).Error
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return changed, nil
|
||||
}
|
||||
|
||||
var _ domain.Repository = &ArticleRepository{}
|
||||
@@ -0,0 +1,365 @@
|
||||
package persistence
|
||||
|
||||
import (
|
||||
domain "RenewCMS/internal/domain/author"
|
||||
"RenewCMS/internal/infrastructure/persistence/mappers"
|
||||
entity "RenewCMS/internal/infrastructure/persistence/models"
|
||||
"strings"
|
||||
|
||||
"gorm.io/gorm"
|
||||
"gorm.io/gorm/clause"
|
||||
)
|
||||
|
||||
type AuthorRepository struct {
|
||||
db *gorm.DB
|
||||
}
|
||||
|
||||
func NewAuthorRepository(db *gorm.DB) *AuthorRepository {
|
||||
return &AuthorRepository{db}
|
||||
}
|
||||
|
||||
type creditTotal struct {
|
||||
AuthorID uint32
|
||||
Total int
|
||||
}
|
||||
|
||||
func creditCounts(db *gorm.DB, authorIDs []uint32) (map[uint32]int, error) {
|
||||
counts := make(map[uint32]int, len(authorIDs))
|
||||
if len(authorIDs) == 0 {
|
||||
return counts, nil
|
||||
}
|
||||
var totals []creditTotal
|
||||
err := db.Table("article_authors").
|
||||
Select("article_authors.author_id AS author_id, COUNT(*) AS total").
|
||||
Joins("JOIN articles ON articles.id = article_authors.article_id").
|
||||
Where("articles.deleted_at IS NULL").
|
||||
Where("article_authors.author_id IN ?", authorIDs).
|
||||
Group("article_authors.author_id").
|
||||
Scan(&totals).Error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, total := range totals {
|
||||
counts[total.AuthorID] = total.Total
|
||||
}
|
||||
return counts, nil
|
||||
}
|
||||
|
||||
func (a *AuthorRepository) toDomain(db *gorm.DB, models []entity.Author) ([]domain.Author, error) {
|
||||
ids := make([]uint32, 0, len(models))
|
||||
for _, model := range models {
|
||||
ids = append(ids, model.ID)
|
||||
}
|
||||
counts, err := creditCounts(db, ids)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
authors := make([]domain.Author, 0, len(models))
|
||||
for _, model := range models {
|
||||
authors = append(authors, mappers.AuthorToDomain(model, counts[model.ID]))
|
||||
}
|
||||
return authors, nil
|
||||
}
|
||||
|
||||
func (a *AuthorRepository) loadOne(db *gorm.DB, model entity.Author) (domain.Author, error) {
|
||||
authors, err := a.toDomain(db, []entity.Author{model})
|
||||
if err != nil {
|
||||
return domain.Author{}, err
|
||||
}
|
||||
return authors[0], nil
|
||||
}
|
||||
|
||||
func (a *AuthorRepository) List(query domain.ListQuery) (domain.Page, error) {
|
||||
query.Page = max(query.Page, 1)
|
||||
query.Size = max(query.Size, 0)
|
||||
needle := strings.TrimSpace(query.Q)
|
||||
if needle != "" {
|
||||
return a.findMatching(query, foldForSearch(needle))
|
||||
}
|
||||
var total int64
|
||||
if err := a.db.Model(&entity.Author{}).Count(&total).Error; err != nil {
|
||||
return domain.Page{}, err
|
||||
}
|
||||
var found []entity.Author
|
||||
err := a.db.Order("id DESC").Limit(query.Size).Offset(pageStart(query.Page, query.Size, int(total))).Find(&found).Error
|
||||
if err != nil {
|
||||
return domain.Page{}, err
|
||||
}
|
||||
items, err := a.toDomain(a.db, found)
|
||||
if err != nil {
|
||||
return domain.Page{}, err
|
||||
}
|
||||
return domain.Page{Items: items, Total: int(total)}, nil
|
||||
}
|
||||
|
||||
func pageStart(page int, size int, total int) int {
|
||||
if size <= 0 || page-1 > total/size {
|
||||
return total
|
||||
}
|
||||
return min((page-1)*size, total)
|
||||
}
|
||||
|
||||
func (a *AuthorRepository) findMatching(query domain.ListQuery, needle string) (domain.Page, error) {
|
||||
var candidates []entity.Author
|
||||
if err := a.db.Select("id", "name", "slug").Order("id DESC").Find(&candidates).Error; err != nil {
|
||||
return domain.Page{}, err
|
||||
}
|
||||
matching := make([]uint32, 0)
|
||||
for _, candidate := range candidates {
|
||||
if strings.Contains(foldForSearch(candidate.Name), needle) || strings.Contains(foldForSearch(candidate.Slug), needle) {
|
||||
matching = append(matching, candidate.ID)
|
||||
}
|
||||
}
|
||||
start := pageStart(query.Page, query.Size, len(matching))
|
||||
end := min(start+query.Size, len(matching))
|
||||
page := domain.Page{Items: []domain.Author{}, Total: len(matching)}
|
||||
if start == end {
|
||||
return page, nil
|
||||
}
|
||||
var found []entity.Author
|
||||
if err := a.db.Where("id IN ?", matching[start:end]).Order("id DESC").Find(&found).Error; err != nil {
|
||||
return domain.Page{}, err
|
||||
}
|
||||
items, err := a.toDomain(a.db, found)
|
||||
if err != nil {
|
||||
return domain.Page{}, err
|
||||
}
|
||||
page.Items = items
|
||||
return page, nil
|
||||
}
|
||||
|
||||
func (a *AuthorRepository) Get(id uint32) (domain.Author, error) {
|
||||
var model entity.Author
|
||||
if err := a.db.First(&model, id).Error; err != nil {
|
||||
return domain.Author{}, mapNotFoundErr(err, domain.ErrAuthorNotFound)
|
||||
}
|
||||
return a.loadOne(a.db, model)
|
||||
}
|
||||
|
||||
func (a *AuthorRepository) GetBySlug(slug string) (domain.Author, error) {
|
||||
var model entity.Author
|
||||
if err := a.db.Where("slug = ?", slug).First(&model).Error; err != nil {
|
||||
return domain.Author{}, mapNotFoundErr(err, domain.ErrAuthorNotFound)
|
||||
}
|
||||
return a.loadOne(a.db, model)
|
||||
}
|
||||
|
||||
func (a *AuthorRepository) GetByUserID(userID uint32) (domain.Author, error) {
|
||||
var model entity.Author
|
||||
if err := a.db.Where("user_id = ?", userID).First(&model).Error; err != nil {
|
||||
return domain.Author{}, mapNotFoundErr(err, domain.ErrAuthorNotFound)
|
||||
}
|
||||
return a.loadOne(a.db, model)
|
||||
}
|
||||
|
||||
func slugInUse(tx *gorm.DB, slug string, exceptID uint32) (bool, error) {
|
||||
var total int64
|
||||
err := tx.Model(&entity.Author{}).Where("slug = ? AND id <> ?", slug, exceptID).Count(&total).Error
|
||||
return total > 0, err
|
||||
}
|
||||
|
||||
func userInUse(tx *gorm.DB, userID *uint32, exceptID uint32) (bool, error) {
|
||||
if userID == nil {
|
||||
return false, nil
|
||||
}
|
||||
var total int64
|
||||
err := tx.Model(&entity.Author{}).Where("user_id = ? AND id <> ?", *userID, exceptID).Count(&total).Error
|
||||
return total > 0, err
|
||||
}
|
||||
|
||||
func ensureUnique(tx *gorm.DB, author domain.Author) error {
|
||||
taken, err := slugInUse(tx, author.Slug, author.ID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if taken {
|
||||
return domain.ErrSlugTaken
|
||||
}
|
||||
linked, err := userInUse(tx, author.UserID, author.ID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if linked {
|
||||
return domain.ErrUserAlreadyLinked
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (a *AuthorRepository) explainWriteFailure(author domain.Author, cause error) error {
|
||||
if err := ensureUnique(a.db, author); err != nil {
|
||||
return err
|
||||
}
|
||||
return cause
|
||||
}
|
||||
|
||||
func (a *AuthorRepository) Create(author domain.Author) (domain.Author, error) {
|
||||
model := mappers.AuthorToModel(author)
|
||||
model.ID = 0
|
||||
author.ID = 0
|
||||
err := a.db.Transaction(func(tx *gorm.DB) error {
|
||||
if err := ensureUnique(tx, author); err != nil {
|
||||
return err
|
||||
}
|
||||
return tx.Create(&model).Error
|
||||
})
|
||||
if err != nil {
|
||||
return domain.Author{}, a.explainWriteFailure(author, err)
|
||||
}
|
||||
return mappers.AuthorToDomain(model, 0), nil
|
||||
}
|
||||
|
||||
func (a *AuthorRepository) Update(author domain.Author) (domain.Author, error) {
|
||||
changes := map[string]any{
|
||||
"name": author.Name,
|
||||
"slug": author.Slug,
|
||||
"bio": author.Bio,
|
||||
"avatar_id": author.AvatarID,
|
||||
"website": author.Website,
|
||||
"social_links": mappers.AuthorToModel(author).SocialLinks,
|
||||
"user_id": author.UserID,
|
||||
}
|
||||
err := a.db.Transaction(func(tx *gorm.DB) error {
|
||||
if _, err := lockAuthor(tx, author.ID); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := ensureUnique(tx, author); err != nil {
|
||||
return err
|
||||
}
|
||||
return tx.Model(&entity.Author{}).Where("id = ?", author.ID).Updates(changes).Error
|
||||
})
|
||||
if err != nil {
|
||||
return domain.Author{}, a.explainWriteFailure(author, err)
|
||||
}
|
||||
return a.Get(author.ID)
|
||||
}
|
||||
|
||||
func lockAuthor(tx *gorm.DB, id uint32) (entity.Author, error) {
|
||||
var locked entity.Author
|
||||
if err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).First(&locked, id).Error; err != nil {
|
||||
return entity.Author{}, mapNotFoundErr(err, domain.ErrAuthorNotFound)
|
||||
}
|
||||
return locked, nil
|
||||
}
|
||||
|
||||
func (a *AuthorRepository) DeleteMovingCredits(id uint32, reassignTo *uint32) error {
|
||||
return a.db.Transaction(func(tx *gorm.DB) error {
|
||||
if _, err := lockAuthor(tx, id); err != nil {
|
||||
return err
|
||||
}
|
||||
if reassignTo == nil {
|
||||
credited, err := hasCredits(tx, id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if credited {
|
||||
return domain.ErrAuthorHasArticles
|
||||
}
|
||||
return removeAuthor(tx, id)
|
||||
}
|
||||
if _, err := lockAuthor(tx, *reassignTo); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := moveCredits(tx, id, *reassignTo); err != nil {
|
||||
return err
|
||||
}
|
||||
return removeAuthor(tx, id)
|
||||
})
|
||||
}
|
||||
|
||||
func (a *AuthorRepository) DeleteUncrediting(id uint32) error {
|
||||
return a.db.Transaction(func(tx *gorm.DB) error {
|
||||
if _, err := lockAuthor(tx, id); err != nil {
|
||||
return err
|
||||
}
|
||||
return removeAuthor(tx, id)
|
||||
})
|
||||
}
|
||||
|
||||
func hasCredits(tx *gorm.DB, id uint32) (bool, error) {
|
||||
var total int64
|
||||
err := tx.Model(&entity.ArticleAuthor{}).Where("author_id = ?", id).Count(&total).Error
|
||||
return total > 0, err
|
||||
}
|
||||
|
||||
func removeAuthor(tx *gorm.DB, id uint32) error {
|
||||
if err := tx.Where("author_id = ?", id).Delete(&entity.ArticleAuthor{}).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
return deleteOrNotFound(tx.Delete(&entity.Author{}, id), domain.ErrAuthorNotFound)
|
||||
}
|
||||
|
||||
func moveCredits(tx *gorm.DB, from uint32, to uint32) error {
|
||||
var alreadyCredited []uint32
|
||||
if err := tx.Model(&entity.ArticleAuthor{}).Where("author_id = ?", to).Pluck("article_id", &alreadyCredited).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
if len(alreadyCredited) > 0 {
|
||||
if err := tx.Where("author_id = ? AND article_id IN ?", from, alreadyCredited).Delete(&entity.ArticleAuthor{}).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return tx.Model(&entity.ArticleAuthor{}).Where("author_id = ?", from).UpdateColumn("author_id", to).Error
|
||||
}
|
||||
|
||||
type avatarTotal struct {
|
||||
AvatarID uint32
|
||||
Total int
|
||||
}
|
||||
|
||||
func (a *AuthorRepository) AvatarUsage() (map[uint32]int, error) {
|
||||
var totals []avatarTotal
|
||||
err := a.db.Model(&entity.Author{}).Select("avatar_id, COUNT(*) AS total").Where("avatar_id IS NOT NULL").Group("avatar_id").Scan(&totals).Error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
usage := make(map[uint32]int, len(totals))
|
||||
for _, total := range totals {
|
||||
usage[total.AvatarID] = total.Total
|
||||
}
|
||||
return usage, nil
|
||||
}
|
||||
|
||||
func (a *AuthorRepository) FindByAvatar(imageID uint32) ([]domain.Author, error) {
|
||||
var found []entity.Author
|
||||
if err := a.db.Where("avatar_id = ?", imageID).Order("id ASC").Find(&found).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return a.toDomain(a.db, found)
|
||||
}
|
||||
|
||||
func (a *AuthorRepository) ClearAvatar(imageID uint32) ([]uint32, error) {
|
||||
ids := []uint32{}
|
||||
err := a.db.Transaction(func(tx *gorm.DB) error {
|
||||
if err := tx.Model(&entity.Author{}).Where("avatar_id = ?", imageID).Order("id ASC").Pluck("id", &ids).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
if len(ids) == 0 {
|
||||
return nil
|
||||
}
|
||||
return tx.Model(&entity.Author{}).Where("id IN ?", ids).UpdateColumn("avatar_id", nil).Error
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return ids, nil
|
||||
}
|
||||
|
||||
func (a *AuthorRepository) AssignAvatar(authorIDs []uint32, imageID uint32) error {
|
||||
if len(authorIDs) == 0 {
|
||||
return nil
|
||||
}
|
||||
return a.db.Model(&entity.Author{}).Where("id IN ?", authorIDs).UpdateColumn("avatar_id", imageID).Error
|
||||
}
|
||||
|
||||
func (a *AuthorRepository) RepointAvatar(fromImageIDs []uint32, toImageID uint32) (int, error) {
|
||||
if len(fromImageIDs) == 0 {
|
||||
return 0, nil
|
||||
}
|
||||
result := a.db.Model(&entity.Author{}).Where("avatar_id IN ?", fromImageIDs).UpdateColumn("avatar_id", toImageID)
|
||||
if result.Error != nil {
|
||||
return 0, result.Error
|
||||
}
|
||||
return int(result.RowsAffected), nil
|
||||
}
|
||||
|
||||
var _ domain.Repository = &AuthorRepository{}
|
||||
@@ -0,0 +1,279 @@
|
||||
package persistence
|
||||
|
||||
import (
|
||||
domain "RenewCMS/internal/domain/site"
|
||||
"RenewCMS/internal/infrastructure/persistence/mappers"
|
||||
entity "RenewCMS/internal/infrastructure/persistence/models"
|
||||
"strings"
|
||||
|
||||
"gorm.io/gorm"
|
||||
"gorm.io/gorm/clause"
|
||||
)
|
||||
|
||||
type SiteRepository struct {
|
||||
db *gorm.DB
|
||||
}
|
||||
|
||||
func NewSiteRepository(db *gorm.DB) *SiteRepository {
|
||||
return &SiteRepository{db}
|
||||
}
|
||||
|
||||
type articleTotal struct {
|
||||
SiteID uint32
|
||||
Total int
|
||||
}
|
||||
|
||||
func (s *SiteRepository) articleCounts(db *gorm.DB) (map[uint32]int, error) {
|
||||
var totals []articleTotal
|
||||
err := db.Model(&entity.Article{}).Select("site_id, COUNT(*) AS total").Group("site_id").Scan(&totals).Error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
counts := make(map[uint32]int, len(totals))
|
||||
for _, total := range totals {
|
||||
counts[total.SiteID] = total.Total
|
||||
}
|
||||
return counts, nil
|
||||
}
|
||||
|
||||
func (s *SiteRepository) articleCount(db *gorm.DB, id uint32) (int, error) {
|
||||
var total int64
|
||||
if err := db.Model(&entity.Article{}).Where("site_id = ?", id).Count(&total).Error; err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return int(total), nil
|
||||
}
|
||||
|
||||
func (s *SiteRepository) List() ([]domain.Site, error) {
|
||||
var found []entity.Site
|
||||
if err := s.db.Order("is_default DESC, LOWER(name) ASC, id ASC").Find(&found).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
counts, err := s.articleCounts(s.db)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
sites := make([]domain.Site, 0, len(found))
|
||||
for _, model := range found {
|
||||
sites = append(sites, mappers.SiteToDomain(model, counts[model.ID]))
|
||||
}
|
||||
return sites, nil
|
||||
}
|
||||
|
||||
func (s *SiteRepository) Find(query domain.ListQuery) (domain.Page, error) {
|
||||
all, err := s.List()
|
||||
if err != nil {
|
||||
return domain.Page{}, err
|
||||
}
|
||||
matching := all
|
||||
if needle := foldForSearch(strings.TrimSpace(query.Q)); needle != "" {
|
||||
matching = make([]domain.Site, 0, len(all))
|
||||
for _, candidate := range all {
|
||||
if siteMatches(candidate, needle) {
|
||||
matching = append(matching, candidate)
|
||||
}
|
||||
}
|
||||
}
|
||||
page := domain.Page{Items: []domain.Site{}, Total: len(matching)}
|
||||
if query.Size <= 0 {
|
||||
page.Items = matching
|
||||
return page, nil
|
||||
}
|
||||
start := pageStart(max(query.Page, 1), query.Size, len(matching))
|
||||
end := min(start+query.Size, len(matching))
|
||||
page.Items = matching[start:end]
|
||||
return page, nil
|
||||
}
|
||||
|
||||
func siteMatches(candidate domain.Site, needle string) bool {
|
||||
for _, field := range []string{candidate.Name, candidate.Key, candidate.BaseURL} {
|
||||
if strings.Contains(foldForSearch(field), needle) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (s *SiteRepository) load(db *gorm.DB, model entity.Site) (domain.Site, error) {
|
||||
total, err := s.articleCount(db, model.ID)
|
||||
if err != nil {
|
||||
return domain.Site{}, err
|
||||
}
|
||||
return mappers.SiteToDomain(model, total), nil
|
||||
}
|
||||
|
||||
func (s *SiteRepository) Get(id uint32) (domain.Site, error) {
|
||||
var model entity.Site
|
||||
if err := s.db.First(&model, id).Error; err != nil {
|
||||
return domain.Site{}, mapNotFoundErr(err, domain.ErrSiteNotFound)
|
||||
}
|
||||
return s.load(s.db, model)
|
||||
}
|
||||
|
||||
func (s *SiteRepository) GetByKey(key string) (domain.Site, error) {
|
||||
var model entity.Site
|
||||
if err := s.db.Where("site_key = ?", key).First(&model).Error; err != nil {
|
||||
return domain.Site{}, mapNotFoundErr(err, domain.ErrSiteNotFound)
|
||||
}
|
||||
return s.load(s.db, model)
|
||||
}
|
||||
|
||||
func (s *SiteRepository) GetDefault() (domain.Site, error) {
|
||||
var model entity.Site
|
||||
if err := s.db.Where("is_default = ?", true).Order("id ASC").First(&model).Error; err != nil {
|
||||
return domain.Site{}, mapNotFoundErr(err, domain.ErrSiteNotFound)
|
||||
}
|
||||
return s.load(s.db, model)
|
||||
}
|
||||
|
||||
func (s *SiteRepository) Create(site domain.Site) (domain.Site, error) {
|
||||
model := mappers.SiteToModel(site)
|
||||
model.ID = 0
|
||||
err := s.db.Transaction(func(tx *gorm.DB) error {
|
||||
if model.IsDefault {
|
||||
if err := lockAllSites(tx); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := unflagDefaults(tx, 0); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return tx.Create(&model).Error
|
||||
})
|
||||
if err != nil {
|
||||
return domain.Site{}, s.explainKeyFailure(model.Key, err)
|
||||
}
|
||||
return mappers.SiteToDomain(model, 0), nil
|
||||
}
|
||||
|
||||
func (s *SiteRepository) explainKeyFailure(key string, cause error) error {
|
||||
if _, err := s.GetByKey(key); err == nil {
|
||||
return domain.ErrSiteKeyTaken
|
||||
}
|
||||
return cause
|
||||
}
|
||||
|
||||
func lockAllSites(tx *gorm.DB) error {
|
||||
var locked []entity.Site
|
||||
return tx.Clauses(clause.Locking{Strength: "UPDATE"}).Order("id ASC").Find(&locked).Error
|
||||
}
|
||||
|
||||
func lockSite(tx *gorm.DB, id uint32) (entity.Site, error) {
|
||||
var locked entity.Site
|
||||
if err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).First(&locked, id).Error; err != nil {
|
||||
return entity.Site{}, mapNotFoundErr(err, domain.ErrSiteNotFound)
|
||||
}
|
||||
return locked, nil
|
||||
}
|
||||
|
||||
func unflagDefaults(tx *gorm.DB, exceptID uint32) error {
|
||||
return tx.Model(&entity.Site{}).Where("is_default = ? AND id <> ?", true, exceptID).UpdateColumn("is_default", false).Error
|
||||
}
|
||||
|
||||
func (s *SiteRepository) Update(site domain.Site) (domain.Site, error) {
|
||||
changes := map[string]any{
|
||||
"name": site.Name,
|
||||
"base_url": site.BaseURL,
|
||||
"default_social_image_id": site.DefaultSocialImageID,
|
||||
"default_robots": site.DefaultRobots,
|
||||
"locale": site.Locale,
|
||||
"site_name": site.SiteName,
|
||||
"title_template": site.TitleTemplate,
|
||||
"default_description": site.DefaultDescription,
|
||||
}
|
||||
if _, err := s.Get(site.ID); err != nil {
|
||||
return domain.Site{}, err
|
||||
}
|
||||
if err := s.db.Model(&entity.Site{}).Where("id = ?", site.ID).Updates(changes).Error; err != nil {
|
||||
return domain.Site{}, err
|
||||
}
|
||||
return s.Get(site.ID)
|
||||
}
|
||||
|
||||
func (s *SiteRepository) SetDefault(id uint32) (domain.Site, error) {
|
||||
err := s.db.Transaction(func(tx *gorm.DB) error {
|
||||
if err := lockAllSites(tx); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := lockSite(tx, id); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := unflagDefaults(tx, id); err != nil {
|
||||
return err
|
||||
}
|
||||
return tx.Model(&entity.Site{}).Where("id = ?", id).UpdateColumn("is_default", true).Error
|
||||
})
|
||||
if err != nil {
|
||||
return domain.Site{}, err
|
||||
}
|
||||
return s.Get(id)
|
||||
}
|
||||
|
||||
func (s *SiteRepository) DeleteMovingArticles(id uint32, reassignTo *uint32) error {
|
||||
return s.db.Transaction(func(tx *gorm.DB) error {
|
||||
target, err := lockSite(tx, id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if target.IsDefault {
|
||||
return domain.ErrDefaultSite
|
||||
}
|
||||
remaining, err := s.articleCount(tx, id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if remaining > 0 && reassignTo == nil {
|
||||
return domain.ErrSiteHasArticles
|
||||
}
|
||||
if reassignTo != nil {
|
||||
if err := moveArticles(tx, id, *reassignTo); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return deleteOrNotFound(tx.Delete(&entity.Site{}, id), domain.ErrSiteNotFound)
|
||||
})
|
||||
}
|
||||
|
||||
func moveArticles(tx *gorm.DB, from uint32, to uint32) error {
|
||||
if _, err := lockSite(tx, to); err != nil {
|
||||
return err
|
||||
}
|
||||
return tx.Unscoped().Model(&entity.Article{}).Where("site_id = ?", from).UpdateColumn("site_id", to).Error
|
||||
}
|
||||
|
||||
func (s *SiteRepository) ClearImage(imageID uint32) ([]uint32, error) {
|
||||
ids := []uint32{}
|
||||
err := s.db.Transaction(func(tx *gorm.DB) error {
|
||||
if err := tx.Model(&entity.Site{}).Where("default_social_image_id = ?", imageID).Order("id ASC").Pluck("id", &ids).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
if len(ids) == 0 {
|
||||
return nil
|
||||
}
|
||||
return tx.Model(&entity.Site{}).Where("id IN ?", ids).UpdateColumn("default_social_image_id", nil).Error
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return ids, nil
|
||||
}
|
||||
|
||||
func (s *SiteRepository) AssignImage(siteIDs []uint32, imageID uint32) error {
|
||||
if len(siteIDs) == 0 {
|
||||
return nil
|
||||
}
|
||||
return s.db.Model(&entity.Site{}).Where("id IN ?", siteIDs).UpdateColumn("default_social_image_id", imageID).Error
|
||||
}
|
||||
|
||||
func (s *SiteRepository) RepointImage(fromImageIDs []uint32, toImageID uint32) (int, error) {
|
||||
if len(fromImageIDs) == 0 {
|
||||
return 0, nil
|
||||
}
|
||||
result := s.db.Model(&entity.Site{}).Where("default_social_image_id IN ?", fromImageIDs).UpdateColumn("default_social_image_id", toImageID)
|
||||
if result.Error != nil {
|
||||
return 0, result.Error
|
||||
}
|
||||
return int(result.RowsAffected), nil
|
||||
}
|
||||
|
||||
var _ domain.Repository = &SiteRepository{}
|
||||
@@ -0,0 +1,130 @@
|
||||
package useCases
|
||||
|
||||
import (
|
||||
"RenewCMS/internal/domain/article"
|
||||
"RenewCMS/internal/domain/image"
|
||||
"RenewCMS/internal/domain/site"
|
||||
)
|
||||
|
||||
type CheckArticleSEOUseCase struct {
|
||||
articleRepository article.Repository
|
||||
sites site.Repository
|
||||
images image.Repository
|
||||
}
|
||||
|
||||
type CheckArticleSEOCommand struct {
|
||||
Body *string
|
||||
Slug *string
|
||||
Excerpt *string
|
||||
SEOTitle *string
|
||||
SEODescription *string
|
||||
CoverImageID article.Nullable[uint32]
|
||||
CoverImageAlt *string
|
||||
SocialTitle *string
|
||||
SocialDescription *string
|
||||
SocialImageID article.Nullable[uint32]
|
||||
CanonicalURL *string
|
||||
Noindex *bool
|
||||
SEODismissed *[]string
|
||||
}
|
||||
|
||||
func NewCheckArticleSEOUseCase(articleRepository article.Repository, sites site.Repository, images image.Repository) *CheckArticleSEOUseCase {
|
||||
return &CheckArticleSEOUseCase{articleRepository: articleRepository, sites: sites, images: images}
|
||||
}
|
||||
|
||||
func (u *CheckArticleSEOUseCase) Check(id uint32, command CheckArticleSEOCommand) (article.SEOCheck, error) {
|
||||
saved, err := u.articleRepository.Get(id)
|
||||
if err != nil {
|
||||
return article.SEOCheck{}, err
|
||||
}
|
||||
if err := u.validate(command); err != nil {
|
||||
return article.SEOCheck{}, err
|
||||
}
|
||||
owner, err := u.sites.Get(saved.SiteID)
|
||||
if err != nil {
|
||||
return article.SEOCheck{}, err
|
||||
}
|
||||
candidate := command.applyTo(saved)
|
||||
slugCheck, err := u.checkSlug(candidate)
|
||||
if err != nil {
|
||||
return article.SEOCheck{}, err
|
||||
}
|
||||
assessment := assessSEO(candidate, owner)
|
||||
return article.SEOCheck{Status: assessment.Status, Suggestions: assessment.Suggestions, Slug: slugCheck}, nil
|
||||
}
|
||||
|
||||
func (u *CheckArticleSEOUseCase) validate(command CheckArticleSEOCommand) error {
|
||||
if command.Slug != nil && *command.Slug != "" && !article.IsValidSlug(*command.Slug) {
|
||||
return article.ErrInvalidSlug
|
||||
}
|
||||
if command.CanonicalURL != nil {
|
||||
if err := article.ValidateCanonicalURL(*command.CanonicalURL); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if command.CoverImageID.Set {
|
||||
if err := ensureImageExists(u.images, command.CoverImageID.Value); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if command.SocialImageID.Set {
|
||||
return ensureImageExists(u.images, command.SocialImageID.Value)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func overrideText(current string, override *string) string {
|
||||
if override == nil {
|
||||
return current
|
||||
}
|
||||
return *override
|
||||
}
|
||||
|
||||
func overrideImage(current *uint32, override article.Nullable[uint32]) *uint32 {
|
||||
if override.Set {
|
||||
return override.Value
|
||||
}
|
||||
return current
|
||||
}
|
||||
|
||||
func (c CheckArticleSEOCommand) applyTo(saved article.Article) article.Article {
|
||||
saved.Body = overrideText(saved.Body, c.Body)
|
||||
saved.Excerpt = overrideText(saved.Excerpt, c.Excerpt)
|
||||
saved.SEOTitle = overrideText(saved.SEOTitle, c.SEOTitle)
|
||||
saved.SEODescription = overrideText(saved.SEODescription, c.SEODescription)
|
||||
saved.CoverImageID = overrideImage(saved.CoverImageID, c.CoverImageID)
|
||||
saved.CoverImageAlt = overrideText(saved.CoverImageAlt, c.CoverImageAlt)
|
||||
saved.SocialTitle = overrideText(saved.SocialTitle, c.SocialTitle)
|
||||
saved.SocialDescription = overrideText(saved.SocialDescription, c.SocialDescription)
|
||||
saved.SocialImageID = overrideImage(saved.SocialImageID, c.SocialImageID)
|
||||
saved.CanonicalURL = overrideText(saved.CanonicalURL, c.CanonicalURL)
|
||||
if c.Noindex != nil {
|
||||
saved.Noindex = *c.Noindex
|
||||
}
|
||||
if c.SEODismissed != nil {
|
||||
saved.SEODismissed = article.NormalizeDismissed(*c.SEODismissed)
|
||||
}
|
||||
if c.Slug != nil {
|
||||
saved.Slug = *c.Slug
|
||||
if saved.Slug == "" {
|
||||
saved.Slug = article.GenerateSlug(saved.Title)
|
||||
}
|
||||
}
|
||||
return saved
|
||||
}
|
||||
|
||||
func (u *CheckArticleSEOUseCase) checkSlug(candidate article.Article) (article.SEOSlugCheck, error) {
|
||||
available := article.SEOSlugCheck{Available: true}
|
||||
if candidate.Slug == "" {
|
||||
return available, nil
|
||||
}
|
||||
taken, err := u.articleRepository.SlugTaken(candidate.SiteID, candidate.Slug, candidate.ID)
|
||||
if err != nil || !taken {
|
||||
return available, err
|
||||
}
|
||||
suggestion, err := freeSlug(u.articleRepository, candidate.SiteID, candidate.Slug, candidate.ID, firstSuggestedAttempt)
|
||||
if err != nil {
|
||||
return article.SEOSlugCheck{}, err
|
||||
}
|
||||
return article.SEOSlugCheck{Suggestion: &suggestion}, nil
|
||||
}
|
||||
@@ -3,23 +3,48 @@ package useCases
|
||||
import (
|
||||
"RenewCMS/internal/domain/article"
|
||||
"RenewCMS/internal/domain/audit"
|
||||
"RenewCMS/internal/domain/author"
|
||||
"RenewCMS/internal/domain/site"
|
||||
"context"
|
||||
"errors"
|
||||
)
|
||||
|
||||
type CreateArticleUseCase struct {
|
||||
articleRepository article.Repository
|
||||
bodyRenderer article.BodyRenderer
|
||||
recorder audit.Recorder
|
||||
sites site.Repository
|
||||
authors author.Repository
|
||||
}
|
||||
|
||||
type CreateArticleCommand struct {
|
||||
Title string
|
||||
Body string
|
||||
Format article.BodyFormat
|
||||
Title string
|
||||
Body string
|
||||
Format article.BodyFormat
|
||||
CreatedBy uint32
|
||||
}
|
||||
|
||||
func NewCreateArticleUseCase(articleRepository article.Repository, bodyRenderer article.BodyRenderer, recorder audit.Recorder) *CreateArticleUseCase {
|
||||
return &CreateArticleUseCase{articleRepository, bodyRenderer, recorder}
|
||||
func NewCreateArticleUseCase(articleRepository article.Repository, bodyRenderer article.BodyRenderer, recorder audit.Recorder, sites site.Repository, authors author.Repository) *CreateArticleUseCase {
|
||||
return &CreateArticleUseCase{articleRepository: articleRepository, bodyRenderer: bodyRenderer, recorder: recorder, sites: sites, authors: authors}
|
||||
}
|
||||
|
||||
func (g *CreateArticleUseCase) defaultSiteID() (uint32, error) {
|
||||
defaultSite, err := g.sites.GetDefault()
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return defaultSite.ID, nil
|
||||
}
|
||||
|
||||
func (g *CreateArticleUseCase) creatorBylines(userID uint32) ([]author.Byline, error) {
|
||||
found, err := g.authors.GetByUserID(userID)
|
||||
if errors.Is(err, author.ErrAuthorNotFound) {
|
||||
return []author.Byline{}, nil
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return []author.Byline{found.Byline()}, nil
|
||||
}
|
||||
|
||||
func (g *CreateArticleUseCase) CreateArticle(ctx context.Context, createArticle CreateArticleCommand) (article.Article, error) {
|
||||
@@ -29,10 +54,25 @@ func (g *CreateArticleUseCase) CreateArticle(ctx context.Context, createArticle
|
||||
return article.Article{}, err
|
||||
}
|
||||
|
||||
created, err := g.articleRepository.Create(article.Article{
|
||||
Title: createArticle.Title,
|
||||
Body: createArticle.Body,
|
||||
IsOnline: false,
|
||||
siteID, err := g.defaultSiteID()
|
||||
if err != nil {
|
||||
recordFailure(ctx, g.recorder, event, err)
|
||||
return article.Article{}, err
|
||||
}
|
||||
|
||||
creditedAuthors, err := g.creatorBylines(createArticle.CreatedBy)
|
||||
if err != nil {
|
||||
recordFailure(ctx, g.recorder, event, err)
|
||||
return article.Article{}, err
|
||||
}
|
||||
|
||||
created, err := g.createWithFreeSlug(article.Article{
|
||||
Title: createArticle.Title,
|
||||
Body: createArticle.Body,
|
||||
IsOnline: false,
|
||||
SiteID: siteID,
|
||||
Authors: creditedAuthors,
|
||||
SEODismissed: []string{},
|
||||
})
|
||||
if err != nil {
|
||||
recordFailure(ctx, g.recorder, event, err)
|
||||
@@ -44,6 +84,22 @@ func (g *CreateArticleUseCase) CreateArticle(ctx context.Context, createArticle
|
||||
return renderArticle(g.bodyRenderer, created, createArticle.Format)
|
||||
}
|
||||
|
||||
func (g *CreateArticleUseCase) createWithFreeSlug(draft article.Article) (article.Article, error) {
|
||||
base := article.GenerateSlug(draft.Title)
|
||||
for attempt := 0; attempt < maxCreateSlugAttempts; attempt++ {
|
||||
slug, err := freeSlug(g.articleRepository, draft.SiteID, base, 0, firstSlugAttempt)
|
||||
if err != nil {
|
||||
return article.Article{}, err
|
||||
}
|
||||
draft.Slug = slug
|
||||
created, err := g.articleRepository.Create(draft)
|
||||
if !isSlugTakenError(err) {
|
||||
return created, err
|
||||
}
|
||||
}
|
||||
return article.Article{}, article.ErrSlugTaken
|
||||
}
|
||||
|
||||
func articleTarget(a article.Article) audit.Target {
|
||||
return audit.NewTarget(audit.TargetArticle, a.ID, a.Title)
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
package useCases
|
||||
|
||||
import (
|
||||
"RenewCMS/internal/domain/audit"
|
||||
"RenewCMS/internal/domain/author"
|
||||
"RenewCMS/internal/domain/image"
|
||||
"RenewCMS/internal/domain/user"
|
||||
"context"
|
||||
"strings"
|
||||
)
|
||||
|
||||
type CreateAuthorUseCase struct {
|
||||
authors author.Repository
|
||||
users user.Repository
|
||||
images image.Repository
|
||||
recorder audit.Recorder
|
||||
}
|
||||
|
||||
type CreateAuthorCommand struct {
|
||||
Name string
|
||||
Slug string
|
||||
Bio string
|
||||
AvatarID *uint32
|
||||
Website *string
|
||||
SocialLinks []author.SocialLink
|
||||
UserID *uint32
|
||||
}
|
||||
|
||||
func NewCreateAuthorUseCase(authors author.Repository, users user.Repository, images image.Repository, recorder audit.Recorder) *CreateAuthorUseCase {
|
||||
return &CreateAuthorUseCase{authors: authors, users: users, images: images, recorder: recorder}
|
||||
}
|
||||
|
||||
func (u *CreateAuthorUseCase) Create(ctx context.Context, command CreateAuthorCommand) (author.Author, error) {
|
||||
command.Name = strings.TrimSpace(command.Name)
|
||||
event := audit.NewEvent(audit.ActionAuthorCreate, audit.CategoryAuthors)
|
||||
event.Target = audit.Target{Type: audit.TargetAuthor, Name: command.Name}
|
||||
created, err := u.create(command)
|
||||
if err != nil {
|
||||
recordFailure(ctx, u.recorder, event, err)
|
||||
return author.Author{}, err
|
||||
}
|
||||
event.Target = authorTarget(created)
|
||||
u.recorder.Record(ctx, event)
|
||||
return withUserEmail(u.users, created), nil
|
||||
}
|
||||
|
||||
func (u *CreateAuthorUseCase) create(command CreateAuthorCommand) (author.Author, error) {
|
||||
website, err := validateAuthorContent(command.Bio, command.Website, command.SocialLinks)
|
||||
if err != nil {
|
||||
return author.Author{}, err
|
||||
}
|
||||
if err := ensureImageExists(u.images, command.AvatarID); err != nil {
|
||||
return author.Author{}, err
|
||||
}
|
||||
if command.UserID != nil {
|
||||
if err := ensureUserCanBeLinked(u.users, u.authors, *command.UserID); err != nil {
|
||||
return author.Author{}, err
|
||||
}
|
||||
}
|
||||
slug, err := u.slugFor(command)
|
||||
if err != nil {
|
||||
return author.Author{}, err
|
||||
}
|
||||
links := command.SocialLinks
|
||||
if links == nil {
|
||||
links = []author.SocialLink{}
|
||||
}
|
||||
return u.authors.Create(author.Author{
|
||||
Name: command.Name,
|
||||
Slug: slug,
|
||||
Bio: command.Bio,
|
||||
AvatarID: command.AvatarID,
|
||||
Website: website,
|
||||
SocialLinks: links,
|
||||
UserID: command.UserID,
|
||||
IsLinked: command.UserID != nil,
|
||||
})
|
||||
}
|
||||
|
||||
func (u *CreateAuthorUseCase) slugFor(command CreateAuthorCommand) (string, error) {
|
||||
slug := command.Slug
|
||||
if slug == "" {
|
||||
slug = author.GenerateSlug(command.Name)
|
||||
}
|
||||
if !author.IsValidSlug(slug) {
|
||||
return "", author.ErrInvalidSlug
|
||||
}
|
||||
taken, err := isSlugTaken(u.authors, slug)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if taken {
|
||||
return "", author.ErrSlugTaken
|
||||
}
|
||||
return slug, nil
|
||||
}
|
||||
|
||||
func validateAuthorContent(bio string, website *string, links []author.SocialLink) (*string, error) {
|
||||
if err := author.ValidateBio(bio); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := author.ValidateLinks(links); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return author.NormalizeWebsite(website)
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
package useCases
|
||||
|
||||
import (
|
||||
"RenewCMS/internal/domain/audit"
|
||||
"RenewCMS/internal/domain/author"
|
||||
"RenewCMS/internal/domain/user"
|
||||
"context"
|
||||
"errors"
|
||||
"strings"
|
||||
)
|
||||
|
||||
const maxOwnSlugAttempts = 50
|
||||
|
||||
type MyAuthorCreated struct {
|
||||
Author author.Author
|
||||
SlugAdjusted bool
|
||||
}
|
||||
|
||||
type CreateMyAuthorUseCase struct {
|
||||
authors author.Repository
|
||||
users user.Repository
|
||||
recorder audit.Recorder
|
||||
}
|
||||
|
||||
func NewCreateMyAuthorUseCase(authors author.Repository, users user.Repository, recorder audit.Recorder) *CreateMyAuthorUseCase {
|
||||
return &CreateMyAuthorUseCase{authors: authors, users: users, recorder: recorder}
|
||||
}
|
||||
|
||||
func (u *CreateMyAuthorUseCase) Create(ctx context.Context, userID uint32) (MyAuthorCreated, error) {
|
||||
caller, err := u.users.Get(userID)
|
||||
if err != nil {
|
||||
return MyAuthorCreated{}, err
|
||||
}
|
||||
name := authorNameOf(caller)
|
||||
event := audit.NewEvent(audit.ActionAuthorCreate, audit.CategoryAuthors)
|
||||
event.Target = audit.Target{Type: audit.TargetAuthor, Name: name}
|
||||
created, err := u.create(caller, name)
|
||||
if err != nil {
|
||||
recordFailure(ctx, u.recorder, event, err)
|
||||
return MyAuthorCreated{}, err
|
||||
}
|
||||
event.Target = authorTarget(created)
|
||||
u.recorder.Record(ctx, event)
|
||||
return MyAuthorCreated{Author: created, SlugAdjusted: created.Slug != author.GenerateSlug(name)}, nil
|
||||
}
|
||||
|
||||
func authorNameOf(caller user.User) string {
|
||||
name := strings.TrimSpace(caller.DisplayName)
|
||||
if name == "" {
|
||||
name = strings.TrimSpace(caller.Username)
|
||||
}
|
||||
runes := []rune(name)
|
||||
return string(runes[:min(len(runes), author.MaxNameRunes)])
|
||||
}
|
||||
|
||||
func (u *CreateMyAuthorUseCase) create(caller user.User, name string) (author.Author, error) {
|
||||
_, err := u.authors.GetByUserID(caller.ID)
|
||||
if err == nil {
|
||||
return author.Author{}, author.ErrUserAlreadyLinked
|
||||
}
|
||||
if !errors.Is(err, author.ErrAuthorNotFound) {
|
||||
return author.Author{}, err
|
||||
}
|
||||
return u.createWithFreeSlug(caller.ID, name)
|
||||
}
|
||||
|
||||
func (u *CreateMyAuthorUseCase) createWithFreeSlug(userID uint32, name string) (author.Author, error) {
|
||||
base := author.GenerateSlug(name)
|
||||
for attempt := 1; attempt <= maxOwnSlugAttempts; attempt++ {
|
||||
slug := author.SlugWithSuffix(base, attempt)
|
||||
taken, err := isSlugTaken(u.authors, slug)
|
||||
if err != nil {
|
||||
return author.Author{}, err
|
||||
}
|
||||
if taken {
|
||||
continue
|
||||
}
|
||||
created, err := u.authors.Create(author.Author{Name: name, Slug: slug, SocialLinks: []author.SocialLink{}, UserID: &userID, IsLinked: true})
|
||||
if errors.Is(err, author.ErrSlugTaken) {
|
||||
continue
|
||||
}
|
||||
return created, err
|
||||
}
|
||||
return author.Author{}, author.ErrSlugTaken
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
package useCases
|
||||
|
||||
import (
|
||||
"RenewCMS/internal/domain/audit"
|
||||
"RenewCMS/internal/domain/image"
|
||||
"RenewCMS/internal/domain/site"
|
||||
"context"
|
||||
)
|
||||
|
||||
type CreateSiteUseCase struct {
|
||||
siteRepository site.Repository
|
||||
imageRepository image.Repository
|
||||
recorder audit.Recorder
|
||||
}
|
||||
|
||||
type CreateSiteCommand struct {
|
||||
Name string
|
||||
Key string
|
||||
BaseURL string
|
||||
DefaultRobots string
|
||||
Locale *string
|
||||
DefaultSocialImageID *uint32
|
||||
IsDefault bool
|
||||
SiteName string
|
||||
TitleTemplate *string
|
||||
DefaultDescription string
|
||||
}
|
||||
|
||||
func NewCreateSiteUseCase(siteRepository site.Repository, imageRepository image.Repository, recorder audit.Recorder) *CreateSiteUseCase {
|
||||
return &CreateSiteUseCase{siteRepository, imageRepository, recorder}
|
||||
}
|
||||
|
||||
func (u *CreateSiteUseCase) Create(ctx context.Context, command CreateSiteCommand) (site.Site, error) {
|
||||
event := audit.NewEvent(audit.ActionSiteCreate, audit.CategorySites)
|
||||
event.Target = audit.Target{Type: audit.TargetSite, Name: command.Name}
|
||||
created, err := u.create(command)
|
||||
if err != nil {
|
||||
recordFailure(ctx, u.recorder, event, err)
|
||||
return site.Site{}, err
|
||||
}
|
||||
event.Target = siteTarget(created)
|
||||
u.recorder.Record(ctx, event)
|
||||
return created, nil
|
||||
}
|
||||
|
||||
func (u *CreateSiteUseCase) create(command CreateSiteCommand) (site.Site, error) {
|
||||
baseURL, err := site.NormalizeBaseURL(command.BaseURL)
|
||||
if err != nil {
|
||||
return site.Site{}, err
|
||||
}
|
||||
locale, err := site.NormalizeLocale(command.Locale)
|
||||
if err != nil {
|
||||
return site.Site{}, err
|
||||
}
|
||||
if err := ensureImageExists(u.imageRepository, command.DefaultSocialImageID); err != nil {
|
||||
return site.Site{}, err
|
||||
}
|
||||
titleTemplate, err := resolveTitleTemplate(command.TitleTemplate)
|
||||
if err != nil {
|
||||
return site.Site{}, err
|
||||
}
|
||||
taken, err := isKeyTaken(u.siteRepository, command.Key)
|
||||
if err != nil {
|
||||
return site.Site{}, err
|
||||
}
|
||||
if taken {
|
||||
return site.Site{}, site.ErrSiteKeyTaken
|
||||
}
|
||||
robots := command.DefaultRobots
|
||||
if robots == "" {
|
||||
robots = site.RobotsIndex
|
||||
}
|
||||
return u.siteRepository.Create(site.Site{
|
||||
Name: command.Name,
|
||||
Key: command.Key,
|
||||
BaseURL: baseURL,
|
||||
DefaultSocialImageID: command.DefaultSocialImageID,
|
||||
DefaultRobots: robots,
|
||||
Locale: locale,
|
||||
IsDefault: command.IsDefault,
|
||||
SiteName: command.SiteName,
|
||||
TitleTemplate: titleTemplate,
|
||||
DefaultDescription: command.DefaultDescription,
|
||||
})
|
||||
}
|
||||
|
||||
func resolveTitleTemplate(requested *string) (string, error) {
|
||||
if requested == nil {
|
||||
return site.DefaultTitleTemplate, nil
|
||||
}
|
||||
if err := site.ValidateTitleTemplate(*requested); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return *requested, nil
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
package useCases
|
||||
|
||||
import (
|
||||
"RenewCMS/internal/domain/audit"
|
||||
"RenewCMS/internal/domain/author"
|
||||
"context"
|
||||
)
|
||||
|
||||
type ReassignMode int
|
||||
|
||||
const (
|
||||
ReassignAbsent ReassignMode = iota
|
||||
ReassignNone
|
||||
ReassignToAuthor
|
||||
ReassignMalformed
|
||||
)
|
||||
|
||||
type Reassignment struct {
|
||||
Mode ReassignMode
|
||||
Destination uint32
|
||||
}
|
||||
|
||||
type DeleteAuthorUseCase struct {
|
||||
authors author.Repository
|
||||
recorder audit.Recorder
|
||||
}
|
||||
|
||||
func NewDeleteAuthorUseCase(authors author.Repository, recorder audit.Recorder) *DeleteAuthorUseCase {
|
||||
return &DeleteAuthorUseCase{authors: authors, recorder: recorder}
|
||||
}
|
||||
|
||||
func (u *DeleteAuthorUseCase) Delete(ctx context.Context, id uint32, reassignment Reassignment) error {
|
||||
target, err := u.authors.Get(id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
event := audit.NewEvent(audit.ActionAuthorDelete, audit.CategoryAuthors)
|
||||
event.Target = authorTarget(target)
|
||||
if err := u.delete(target, reassignment); err != nil {
|
||||
recordFailure(ctx, u.recorder, event, err)
|
||||
return err
|
||||
}
|
||||
u.recorder.Record(ctx, event)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (u *DeleteAuthorUseCase) delete(target author.Author, reassignment Reassignment) error {
|
||||
if reassignment.Mode == ReassignNone {
|
||||
return u.authors.DeleteUncrediting(target.ID)
|
||||
}
|
||||
if target.ArticleCount == 0 {
|
||||
return u.authors.DeleteMovingCredits(target.ID, nil)
|
||||
}
|
||||
destination, err := u.destination(target, reassignment)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return u.authors.DeleteMovingCredits(target.ID, &destination)
|
||||
}
|
||||
|
||||
func (u *DeleteAuthorUseCase) destination(target author.Author, reassignment Reassignment) (uint32, error) {
|
||||
switch reassignment.Mode {
|
||||
case ReassignAbsent:
|
||||
return 0, author.ErrAuthorHasArticles
|
||||
case ReassignMalformed:
|
||||
return 0, author.ErrInvalidReassign
|
||||
}
|
||||
if reassignment.Destination == 0 || reassignment.Destination == target.ID {
|
||||
return 0, author.ErrInvalidReassign
|
||||
}
|
||||
if _, err := u.authors.Get(reassignment.Destination); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return reassignment.Destination, nil
|
||||
}
|
||||
@@ -1,19 +1,57 @@
|
||||
package useCases
|
||||
|
||||
import (
|
||||
"RenewCMS/internal/domain/article"
|
||||
"RenewCMS/internal/domain/audit"
|
||||
"RenewCMS/internal/domain/author"
|
||||
"RenewCMS/internal/domain/image"
|
||||
"RenewCMS/internal/domain/site"
|
||||
"context"
|
||||
"log"
|
||||
)
|
||||
|
||||
type DeleteMediaUseCase struct {
|
||||
imageRepository image.Repository
|
||||
remover mediaRemover
|
||||
recorder audit.Recorder
|
||||
sites site.Repository
|
||||
authors author.Repository
|
||||
articles article.Repository
|
||||
}
|
||||
|
||||
func NewDeleteMediaUseCase(imageRepository image.Repository, storage image.Storage, variantFiles image.VariantFileRepository, recorder audit.Recorder) *DeleteMediaUseCase {
|
||||
return &DeleteMediaUseCase{imageRepository, newMediaRemover(imageRepository, storage, variantFiles), recorder}
|
||||
func NewDeleteMediaUseCase(imageRepository image.Repository, storage image.Storage, variantFiles image.VariantFileRepository, recorder audit.Recorder, sites site.Repository, authors author.Repository, articles article.Repository) *DeleteMediaUseCase {
|
||||
return &DeleteMediaUseCase{imageRepository: imageRepository, remover: newMediaRemover(imageRepository, storage, variantFiles), recorder: recorder, sites: sites, authors: authors, articles: articles}
|
||||
}
|
||||
|
||||
func logCompensation(step string, err error) {
|
||||
if err != nil {
|
||||
log.Println("media compensation failed to", step+":", err)
|
||||
}
|
||||
}
|
||||
|
||||
func (u *DeleteMediaUseCase) removeClearingSites(img image.Image) error {
|
||||
clearedSites, err := u.sites.ClearImage(img.ID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
clearedAuthors, err := u.authors.ClearAvatar(img.ID)
|
||||
if err != nil {
|
||||
logCompensation("restore site images", u.sites.AssignImage(clearedSites, img.ID))
|
||||
return err
|
||||
}
|
||||
clearedArticles, err := u.articles.ClearImage(img.ID)
|
||||
if err != nil {
|
||||
logCompensation("restore site images", u.sites.AssignImage(clearedSites, img.ID))
|
||||
logCompensation("restore author avatars", u.authors.AssignAvatar(clearedAuthors, img.ID))
|
||||
return err
|
||||
}
|
||||
if err := u.remover.remove(img); err != nil {
|
||||
logCompensation("restore site images", u.sites.AssignImage(clearedSites, img.ID))
|
||||
logCompensation("restore author avatars", u.authors.AssignAvatar(clearedAuthors, img.ID))
|
||||
logCompensation("restore article images", u.articles.RestoreImage(clearedArticles, img.ID))
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (u *DeleteMediaUseCase) Delete(ctx context.Context, id uint32) error {
|
||||
@@ -24,7 +62,7 @@ func (u *DeleteMediaUseCase) Delete(ctx context.Context, id uint32) error {
|
||||
|
||||
event := audit.NewEvent(audit.ActionMediaDelete, audit.CategoryMedia)
|
||||
event.Target = imageTarget(img)
|
||||
if err := u.remover.remove(img); err != nil {
|
||||
if err := u.removeClearingSites(img); err != nil {
|
||||
recordFailure(ctx, u.recorder, event, err)
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
package useCases
|
||||
|
||||
import (
|
||||
"RenewCMS/internal/domain/audit"
|
||||
"RenewCMS/internal/domain/site"
|
||||
"context"
|
||||
)
|
||||
|
||||
type DeleteSiteUseCase struct {
|
||||
siteRepository site.Repository
|
||||
recorder audit.Recorder
|
||||
}
|
||||
|
||||
type DeleteSiteCommand struct {
|
||||
ID uint32
|
||||
ReassignTo *uint32
|
||||
ReassignInvalid bool
|
||||
}
|
||||
|
||||
func NewDeleteSiteUseCase(siteRepository site.Repository, recorder audit.Recorder) *DeleteSiteUseCase {
|
||||
return &DeleteSiteUseCase{siteRepository, recorder}
|
||||
}
|
||||
|
||||
func (u *DeleteSiteUseCase) Delete(ctx context.Context, command DeleteSiteCommand) error {
|
||||
target, err := u.siteRepository.Get(command.ID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
event := audit.NewEvent(audit.ActionSiteDelete, audit.CategorySites)
|
||||
event.Target = siteTarget(target)
|
||||
if err := u.delete(target, command); err != nil {
|
||||
recordFailure(ctx, u.recorder, event, err)
|
||||
return err
|
||||
}
|
||||
u.recorder.Record(ctx, event)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (u *DeleteSiteUseCase) delete(target site.Site, command DeleteSiteCommand) error {
|
||||
if target.IsDefault {
|
||||
return site.ErrDefaultSite
|
||||
}
|
||||
if target.ArticleCount == 0 {
|
||||
return u.siteRepository.DeleteMovingArticles(target.ID, nil)
|
||||
}
|
||||
destination, err := u.destination(target, command)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return u.siteRepository.DeleteMovingArticles(target.ID, &destination)
|
||||
}
|
||||
|
||||
func (u *DeleteSiteUseCase) destination(target site.Site, command DeleteSiteCommand) (uint32, error) {
|
||||
if command.ReassignInvalid {
|
||||
return 0, site.ErrInvalidReassign
|
||||
}
|
||||
if command.ReassignTo == nil {
|
||||
return 0, site.ErrSiteHasArticles
|
||||
}
|
||||
if *command.ReassignTo == 0 || *command.ReassignTo == target.ID {
|
||||
return 0, site.ErrInvalidReassign
|
||||
}
|
||||
if _, err := u.siteRepository.Get(*command.ReassignTo); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return *command.ReassignTo, nil
|
||||
}
|
||||
Loaded 100 of 555 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user