Compare commits

..
68 changed files with 6600 additions and 15 deletions

No files matched your search

+1
View File
@@ -51,6 +51,7 @@ task dev # API with hot reload + Vite HMR → http://localhost:51
| [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/custom-content-types.md](docs/custom-content-types.md) | Custom content types: layering, phase 1 limitations and their fix path |
| [docs/image-variants.md](docs/image-variants.md) | Image variants and their cache |
| [docs/release-notes.md](docs/release-notes.md) | Release notes format, the published releases and how to publish one |
+32
View File
@@ -5,6 +5,8 @@ import (
domainArticle "RenewCMS/internal/domain/article"
domainAudit "RenewCMS/internal/domain/audit"
domainAuthor "RenewCMS/internal/domain/author"
domainContentType "RenewCMS/internal/domain/contenttype"
domainEntry "RenewCMS/internal/domain/entry"
domainImage "RenewCMS/internal/domain/image"
domainInvite "RenewCMS/internal/domain/invite"
domainMail "RenewCMS/internal/domain/mail"
@@ -63,6 +65,19 @@ type UseCases struct {
UpdateSiteUseCase *useCases.UpdateSiteUseCase
SetDefaultSiteUseCase *useCases.SetDefaultSiteUseCase
DeleteSiteUseCase *useCases.DeleteSiteUseCase
CreateContentTypeUseCase *useCases.CreateContentTypeUseCase
ListContentTypesUseCase *useCases.ListContentTypesUseCase
GetContentTypeUseCase *useCases.GetContentTypeUseCase
UpdateContentTypeUseCase *useCases.UpdateContentTypeUseCase
DeleteContentTypeUseCase *useCases.DeleteContentTypeUseCase
ListBuiltinTypesUseCase *useCases.ListBuiltinTypesUseCase
GetBuiltinTypeUseCase *useCases.GetBuiltinTypeUseCase
LookupUserNamesUseCase *useCases.LookupUserNamesUseCase
CreateEntryUseCase *useCases.CreateEntryUseCase
GetEntryUseCase *useCases.GetEntryUseCase
ListEntriesUseCase *useCases.ListEntriesUseCase
UpdateEntryUseCase *useCases.UpdateEntryUseCase
DeleteEntryUseCase *useCases.DeleteEntryUseCase
GetUserUseCase *useCases.GetUserUseCase
CreateUserUseCase *useCases.CreateUserUseCase
AuthenticateUserUseCase *useCases.AuthenticateUserUseCase
@@ -140,6 +155,8 @@ func (c *UseCases) RunSchedulers(ctx context.Context) {
type Repositories struct {
ArticleRepo domainArticle.Repository
SiteRepo domainSite.Repository
ContentTypeRepo domainContentType.Repository
EntryRepo domainEntry.Repository
AuthorRepo domainAuthor.Repository
UserRepo domainUser.Repository
ImageRepo domainImage.Repository
@@ -280,6 +297,8 @@ func getRepositories(connection *database.Connection, settings config.Settings)
return &Repositories{
ArticleRepo: persistence.NewArticleRepository(db),
SiteRepo: persistence.NewSiteRepository(db),
ContentTypeRepo: persistence.NewContentTypeRepository(db),
EntryRepo: persistence.NewEntryRepository(db),
AuthorRepo: persistence.NewAuthorRepository(db),
UserRepo: persistence.NewUserRepository(db),
ImageRepo: persistence.NewImageRepository(db),
@@ -345,6 +364,19 @@ func getUseCases(repos *Repositories, imageStorage domainImage.Storage, settings
UpdateSiteUseCase: useCases.NewUpdateSiteUseCase(repos.SiteRepo, repos.ImageRepo, recorder),
SetDefaultSiteUseCase: useCases.NewSetDefaultSiteUseCase(repos.SiteRepo, recorder),
DeleteSiteUseCase: useCases.NewDeleteSiteUseCase(repos.SiteRepo, recorder),
CreateContentTypeUseCase: useCases.NewCreateContentTypeUseCase(repos.ContentTypeRepo, time.Now),
ListContentTypesUseCase: useCases.NewListContentTypesUseCase(repos.ContentTypeRepo),
GetContentTypeUseCase: useCases.NewGetContentTypeUseCase(repos.ContentTypeRepo),
UpdateContentTypeUseCase: useCases.NewUpdateContentTypeUseCase(repos.ContentTypeRepo, repos.EntryRepo, time.Now),
DeleteContentTypeUseCase: useCases.NewDeleteContentTypeUseCase(repos.ContentTypeRepo, repos.EntryRepo),
ListBuiltinTypesUseCase: useCases.NewListBuiltinTypesUseCase(),
GetBuiltinTypeUseCase: useCases.NewGetBuiltinTypeUseCase(),
LookupUserNamesUseCase: useCases.NewLookupUserNamesUseCase(repos.UserRepo),
CreateEntryUseCase: useCases.NewCreateEntryUseCase(repos.ContentTypeRepo, repos.EntryRepo, time.Now),
GetEntryUseCase: useCases.NewGetEntryUseCase(repos.ContentTypeRepo, repos.EntryRepo),
ListEntriesUseCase: useCases.NewListEntriesUseCase(repos.ContentTypeRepo, repos.EntryRepo),
UpdateEntryUseCase: useCases.NewUpdateEntryUseCase(repos.ContentTypeRepo, repos.EntryRepo, time.Now),
DeleteEntryUseCase: useCases.NewDeleteEntryUseCase(repos.ContentTypeRepo, repos.EntryRepo),
GetUserUseCase: useCases.NewGetUserUseCase(repos.UserRepo),
CreateUserUseCase: useCases.NewCreateUserUseCase(repos.UserRepo, hasher, repos.MailRepo, settings.PublicURL, recorder),
AuthenticateUserUseCase: useCases.NewAuthenticateUserUseCase(repos.UserRepo, hasher, recorder),
@@ -0,0 +1,38 @@
package builtintype
import (
"RenewCMS/api/pkg/apperr"
"RenewCMS/api/pkg/response"
domain "RenewCMS/internal/domain/builtintype"
"RenewCMS/internal/infrastructure/useCases"
"errors"
"net/http"
"github.com/go-chi/chi/v5"
)
type Handler struct {
ListUseCase *useCases.ListBuiltinTypesUseCase
GetUseCase *useCases.GetBuiltinTypeUseCase
}
func NewHandler(list *useCases.ListBuiltinTypesUseCase, get *useCases.GetBuiltinTypeUseCase) *Handler {
return &Handler{ListUseCase: list, GetUseCase: get}
}
func (h *Handler) List(w http.ResponseWriter, r *http.Request) {
response.WriteJSON(w, http.StatusOK, h.ListUseCase.List())
}
func (h *Handler) Get(w http.ResponseWriter, r *http.Request) {
found, err := h.GetUseCase.Get(chi.URLParam(r, "key"))
if errors.Is(err, domain.ErrNotFound) {
http.Error(w, apperr.BuiltinTypeNotFoundErrorMessage, http.StatusNotFound)
return
}
if err != nil {
http.Error(w, "Internal server error", http.StatusInternalServerError)
return
}
response.WriteJSON(w, http.StatusOK, found)
}
@@ -0,0 +1,182 @@
package contenttype
import (
"RenewCMS/api/pkg/apperr"
"RenewCMS/api/pkg/response"
validator "RenewCMS/api/pkg/validator"
domain "RenewCMS/internal/domain/contenttype"
"RenewCMS/internal/infrastructure/useCases"
"encoding/json"
"errors"
"net/http"
"time"
"github.com/go-chi/chi/v5"
)
type Handler struct {
CreateUseCase *useCases.CreateContentTypeUseCase
ListUseCase *useCases.ListContentTypesUseCase
GetUseCase *useCases.GetContentTypeUseCase
UpdateUseCase *useCases.UpdateContentTypeUseCase
DeleteUseCase *useCases.DeleteContentTypeUseCase
}
func NewHandler(create *useCases.CreateContentTypeUseCase, list *useCases.ListContentTypesUseCase, get *useCases.GetContentTypeUseCase, update *useCases.UpdateContentTypeUseCase, deleteUseCase *useCases.DeleteContentTypeUseCase) *Handler {
return &Handler{CreateUseCase: create, ListUseCase: list, GetUseCase: get, UpdateUseCase: update, DeleteUseCase: deleteUseCase}
}
type iconInput struct {
value *string
invalid bool
}
func (i *iconInput) UnmarshalJSON(data []byte) error {
if string(data) == "null" {
return nil
}
var text string
if err := json.Unmarshal(data, &text); err != nil {
i.invalid = true
return nil
}
i.value = &text
return nil
}
type PostContentType struct {
Key string `json:"key" validate:"required"`
Name string `json:"name" validate:"required,max=100"`
Icon iconInput `json:"icon"`
Fields []domain.Field `json:"fields"`
}
type PutContentType struct {
Key string `json:"key"`
Name string `json:"name" validate:"required,max=100"`
Icon iconInput `json:"icon"`
Fields []domain.Field `json:"fields"`
}
type contentTypeResponse struct {
ID uint32 `json:"id"`
Key string `json:"key"`
Name string `json:"name"`
Icon *string `json:"icon"`
Fields []domain.Field `json:"fields"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
func toResponse(contentType domain.ContentType) contentTypeResponse {
fields := contentType.Fields
if fields == nil {
fields = []domain.Field{}
}
return contentTypeResponse{
ID: contentType.ID,
Key: contentType.Key,
Name: contentType.Name,
Icon: contentType.Icon,
Fields: fields,
CreatedAt: contentType.CreatedAt,
UpdatedAt: contentType.UpdatedAt,
}
}
func writeContentTypeError(w http.ResponseWriter, err error) {
switch {
case errors.Is(err, domain.ErrContentTypeNotFound):
http.Error(w, apperr.ContentTypeNotFoundErrorMessage, http.StatusNotFound)
case errors.Is(err, domain.ErrKeyTaken):
http.Error(w, apperr.ContentTypeKeyTakenErrorMessage, http.StatusConflict)
case errors.Is(err, domain.ErrHasEntries):
http.Error(w, apperr.ContentTypeHasEntriesErrorMessage, http.StatusConflict)
case errors.Is(err, domain.ErrSchemaIncompatible):
http.Error(w, apperr.SchemaIncompatibleErrorMessage, http.StatusConflict)
case errors.Is(err, domain.ErrInvalidName):
http.Error(w, apperr.BodyErrorMessage, http.StatusBadRequest)
case errors.Is(err, domain.ErrInvalidIcon):
http.Error(w, apperr.InvalidIconErrorMessage, http.StatusBadRequest)
case errors.Is(err, domain.ErrInvalidKey):
http.Error(w, apperr.InvalidContentTypeKeyErrorMessage, http.StatusBadRequest)
case errors.Is(err, domain.ErrInvalidField):
http.Error(w, apperr.InvalidFieldErrorMessage, http.StatusUnprocessableEntity)
default:
http.Error(w, "Internal server error", http.StatusInternalServerError)
}
}
func (h *Handler) List(w http.ResponseWriter, r *http.Request) {
found, err := h.ListUseCase.List()
if err != nil {
writeContentTypeError(w, err)
return
}
responses := make([]contentTypeResponse, 0, len(found))
for _, contentType := range found {
responses = append(responses, toResponse(contentType))
}
response.WriteJSON(w, http.StatusOK, responses)
}
func (h *Handler) Get(w http.ResponseWriter, r *http.Request) {
found, err := h.GetUseCase.Get(chi.URLParam(r, "key"))
if err != nil {
writeContentTypeError(w, err)
return
}
response.WriteJSON(w, http.StatusOK, toResponse(found))
}
func (h *Handler) Create(w http.ResponseWriter, r *http.Request) {
var request PostContentType
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
}
if request.Icon.invalid {
writeContentTypeError(w, domain.ErrInvalidIcon)
return
}
created, err := h.CreateUseCase.Create(useCases.CreateContentTypeCommand{Key: request.Key, Name: request.Name, Icon: request.Icon.value, Fields: request.Fields})
if err != nil {
writeContentTypeError(w, err)
return
}
response.WriteJSON(w, http.StatusCreated, toResponse(created))
}
func (h *Handler) Update(w http.ResponseWriter, r *http.Request) {
var request PutContentType
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
}
if request.Icon.invalid {
writeContentTypeError(w, domain.ErrInvalidIcon)
return
}
updated, err := h.UpdateUseCase.Update(useCases.UpdateContentTypeCommand{Key: chi.URLParam(r, "key"), Name: request.Name, Icon: request.Icon.value, Fields: request.Fields})
if err != nil {
writeContentTypeError(w, err)
return
}
response.WriteJSON(w, http.StatusOK, toResponse(updated))
}
func (h *Handler) Delete(w http.ResponseWriter, r *http.Request) {
if err := h.DeleteUseCase.Delete(chi.URLParam(r, "key")); err != nil {
writeContentTypeError(w, err)
return
}
w.WriteHeader(http.StatusNoContent)
}
+232
View File
@@ -0,0 +1,232 @@
package entry
import (
"RenewCMS/api/pkg/apperr"
"RenewCMS/api/pkg/claims"
"RenewCMS/api/pkg/response"
validator "RenewCMS/api/pkg/validator"
"RenewCMS/internal/domain/contenttype"
domain "RenewCMS/internal/domain/entry"
"RenewCMS/internal/infrastructure/useCases"
"encoding/json"
"errors"
"net/http"
"net/url"
"strconv"
"time"
"github.com/go-chi/chi/v5"
)
type Handler struct {
CreateUseCase *useCases.CreateEntryUseCase
GetUseCase *useCases.GetEntryUseCase
ListUseCase *useCases.ListEntriesUseCase
UpdateUseCase *useCases.UpdateEntryUseCase
DeleteUseCase *useCases.DeleteEntryUseCase
}
func NewHandler(create *useCases.CreateEntryUseCase, get *useCases.GetEntryUseCase, list *useCases.ListEntriesUseCase, update *useCases.UpdateEntryUseCase, deleteUseCase *useCases.DeleteEntryUseCase) *Handler {
return &Handler{CreateUseCase: create, GetUseCase: get, ListUseCase: list, UpdateUseCase: update, DeleteUseCase: deleteUseCase}
}
type EntryBody struct {
Data map[string]any `json:"data" validate:"required"`
}
type entryResponse struct {
ID uint32 `json:"id"`
ContentType string `json:"content_type"`
Data map[string]any `json:"data"`
CreatedBy uint32 `json:"created_by"`
UpdatedBy uint32 `json:"updated_by"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
func toResponse(typed useCases.TypedEntry) entryResponse {
return entryResponse{
ID: typed.ID,
ContentType: typed.ContentTypeKey,
Data: typed.Data,
CreatedBy: typed.CreatedBy,
UpdatedBy: typed.UpdatedBy,
CreatedAt: typed.CreatedAt,
UpdatedAt: typed.UpdatedAt,
}
}
type pageResponse struct {
Items []entryResponse `json:"items"`
Total int `json:"total"`
Page int `json:"page"`
Size int `json:"size"`
}
const (
defaultListPage = 1
defaultListSize = 25
)
type listQuery struct {
Page int `validate:"gte=1"`
Size int `validate:"oneof=5 25 50 100"`
Sort domain.Sort
}
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
}
order := domain.DefaultSort()
if values.Has("sort") {
order, err = domain.ParseSort(values.Get("sort"))
if err != nil {
return listQuery{}, err
}
}
return listQuery{Page: page, Size: size, Sort: order}, nil
}
func parseEntryId(r *http.Request) (uint32, error) {
id, err := strconv.ParseUint(chi.URLParam(r, "id"), 10, 32)
return uint32(id), err
}
func writeEntryError(w http.ResponseWriter, err error) {
var fieldError domain.FieldError
switch {
case errors.Is(err, contenttype.ErrContentTypeNotFound):
http.Error(w, apperr.ContentTypeNotFoundErrorMessage, http.StatusNotFound)
case errors.Is(err, domain.ErrEntryNotFound):
http.Error(w, apperr.EntryNotFoundErrorMessage, http.StatusNotFound)
case errors.As(err, &fieldError):
http.Error(w, apperr.InvalidEntryErrorMessage+": "+fieldError.Error(), fieldErrorStatus(err))
case errors.Is(err, domain.ErrInvalidPage), errors.Is(err, domain.ErrInvalidSort):
http.Error(w, apperr.BodyErrorMessage, http.StatusBadRequest)
case errors.Is(err, domain.ErrInvalidEntry):
http.Error(w, apperr.InvalidEntryErrorMessage, http.StatusUnprocessableEntity)
default:
http.Error(w, "Internal server error", http.StatusInternalServerError)
}
}
func fieldErrorStatus(err error) int {
if errors.Is(err, domain.ErrUniqueViolation) {
return http.StatusConflict
}
return http.StatusUnprocessableEntity
}
func readBody(w http.ResponseWriter, r *http.Request) (EntryBody, bool) {
var body EntryBody
if err := json.NewDecoder(r.Body).Decode(&body); err != nil || validator.Validate.Struct(body) != nil {
http.Error(w, apperr.BodyErrorMessage, http.StatusBadRequest)
return EntryBody{}, false
}
return body, true
}
func currentUserId(w http.ResponseWriter, r *http.Request) (uint32, bool) {
userId, ok := claims.UserId(r)
if !ok {
http.Error(w, apperr.UnauthorizedErrorMessage, http.StatusUnauthorized)
}
return userId, ok
}
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.ListEntriesCommand{ContentTypeKey: chi.URLParam(r, "key"), Page: query.Page, Size: query.Size, Sort: query.Sort})
if err != nil {
writeEntryError(w, err)
return
}
items := make([]entryResponse, 0, len(page.Items))
for _, typed := range page.Items {
items = append(items, toResponse(typed))
}
response.WriteJSON(w, http.StatusOK, pageResponse{Items: items, Total: page.Total, Page: page.Page, Size: page.Size})
}
func (h *Handler) Get(w http.ResponseWriter, r *http.Request) {
id, err := parseEntryId(r)
if err != nil {
http.Error(w, apperr.IdUint32ErrorMessage, http.StatusBadRequest)
return
}
found, err := h.GetUseCase.Get(chi.URLParam(r, "key"), id)
if err != nil {
writeEntryError(w, err)
return
}
response.WriteJSON(w, http.StatusOK, toResponse(found))
}
func (h *Handler) Create(w http.ResponseWriter, r *http.Request) {
userId, ok := currentUserId(w, r)
if !ok {
return
}
body, ok := readBody(w, r)
if !ok {
return
}
created, err := h.CreateUseCase.Create(useCases.CreateEntryCommand{ContentTypeKey: chi.URLParam(r, "key"), Data: body.Data, UserID: userId})
if err != nil {
writeEntryError(w, err)
return
}
response.WriteJSON(w, http.StatusCreated, toResponse(created))
}
func (h *Handler) Update(w http.ResponseWriter, r *http.Request) {
id, err := parseEntryId(r)
if err != nil {
http.Error(w, apperr.IdUint32ErrorMessage, http.StatusBadRequest)
return
}
userId, ok := currentUserId(w, r)
if !ok {
return
}
body, ok := readBody(w, r)
if !ok {
return
}
updated, err := h.UpdateUseCase.Update(useCases.UpdateEntryCommand{ContentTypeKey: chi.URLParam(r, "key"), ID: id, Data: body.Data, UserID: userId})
if err != nil {
writeEntryError(w, err)
return
}
response.WriteJSON(w, http.StatusOK, toResponse(updated))
}
func (h *Handler) Delete(w http.ResponseWriter, r *http.Request) {
id, err := parseEntryId(r)
if err != nil {
http.Error(w, apperr.IdUint32ErrorMessage, http.StatusBadRequest)
return
}
if err := h.DeleteUseCase.Delete(chi.URLParam(r, "key"), id); err != nil {
writeEntryError(w, err)
return
}
w.WriteHeader(http.StatusNoContent)
}
+66
View File
@@ -0,0 +1,66 @@
package user
import (
"RenewCMS/api/pkg/apperr"
"RenewCMS/api/pkg/response"
domainUser "RenewCMS/internal/domain/user"
"RenewCMS/internal/infrastructure/useCases"
"errors"
"net/http"
"strconv"
"strings"
)
type LookupHandler struct {
LookupUseCase *useCases.LookupUserNamesUseCase
}
type userNameResponse struct {
ID uint32 `json:"id"`
DisplayName string `json:"display_name"`
}
func NewLookupHandler(lookup *useCases.LookupUserNamesUseCase) *LookupHandler {
return &LookupHandler{LookupUseCase: lookup}
}
func parseLookupIDs(raw string) ([]uint32, bool) {
if raw == "" {
return nil, false
}
if strings.Count(raw, ",")+1 > domainUser.MaxLookupIDs {
return nil, false
}
parts := strings.Split(raw, ",")
ids := make([]uint32, 0, len(parts))
for _, part := range parts {
id, err := strconv.ParseUint(part, 10, 32)
if err != nil {
return nil, false
}
ids = append(ids, uint32(id))
}
return ids, true
}
func (h *LookupHandler) Lookup(w http.ResponseWriter, r *http.Request) {
ids, ok := parseLookupIDs(r.URL.Query().Get("ids"))
if !ok {
http.Error(w, apperr.BodyErrorMessage, http.StatusBadRequest)
return
}
names, err := h.LookupUseCase.Lookup(ids)
if errors.Is(err, domainUser.ErrInvalidLookup) {
http.Error(w, apperr.BodyErrorMessage, http.StatusBadRequest)
return
}
if err != nil {
http.Error(w, "Internal server error", http.StatusInternalServerError)
return
}
items := make([]userNameResponse, 0, len(names))
for _, name := range names {
items = append(items, userNameResponse{ID: name.ID, DisplayName: name.DisplayName})
}
response.WriteJSON(w, http.StatusOK, items)
}
+11
View File
@@ -86,3 +86,14 @@ const ArticleSlugTakenErrorMessage = "slug_taken"
const ArticleImageNotFoundErrorMessage = "image_not_found"
const InvalidTitleTemplateErrorMessage = "invalid_title_template"
const SlugSuggestionHeader = "X-Slug-Suggestion"
const ContentTypeNotFoundErrorMessage = "content_type_not_found"
const ContentTypeKeyTakenErrorMessage = "content_type_key_taken"
const ContentTypeHasEntriesErrorMessage = "content_type_has_entries"
const InvalidContentTypeKeyErrorMessage = "invalid_content_type_key"
const InvalidIconErrorMessage = "invalid_icon"
const BuiltinTypeNotFoundErrorMessage = "builtin_type_not_found"
const InvalidFieldErrorMessage = "invalid_field"
const SchemaIncompatibleErrorMessage = "schema_incompatible"
const EntryNotFoundErrorMessage = "entry_not_found"
const InvalidEntryErrorMessage = "invalid_entry"
+21
View File
@@ -0,0 +1,21 @@
package response
import (
"encoding/json"
"log"
"net/http"
)
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)
}
}
+55
View File
@@ -6,6 +6,9 @@ import (
"RenewCMS/api/handlers/article"
"RenewCMS/api/handlers/auth"
"RenewCMS/api/handlers/author"
"RenewCMS/api/handlers/builtintype"
"RenewCMS/api/handlers/contenttype"
"RenewCMS/api/handlers/entry"
"RenewCMS/api/handlers/frontend"
"RenewCMS/api/handlers/imagevariant"
"RenewCMS/api/handlers/media"
@@ -131,6 +134,7 @@ func NewUserRouter(container *UseCases, rateLimit config.AuthRateLimitSettings,
r := chi.NewRouter()
userHandler := user.NewHandler(container.UpdateUserProfileUseCase)
lookupHandler := user.NewLookupHandler(container.LookupUserNamesUseCase)
inviteHandler := user.NewInviteHandler(container.CreateInviteUseCase, container.CancelInviteUseCase, container.RenewInviteUseCase, container.ListUsersAndInvitesUseCase)
r.Use(jwtauth.Verifier(container.Token))
@@ -141,6 +145,7 @@ func NewUserRouter(container *UseCases, rateLimit config.AuthRateLimitSettings,
r.Use(middleware.RequireVerifiedUser(container.GetUserUseCase))
r.Patch("/me", userHandler.UpdateMe)
r.Get("/", inviteHandler.ListUsers)
r.Get("/lookup", lookupHandler.Lookup)
r.Group(func(r chi.Router) {
r.Use(middleware.RequireOwner(container.GetUserUseCase))
r.Use(middleware.TrustedProxyRealIP(trustedProxies))
@@ -244,6 +249,54 @@ func NewAuthorRouter(container *UseCases, trustedProxies []string) http.Handler
return r
}
func NewContentTypeRouter(container *UseCases, trustedProxies []string) http.Handler {
r := chi.NewRouter()
contentTypeHandler := contenttype.NewHandler(container.CreateContentTypeUseCase, container.ListContentTypesUseCase, container.GetContentTypeUseCase, container.UpdateContentTypeUseCase, container.DeleteContentTypeUseCase)
entryHandler := entry.NewHandler(container.CreateEntryUseCase, container.GetEntryUseCase, container.ListEntriesUseCase, container.UpdateEntryUseCase, container.DeleteEntryUseCase)
r.Use(jwtauth.Verifier(container.Token))
r.Use(container.apiKeyAuth())
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.Get("/", contentTypeHandler.List)
r.Get("/{key}", contentTypeHandler.Get)
r.Group(func(r chi.Router) {
r.Use(middleware.RequireOwnerOrAdmin(container.GetUserUseCase))
r.Post("/", contentTypeHandler.Create)
r.Put("/{key}", contentTypeHandler.Update)
r.Delete("/{key}", contentTypeHandler.Delete)
})
r.Get("/{key}/entry", entryHandler.List)
r.Post("/{key}/entry", entryHandler.Create)
r.Get("/{key}/entry/{id}", entryHandler.Get)
r.Put("/{key}/entry/{id}", entryHandler.Update)
r.Delete("/{key}/entry/{id}", entryHandler.Delete)
return r
}
func NewBuiltinTypeRouter(container *UseCases, trustedProxies []string) http.Handler {
r := chi.NewRouter()
builtinTypeHandler := builtintype.NewHandler(container.ListBuiltinTypesUseCase, container.GetBuiltinTypeUseCase)
r.Use(jwtauth.Verifier(container.Token))
r.Use(container.apiKeyAuth())
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.RequireOwnerOrAdmin(container.GetUserUseCase))
r.Get("/", builtinTypeHandler.List)
r.Get("/{key}", builtinTypeHandler.Get)
return r
}
func NewActivityRouter(container *UseCases, trustedProxies []string) http.Handler {
r := chi.NewRouter()
@@ -394,6 +447,8 @@ func InitBackendRoutes(container *UseCases, settings config.Settings) *chi.Mux {
r.Mount("/settings", NewSettingsRouter(container, settings.TrustedProxies))
r.Mount("/site", NewSiteRouter(container, settings.TrustedProxies))
r.Mount("/author", NewAuthorRouter(container, settings.TrustedProxies))
r.Mount("/content-type", NewContentTypeRouter(container, settings.TrustedProxies))
r.Mount("/builtin-type", NewBuiltinTypeRouter(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))
+108
View File
@@ -0,0 +1,108 @@
# Claude Design prompt: custom content types
Paste everything below the line into Claude Design, with the existing RenewCMS design system attached.
---
You are extending the RenewCMS back-office design. RenewCMS is a small self-hosted CMS (Go API plus a Vue 3 SPA built with Nuxt UI v4 and Tailwind 4). The existing screens, the AppFrame back-office shell, the AuthCard auth frames, the design tokens and the component inventory are already in this design system: reuse them, never invent new colors, spacing, radius or type values, and keep the same copy tone (short, plain, sentence case). Deliver the same artifacts the system already uses: one board per screen with every state, the exact copy per state, the routes with their auth requirement, the new components with their Nuxt UI mapping, and light and dark variants at desktop (1440x900) and mobile (390x844).
## The feature
Until now RenewCMS only managed fixed content: articles, authors, sites, media and users. We are adding custom content types: an owner or admin defines a content type (for example "Recipe" or "Event") made of ordered fields, and then any verified user creates entries of that type. Think of the clear part of Directus: a type is a collection, a field is a typed column. Do not copy Strapi's split between collections, components and fields into separate screens: everything about a type happens on one screen. Do not draw a table-builder feel with database jargon; speak in terms of content.
The backend for the first part already exists. Design the full experience including the parts that come later, and mark each screen or state as "available now" or "later" (see the scope table).
## What the backend does today (design against this, do not contradict it)
Routes, all behind the normal signed-in, verified-user back-office session (cookie or API key):
- GET /v1/content-type: list of types, ordered by name.
- POST /v1/content-type, PUT /v1/content-type/{key}, DELETE /v1/content-type/{key}: owner or admin only.
- GET /v1/content-type/{key}.
- GET and POST /v1/content-type/{key}/entry; GET, PUT and DELETE /v1/content-type/{key}/entry/{id}. Any verified user.
A content type: id, key, name, fields, created_at, updated_at.
- key: lowercase slug, 2 to 40 characters, unique, chosen at creation, never editable afterwards. It appears in URLs and the API.
- name: free text, up to 100 characters, editable.
- fields: ordered list, 1 to 50 fields.
A field: key, label, type, required, unique, default, min, max, options.
- key: lowercase letters, digits and underscores, starts with a letter, up to 40 characters, unique within the type. It becomes the JSON key in the API.
- label: the text shown in the editor.
- type: one of text, richtext (markdown), number, boolean, date (a calendar date, no time), select (a single choice from a list of 1 to 50 distinct options).
- required, unique (text, number, date and select only), default (applied only when an entry is created and the field is omitted), min and max.
- min and max mean: length in characters for text and richtext, value for number, earliest and latest date for date. They do not exist for boolean and select. min must not exceed max. A default must satisfy the field's own rules. A unique field cannot have a default.
- A field's type can never change after the type is saved, and the type key never changes.
An entry: id, content_type (the type's key), data (an object keyed by field key), created_by, updated_by, created_at, updated_at.
- Saving an entry replaces its whole data. Defaults apply only on create. An explicit empty value stays empty, and a required field cannot be empty.
- Unknown keys are rejected. Values of a removed field disappear.
Schema changes once entries exist:
- Removing a field is allowed; its stored values stop being returned.
- Every existing entry is re-validated against the new schema. If any entry would become invalid (a new required field without a default, a field made unique while duplicates exist, a tighter min or max below a stored value, a removed option still in use), the whole change is refused as incompatible and nothing changes.
- Adding a required field is fine if it has a default.
- A type that has entries cannot be deleted.
Entry lists are paginated: page size 5, 25, 50 or 100 (default 25), sort by id, created_at or updated_at in either direction (default most recently updated first). There is no filtering or search on custom fields yet.
Errors come back as plain text. Map each to friendly copy:
- content_type_not_found, entry_not_found
- content_type_key_taken
- content_type_has_entries
- invalid_content_type_key
- invalid_field
- schema_incompatible
- "invalid_entry: <field key>: <rule>", rule being one of required, type, min, max, options, unique, unknown_field. Unique violations arrive as HTTP 409, the other entry rules as 422.
- The usual 401, 403 (unverified account or insufficient role), 400 and 500 already covered in the system's HTTP-status-to-copy table.
## Screens to design
For each screen: every state (loading, empty, populated, error, forbidden, offline or failed save where relevant), the exact copy, the routes and their auth requirement, and a mobile layout.
### 1. Schema screen: list of types (available now)
Sits in the back-office navigation as "Schema", visible to owners and admins; other verified users do not see it. Shows the types as a list or table: name, key, number of fields, last updated. Shows the built-in types (Articles, Authors, Sites, Media, Users) in the same list with a "Built-in" badge and a lock icon. Built-ins are read-only entries here: they open a read-only view listing their fields, with no edit, no delete and no ability to add fields. Do not suggest that built-ins are custom collections; the badge and a one-line explanation make clear they are managed by RenewCMS. Primary action "New content type". States: loading, empty (no custom type yet: invite the user to create one, built-ins still listed), populated, error, forbidden (non-admin who types the URL).
### 2. Schema builder (available now, the main screen)
One screen with three regions, not three separate areas:
- Left: the ordered field list. Reorder (drag with a keyboard-accessible alternative), add field, remove field. Each row shows label, key, type icon and small badges for required and unique.
- Right: the field inspector for the selected field: label, key (generated from the label, editable until the type is first saved, then locked), type (a gallery of the six types with icon and one-line description), required, unique (disabled with an explanation where not allowed), default, min and max (with the right unit wording per type), and for select an options editor (add, remove, reorder, no duplicates, no blanks). Show the rules inline as the user types, not only after save.
- Top: type name, type key (editable only at creation; afterwards locked with a tooltip explaining why), Save and Discard.
- Live API preview: a collapsible panel showing the exact JSON an entry of this type looks like (a sample entry using each field's type and default) and the route it lives at, updating as fields change. Include a copy button.
States: new type, editing an existing type, unsaved changes, validation errors per field and at type level (inline, with the field highlighted in the list), saving, saved, save failed, key already taken, schema incompatible with existing entries.
### 3. Schema change review (available now for the review step, later for the diff)
Before saving changes to a type that already has entries, show a review step: "Add 2 fields, change 1, remove 1", listing each change, with destructive ones (removing a field, removing an option, tightening a limit, making a field unique or required) clearly flagged. Because the server decides compatibility, the review is informational plus an explicit Apply button; if the server answers schema incompatible, show a refusal state that says nothing was changed and which kind of change likely caused it (we cannot tell which entry, so write copy that does not pretend to). Also design the "delete type" confirmation: blocked when entries exist (explain that entries must be deleted first) and a plain confirmation when empty. Mark per-change entry counts and a full diff as "later" (the API does not return them yet).
### 4. Field-type gallery (available now)
A reference board for the six field types showing, for each: its icon, its inspector options, its list cell (how a value renders in the entries table, including the empty state), its form control in the entry editor (markdown editor for richtext with preview, number input with min and max hints, toggle for boolean using the system's single toggle component, date picker, select, text with a character counter when a limit exists), and its error states per rule (required, type, min, max, options, unique). Show the "filter" widget for each type as "later" since filtering on custom fields is not available yet.
### 5. Content navigation and entry list (available now)
The back-office sidebar gets a "Content" group generated from the custom types, one entry per type (name, with the type's icon if any; truncated gracefully with many types; collapsed on mobile). The list screen for a type shows a paginated table with a column per field (cap the visible columns and let the user choose which, defaulting to the first few), plus created and updated dates and the author of the last change. Sort control (id, created, updated), page size selector (5, 25, 50, 100), "New entry" button. Row click opens the editor. States: loading, empty for this type (with a hint pointing to "New entry"), populated, error, forbidden, type not found.
Use a sample "Events" type for all boards: title (text, required, unique, max 80), starts_on (date, required), ends_on (date), online (boolean, default false), capacity (number, min 1, max 5000), category (select: Talk, Workshop, Meetup), description (richtext).
### 6. Entry editor (available now)
Create and edit form generated from the schema, one control per field in schema order, with labels, required markers, helper text from min, max and options, a character counter where a limit exists, and inline errors per field. Show defaults pre-filled on create. Save, Cancel, Delete (with confirmation). Provenance footer: created by, updated by, dates. States: new, editing, unsaved changes, saving, saved, failed save, field errors for each rule, duplicate unique value (409), entry not found, concurrent schema change (a field disappeared or a new required field appeared since the form loaded: explain that the form must be reloaded).
### 7. Relation field and sentence-style relation picker (later, design now)
Relations are not built yet. Design the picker so that the model reads as sentences, not jargon: "Each Event has one Venue" and, beside it, "Each Venue has many Events", with a live preview of both sides. Offer the three relationship shapes in plain words. Show how a relation field renders in the inspector, the entry form (search and pick, with chips for many) and the list cell. Mark everything "later".
### 8. Permissions grid (later, design now)
A collection by action grid on the roles area: rows are types (custom and built-in), columns are read, create, update and delete, per role. Built-in rows are locked where the system dictates it. Make the grid usable on mobile (collapse to a per-role list). Mark "later". Today's rule is simple: owners and admins edit schema, any verified user reads and writes entries; show that as the default state of the grid.
### 9. Schema export and import (later, design now)
Export the whole schema or a single type to a file, import with a preview of what will be created or changed and the same compatibility review as screen 3, plus an explicit confirm. Aim at the dev-to-production flow. Mark "later".
## Scope table to include in your answer
For every screen and state, label it "available now" or "later" so engineering knows what is wired. Available now: screens 1 to 6 (except the diff counts), the live API preview, the type-level and field-level validation states. Later: relation picker, permissions grid, schema export and import, filters on custom fields, per-change entry counts, publish and draft state, public (anonymous) read access, activity log entries for types and entries.
## Constraints
- Nuxt UI v4 only, mapped to existing components in the inventory. List every new component you introduce with its Nuxt UI mapping and why an existing one does not fit.
- Tokens only. No raw hex values and no arbitrary Tailwind colors.
- Accessibility: keyboard reorder for fields, focus order, visible focus, labels on every control, error text tied to its input, sufficient contrast in light and dark.
- Copy: short and plain, no database jargon in primary labels (say "field", "choice list", "entry", "content type"; keep "key" for the API identifier and explain it once).
- Do not redesign existing screens. Only add what these screens need: new sidebar group, new routes, new components.
- Provide the routes table: /schema, /schema/new, /schema/:key, /content/:key, /content/:key/new, /content/:key/:id, each with its auth requirement (schema routes owner or admin, content routes any verified user).
- Anything the API cannot do today (see above) must not appear as if it works. If a design needs a backend capability that does not exist, flag it explicitly in a short "needs backend" list at the end.
+20
View File
@@ -0,0 +1,20 @@
# Custom content types
A content type is a named schema (a key, a name and 1 to 50 fields) stored as one row with the fields as a JSON text column. Entries of every type share one generic table whose `data` column holds a JSON object. No DDL runs at runtime, so creating or changing a type never alters the database schema.
## Icon, built-in types and user lookup
- A content type has an optional `icon`: `null` or a string matching `^[a-z][a-z0-9-]{0,39}$`, validated in the domain (`ErrInvalidIcon`, `400 invalid_icon`) and never checked against a list of known icons. `""` is stored as `null`. `PUT` replaces the icon like the name and the fields, so an absent icon clears it. The column is nullable, so rows stored before it existed read as `null`.
- `GET /v1/builtin-type` and `GET /v1/builtin-type/{key}` expose a static, read-only catalogue (`internal/domain/builtintype`) of the built-in types `article`, `author`, `site`, `media` and `user` as `key`, `name` and `fields` shaped like content type fields. Owners and admins only. It uses no repository; an unknown key is `404 builtin_type_not_found`. A test checks that every catalogue field key exists in the JSON of the matching entity.
- `GET /v1/user/lookup?ids=1,2,3` returns `[{id, display_name}]` for any verified user, ordered by id, with the username when the display name is empty. 1 to 100 distinct uint32 ids; anything else is `400`. Unknown ids are omitted.
## Layering
The domain packages `internal/domain/contenttype` and `internal/domain/entry` own the rules: key, name and field validation, entry validation against a schema, the sort whitelist, the page limits and the value equality used by uniqueness. The use cases orchestrate them through the two repositories. The repositories only store and load rows. Entry counting for the "type still has entries" rule lives on the entry repository.
## Known limitations of phase 1
- Uniqueness and schema re-validation are O(n). Checking a unique field loads every entry of the type and compares values in Go, and updating a type with stored entries loads all of them to re-validate. This keeps the SQL portable across SQLite, MySQL/MariaDB and PostgreSQL. The path to fix it is the filterable-fields phase: project the values of unique and filterable fields into an indexed table, so uniqueness becomes an indexed lookup and re-validation can be restricted to the changed fields.
- Unique values are checked without a transaction, so two concurrent writes of the same unique value can both succeed. A content type key is protected by a unique index, and a violation is reported as `content_type_key_taken` (409).
- `entry.Repository.DeleteByContentType` is intentionally unused for now. A content type that still has entries cannot be deleted; the method is kept as part of the repository contract for a later cascade.
- Listing is limited to page 1,000,000 and to page sizes of 100 so that the SQL offset cannot overflow.
+6
View File
@@ -20,6 +20,12 @@ Back-office board groups: Sites, Sites: form, Sites: delete, Authors, Authors: f
- 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.
## Pass 4: custom content types
Board `RenewCMS Screens Schema.dc.html` (frames: `SchemaFrame`, mounted in `AppFrame`): 9 groups, 65 states (56 available now, 9 later). 1 Schema list 6, 2 Schema builder 16, 3 Review and delete 7, 4 Field types 6, 5 Content and entry list 9, 6 Entry editor 13, 7 Relations 3, 8 Permissions 2, 9 Export and import 3. Plus tables: scope, routes, new components with their Nuxt UI mapping, errors to copy, needs backend (4 rows), decisions to confirm, accessibility. Specs: screens/schema.md, content.md, entry.md, schema-later.md.
- AppFrame gains a Schema item (owner and admin) and a Content group (sidebar and mobile drawer). Nothing else in AppFrame changed.
- Backend gaps still open: built-in types and fields, display names for created_by and updated_by, a type icon, per-change entry counts.
- Not done: Back-office and Prototype boards were not compared visually after the sidebar change (see Checks below).
## Specs
routes.md · components.md · states.md · foundations.md · change-list.md · activity-spec.js · screens/*.md (24 files)
+32
View File
@@ -89,3 +89,35 @@ Frames: `DirectoryFrame.dc.html` (Sites, Authors, editor section content; the li
| 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 |
## Custom content types (pass 4)
Frames: `SchemaFrame.dc.html` (all schema, content and entry bodies; relation, permissions and import frames are Later), mounted in `AppFrame.dc.html`. Existing pieces are reused unchanged: dialogs and sheets, toasts, alerts, paginator, skeletons, empty states, SlugField, CodeSnippet, the single switch.
**AppFrame changes.** Sidebar: a "Schema" item (icon shapes) after Users, owner and admin only. A "Content" group under the main items, one row per custom type (default icon files, name truncated with the full name in the tooltip, selected row sand). Over 5 types it shows the first 5 and the selected one, then "Show all N". Mobile drawer: the group is one collapsed row "All content types" with the count; expanded it lists the types at 44 px. New props on the shell state: `content` (types), `contentOn`, `contentOpen`. The group is hidden when there are no custom types. No existing item changed.
| Component | Status | Nuxt UI | Notes |
|---|---|---|---|
| SchemaTable | New | UTable; below 640 px a list of UCard | Same pattern as SitesTable. Built-in rows add the lock and a Built-in badge |
| BuiltInBadge | New | UBadge outline + lock icon | Existing badges have no lock; same size as the Linked badge |
| FieldList | New | List of UButton rows, useSortable, UBadge | No Nuxt UI sortable list. Keyboard: the grip is a button; Space picks up, arrows move, Space drops, Esc cancels. Move up and Move down buttons on the selected row. Same approach as AuthorList |
| FieldInspector | New | UForm, UFormField, UInput, UInputNumber, UInputDate, USelect, UTextarea, USwitch | Composition only. Controls follow the field type |
| FieldTypePicker | New | URadioGroup variant="card" in a grid, icon in the label | Existing radio cards fit; only the icon and the lock state are added |
| KeyField | Existing | SlugField (UInput + UButton + UBadge) | Reused for the type key and field keys. Locked variant already exists |
| ChoicesEditor | New | UInput + UButton rows, useSortable | UInputTags can't reorder or flag a blank or duplicate per row |
| ApiPreview | New | UCollapsible + CodeSnippet + UButton | CodeSnippet is reused. Sheet on mobile |
| ChangeReview | New | UModal (sheet on mobile), UBadge, list rows | Dialog pattern unchanged. Rows reuse the UAlert-style row of SuggestionList |
| SchemaRefusal, DeleteTypeDialog | New | UModal + UAlert | Dialog pattern unchanged. Delete uses color="error" |
| ContentNavGroup | New | UNavigationMenu group "Content" (NavGroup) | Adds the 5 + selected cap, "Show all N" and the collapsed mobile row |
| EntryTable | New | UTable with column visibility | Cells per field type (FieldCell). Cards on mobile |
| ColumnPicker | New | UPopover + UCheckbox list; bottom sheet on mobile | UDropdownMenu closes on each pick and has no cap message |
| SortSelect | New | USelect + UButton icon | ID, Created and Updated only |
| FieldControl | New | UInput, UInputNumber, UInputDate, USelect, USwitch (the single toggle), MarkdownField | One switch per field type, generated from the schema |
| MarkdownField | New | UTextarea + UTabs (Write, Preview) + toolbar of UButton | The article editor is a full document editor. This is a compact one |
| FieldCell | New | text, UBadge outline (choice), icon + text (yes or no) | Renders one value per type, with the empty dash |
| EntryForm | New | UForm generated from the schema | Provenance footer, schema-changed alert |
| RelationPicker (later) | New | URadioGroup card + USelect | Sentence preview is text |
| RelationField (later) | New | UInputMenu multiple | Chips and search |
| PermissionsGrid (later) | New | UTable + UCheckbox; UCard list on mobile | |
| SchemaImportDialog (later) | New | UModal + UFileUpload | |
+10
View File
@@ -16,6 +16,13 @@
| /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} |
| /schema | Schema list, custom and built-in types (owner or admin; others get a 403 page and no sidebar entry). Available now | none | GET /v1/content-type |
| /schema/new | Schema builder, new type (owner or admin). Available now | none | POST /v1/content-type |
| /schema/:key | Schema builder for a custom type, read-only view for a built-in (owner or admin). Review step on save when the type has entries. Available now | none | GET/PUT/DELETE /v1/content-type/{key} |
| /content/:key | Entry list (any verified user). Available now | page, size, sort | GET /v1/content-type/{key}, GET /v1/content-type/{key}/entry?page=&size=&sort= |
| /content/:key/new | New entry (any verified user). Available now | none | POST /v1/content-type/{key}/entry |
| /content/:key/:id | Entry editor (any verified user). Available now | none | GET/PUT/DELETE /v1/content-type/{key}/entry/{id} |
| /settings/permissions | Permissions grid (owner or admin). Later | none | not built |
## Pagination in the URL (Articles, Media)
`/articles?page=2&size=50` and `/media?page=7&size=50`. Parameter names follow the repo (activity already uses `page` and `size`). Allowed sizes 5, 25, 50, 100. Defaults `page=1`, `size=25`, omitted from the URL when default. Changing search, tab, filter or size resets `page` to 1. `page` above the last page redirects (replace) to the last page and shows "That page doesn't exist. Showing the last page." An invalid `size` falls back to 25.
@@ -43,3 +50,6 @@ Sites pagination: `/settings/sites?q=&page=&size=` with the same rules as Articl
## 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.
## Custom content types in the URL
`/content/events?page=2&size=50&sort=created_at:desc`. `page` and `size` follow Articles (sizes 5, 25, 50, 100; default 25). `sort` is one parameter, `<id|created_at|updated_at>:<asc|desc>`, default `updated_at:desc`. Defaults are omitted from the URL; a size or sort change resets `page` to 1; invalid values are replaced silently by the default; a `page` past the end falls back to the last page. The response carries `total`, `page`, `size` and `sort`: use them for the summary ("Showing 1–5 of 37"), the pager and the "37 entries use this content type" line of the review step. No filter or search on custom fields yet. Auth: `/schema*` owner or admin (403 page otherwise), `/content*` any verified user (unverified accounts are redirected to /register/pending). Unknown type: 404 content_type_not_found page. Unknown entry: 404 entry_not_found page.
+23
View File
@@ -0,0 +1,23 @@
# Content
Route: `/content/:key`. API: GET /v1/content-type/{key} · GET /v1/content-type/{key}/entry?page=&size=&sort=. Auth: any verified user.
Visual reference: `RenewCMS Screens Schema.dc.html`, groups "Content and entry list". Frames: `SchemaFrame.dc.html` mounted in `AppFrame.dc.html` (shell, sidebar, topbar, drawer). Every state is drawn in light and dark (theme switch) at 1440×900 (shown at 50%) and 390×844 (shown at 75%). Copy is exact. Strings in a Copy cell are separated by " · " and listed in reading order. Nothing is clock-sensitive.
### 5 Content navigation and entry list (group "5 Content and entry list", 9 states)
Route: `/content/:key`. API: GET /v1/content-type/{key}, GET /v1/content-type/{key}/entry. Auth: Any verified user.
The sidebar gets a "Content" group, one item per custom type (a default icon: types have no icon in the API). With more than 5 types it shows the first 5 and the selected one, then "Show all N"; long names truncate with the full name in a tooltip. On mobile the group is one collapsed row in the drawer. List: ID, up to 6 chosen field columns (default: first 4), Created, Updated, Updated by. Sort: ID, Created, Updated, either direction (default Updated, newest first). Page size 5, 25, 50, 100 (default 25). No filter or search. URL: /content/events?page=2&size=50&sort=created_at:desc (defaults omitted). The response carries total, page, size and sort; the summary, the pager and the review dialog use them.
| # | State | Trigger | Copy | Scope |
|---|---|---|---|---|
| 1 | Populated | /content/events. 7 entries, one page: no pager, only the count. | Content · Events · events · 7 fields · New entry · Sort by · Last updated · Columns · Edit content type · ID · Title · Starts on · Ends on · Online · Created · Updated · Updated by · 7 entries | Available now |
| 2 | Paginated, 5 per page | /content/events?size=5. 37 entries. | Showing 1–5 of 37 · 5 per page · Page 1 of 8 (mobile) | Available now |
| 3 | Columns menu | The Columns button. Popover on desktop, sheet on mobile. Created and updated always show. | Columns · 4 of 6 · Choose up to 6 fields to show. 4 selected. · Created and updated dates always show · Reset · Done | Available now |
| 4 | Many types in the sidebar | 14 custom types. Long names truncate. Mobile shows the drawer with the group expanded. | Content · Frequently asked questions and answers (truncated) · Show all 14 · All content types 14 (mobile, collapsed) | Available now |
| 5 | Loading | First load or retry. | (skeleton) | Available now |
| 6 | Empty for this type | Total is 0. The hint points to New entry. | No entries yet · Use New entry to add the first event. Each entry follows the fields of this content type. · New entry | Available now |
| 7 | Error | 500 or network failure. | Couldn't load entries · GET /v1/content-type/events/entry failed. Check your connection and try again. · Try again | Available now |
| 8 | Forbidden (403) | The API answers 403. Unverified accounts are redirected to /register/pending before this. | You don't have access to Events · Your account can't open this content right now. If you think this is a mistake, ask an owner or an admin. · Go to Home | Available now |
| 9 | Type not found | 404 content_type_not_found on /content/unknown. | Content type not found · It may have been deleted, or the address may be mistyped. · Go to Home | Available now |
+27
View File
@@ -0,0 +1,27 @@
# Entry editor
Route: `/content/:key/new`, `/content/:key/:id`. API: POST /v1/content-type/{key}/entry · GET/PUT/DELETE /v1/content-type/{key}/entry/{id}. Auth: any verified user.
Visual reference: `RenewCMS Screens Schema.dc.html`, groups "Entry editor". Frames: `SchemaFrame.dc.html` mounted in `AppFrame.dc.html` (shell, sidebar, topbar, drawer). Every state is drawn in light and dark (theme switch) at 1440×900 (shown at 50%) and 390×844 (shown at 75%). Copy is exact. Strings in a Copy cell are separated by " · " and listed in reading order. Nothing is clock-sensitive.
### 6 Entry editor (group "6 Entry editor", 13 states)
Route: `/content/:key/new, /content/:key/:id`. API: POST /v1/content-type/{key}/entry, GET/PUT/DELETE /v1/content-type/{key}/entry/{id}. Auth: Any verified user.
The form is generated from the schema, one control per field in schema order. Required fields carry * and the line "Fields marked * are required." Defaults are pre-filled on create and tagged Default. Saving replaces the whole entry.
| # | State | Trigger | Copy | Scope |
|---|---|---|---|---|
| 1 | New entry | /content/events/new. Online is pre-filled from its default. | New entry · Events · Fields marked * are required. · Default · Each entry needs a different title. · Between 1 and 5000. · Choose an option · Pick a date · Save · Cancel · New entry · Not saved yet | Available now |
| 2 | Editing | /content/events/42. Save is disabled until something changes. | Lime plaster workshop · Events · Entry 42 · Saved · Delete · Cancel · Save · Created by · Updated by · Inès Duarte · 12 Oct 2026, 09:14 · Marta Alves · 15 Oct 2026, 11:02 | Available now |
| 3 | Unsaved changes | Any edit. | Unsaved changes · 32 / 80 | Available now |
| 4 | Markdown preview | The Preview tab of a rich text field. | Write · Preview | Available now |
| 5 | Saving | PUT or POST in flight. Form dims. | Saving… | Available now |
| 6 | Saved | 200. | Saved at 11:02 · Entry saved · "Lime plaster workshop" is up to date. | Available now |
| 7 | Save failed | 500 or network failure. Values stay. | Save failed · Couldn't save the entry · Something went wrong on our side. Your changes are still here. Try again in a moment. · Try again | Available now |
| 8 | Required fields empty | 422 invalid_entry: title: required, starts_on: required. The first field with an error takes focus. | Fill in Title. · Pick a date for Starts on. · Not saved | Available now |
| 9 | Rule errors | 422 invalid_entry for max, type, max and options. One rule per field is shown at a time. | Title can be up to 80 characters. · 91 / 80 · Ends on must be a date, like 2026-11-21. · Capacity must be at most 5000. · Choose one of: Talk, Workshop or Meetup. · Not saved | Available now |
| 10 | Duplicate unique value (409) | 409 invalid_entry: title: unique. | Not saved · Another entry already uses this title. Change it and save again. · Another entry already uses this Title. Enter a different one. | Available now |
| 11 | Entry not found | 404 entry_not_found, for example after a delete elsewhere. | Entry not found · It may have been deleted by someone else. · Back to Events | Available now |
| 12 | Schema changed since load | 422 invalid_entry: room: required, or unknown_field. The form is read-only until reloaded. | The fields of Events changed · A field was removed and a new required field, Room, was added after you opened this form. Reload the form to continue. What you typed here can't be saved against the old fields. · Reload form | Available now |
| 13 | Delete entry: confirm | Delete. | Delete this entry? · "Lime plaster workshop" will be deleted from Events. This can't be undone. · Cancel · Delete entry | Available now |
+40
View File
@@ -0,0 +1,40 @@
# Schema: later
All states on this page are **Later**: relations, permissions and schema export and import are not built. Drawn now so the model and the layout are settled.
Visual reference: `RenewCMS Screens Schema.dc.html`, groups "Relations", "Permissions", "Export and import". Frames: `SchemaFrame.dc.html` mounted in `AppFrame.dc.html` (shell, sidebar, topbar, drawer). Every state is drawn in light and dark (theme switch) at 1440×900 (shown at 50%) and 390×844 (shown at 75%). Copy is exact. Strings in a Copy cell are separated by " · " and listed in reading order. Nothing is clock-sensitive.
### 7 Relation field and picker (group "7 Relations", 3 states)
Route: `/schema/:key, /content/:key/:id`. API: not built. Auth: Owner or admin (picker), any verified user (form).
All later. The model reads as two sentences, with a live preview of both sides. Three shapes: one to one, one to many, many to many.
| # | State | Trigger | Copy | Scope |
|---|---|---|---|---|
| 1 | Relation in the builder | A seventh type, Relation, in the type gallery. | Relation · Related content type · How are they connected? · One to one · Each Event has one Venue, and each Venue has one Event. · One to many · Each Event has one Venue. A Venue has many Events. · Many to many · Each Event has many Venues, and each Venue has many Events. · Each Event has one Venue · Each Venue has many Events · shown on Venue as the field "Events" | Later |
| 2 | Relation in the entry form | Search and pick; chips for many. | Venue · Speakers · Search to add · An event can have many speakers. | Later |
| 3 | Relation in the list | One chip, two chips and +N, or a dash. | One chip for a single relation. Up to two chips and a "+N" for many. Empty shows a dash. | Later |
### 8 Permissions grid (group "8 Permissions", 2 states)
Route: `/settings/permissions`. API: not built. Auth: Owner or admin.
All later. Rows are types, columns are actions, one role at a time. Built-in rows are locked. Mobile collapses to one card per type with four checkboxes.
| # | State | Trigger | Copy | Scope |
|---|---|---|---|---|
| 1 | Default: today's rules | Role User selected. Everything on, as today. | Permissions · What each role can do with each content type. · Today's rules are the starting point · Owners and admins edit the schema. Any verified user can read, add, edit and delete entries. · Owner · Admin · User · Read · Create · Update · Delete · Built-in types. RenewCMS sets these rules. · Schema (create, edit and delete content types): owners and admins only. Set by RenewCMS. · No changes · Discard · Save permissions | Later |
| 2 | Changed, not saved | Two types restricted for the User role. | 4 changes not saved · Changed | Later |
### 9 Schema export and import (group "9 Export and import", 3 states)
Route: `/schema (dialogs)`. API: not built. Auth: Owner or admin.
All later. Dev-to-production flow: export a file, import it elsewhere, preview, same compatibility review as group 3, explicit confirm.
| # | State | Trigger | Copy | Scope |
|---|---|---|---|---|
| 1 | Export | Export on /schema. | Export schema · Download the fields of your content types as a file. Entries aren't included. · All content types · 3 content types · One content type · Choose which one · File name · renewcms-schema.json · Import this file on another RenewCMS site to create the same content types. · Cancel · Download file | Later |
| 2 | Import preview | A file was chosen. | Import schema · renewcms-schema.json · 3 content types · Create 1, change 1, no change 1 · Recipes · New content type with 4 fields. · Events · Add 2 fields, remove Description. Events has 37 entries on this site. · Removes data · Press mentions · Same as on this site. · Existing entries are checked against the changes when you import. If any entry doesn't fit, nothing is imported. · Cancel · Import schema | Later |
| 3 | Import refused | The server answers schema_incompatible. | Nothing was imported · Some entries on this site don't fit the imported fields. RenewCMS can't tell which entries. The flagged change can cause this. · Try again | Later |
+78
View File
@@ -0,0 +1,78 @@
# Schema
Route: `/schema`, `/schema/new`, `/schema/:key`. API: GET/POST /v1/content-type · GET/PUT/DELETE /v1/content-type/{key}. Auth: owner or admin.
Custom content types: an owner or admin defines a type (for example Events) made of 1 to 50 ordered fields; any verified user then writes entries. Everything about a type happens on one screen. Primary words: content type, field, choice list, entry. "Key" is kept for the API identifier. The key of a type is chosen at creation and never changes; the key and type of a saved field never change. Built-in types (Articles, Authors, Sites, Media, Users) are listed with a lock and a "Built-in" badge and open a read-only view. Non-owner, non-admin users see no Schema entry; a direct link shows a 403 page.
Visual reference: `RenewCMS Screens Schema.dc.html`, groups "Schema list", "Schema builder", "Review and delete", "Field types". Frames: `SchemaFrame.dc.html` mounted in `AppFrame.dc.html` (shell, sidebar, topbar, drawer). Every state is drawn in light and dark (theme switch) at 1440×900 (shown at 50%) and 390×844 (shown at 75%). Copy is exact. Strings in a Copy cell are separated by " · " and listed in reading order. Nothing is clock-sensitive.
### 1 Schema: list of types (group "1 Schema list", 6 states)
Route: `/schema, /schema/:key (built-in)`. API: GET /v1/content-type. Auth: Owner or admin.
Sidebar entry "Schema" for owners and admins only. Built-in types are listed with a lock and a Built-in badge, always after the custom ones. They open a read-only view. Sample data: the field counts of built-ins are illustrative.
| # | State | Trigger | Copy | Scope |
|---|---|---|---|---|
| 1 | Populated | An owner or admin opens /schema. | Schema · Content types and the fields they are made of. · New content type · Name · Key · Fields · Last updated · Built-in types are managed by RenewCMS. You can read their fields, but not change them. · Built-in · 3 content types · 5 built-in | Available now |
| 2 | Loading | First load or retry. Skeleton rows appear after 150 ms. New content type is disabled. | (skeleton) · New content type (disabled) | Available now |
| 3 | Empty: no custom type yet | GET /v1/content-type returns []. Built-ins are still listed below. | No content types yet · Create a content type to manage your own kind of content, like events or recipes. The built-in types stay as they are. · New content type | Available now |
| 4 | Error | 500 or network failure on the list request. | Couldn't load content types · GET /v1/content-type failed. Check your connection and try again. · Try again | Available now |
| 5 | Forbidden (403) | A user who is not owner or admin types /schema. There is no sidebar entry, so the page explains instead of redirecting. | You don't have access to Schema · Only owners and admins can change content types. You can still add and edit entries from the Content menu. · Go to Home | Available now |
| 6 | Built-in type: read-only view | Click Articles in the list. No edit, no delete, no add field. | Articles · Built-in · Managed by RenewCMS · Articles is a built-in type. You can read its fields here, but you can't edit it, delete it or add fields. · Label · Key · Type · Rules · Entries of built-in types are managed from their own screens, like Articles and Authors. | Available now |
### 2 Schema builder (group "2 Schema builder", 16 states)
Route: `/schema/new, /schema/:key`. API: POST /v1/content-type, GET/PUT /v1/content-type/{key}. Auth: Owner or admin.
One screen, three regions: type name and key on top, ordered field list on the left, field inspector on the right, collapsible API preview at the bottom. Mobile: the list is the page, the inspector is a 92% sheet, the API preview is a sheet. Field keys and types of saved fields are locked; fields added since the last save can still choose both.
| # | State | Trigger | Copy | Scope |
|---|---|---|---|---|
| 1 | New type | /schema/new. One starter field is added because a type needs at least one. | New content type · Name · For example, Events · Key · events · Used in URLs and the API. Lowercase letters, digits and hyphens. It can't change after you save. · Fields · 1 of 50 · Add field · Field: Title · Label · Key · The name used in the API. Starts with a letter. Lowercase letters, digits and underscores. · Type · Required · An entry can't be saved with this field empty. · Unique values · Default value · Used when an entry is created and this field is left out. · Shortest · Longest · Counted in characters. Entries show a counter. · Save · Discard | Available now |
| 2 | Editing an existing type | /schema/events with 37 entries. Key is locked, saved field keys and types are locked. | 37 entries use this content type. Changes are checked against them when you save. · Key (lock) · Used in the API, so it can't change. · Can't change after saving · Saved | Available now |
| 3 | Locked key: tooltip | Hover or focus the locked key. | The key is used in URLs and the API, so it can't change after the type is created. | Available now |
| 4 | Unsaved changes | Two fields added, Capacity changed, Description removed. Rows carry New and Changed badges; removal shows an undo row. | Unsaved changes · New · Changed · Description will be removed · Undo · Save · Discard | Available now |
| 5 | Field errors | Checked as the user types, and again on Save. The row is outlined and shows an alert icon. Save is disabled until all are fixed. | 3 problems to fix · Give the field a label. · Lowest value can't be above the highest value. · Choices can't be blank. · Two choices are the same. | Available now |
| 6 | Type-level errors | New type with no name, a one-letter key and no fields. | Give the content type a name. · Use 2 to 40 lowercase letters, digits or hyphens. · No fields yet · A content type needs at least one field. · 3 problems to fix | Available now |
| 7 | Field key error | A field added since the last save has an invalid key (hyphen). Checked as the user types. Field keys use underscores; type keys use hyphens. | Key · Start with a letter. Use lowercase letters, digits and underscores. · 1 problem to fix | Available now |
| 8 | Choice list editor | A Choice field is selected. Add, remove and reorder; blanks and duplicates are flagged per row. | Choices · 5 of 50 · Add a choice · Add · Add 1 to 50 choices. Each one needs a different name. Removing a choice that entries use will be refused when you save. · Choices can't be blank. · Two choices are the same. | Available now |
| 9 | Keyboard reorder | Focus the grip, press Space. Up and Down move, Space drops, Esc cancels. Move up, Move down and Remove buttons are on the selected row. | Moving Ends on. Position 2 of 7. Press Up or Down to move, Space to drop, Esc to cancel. (live region, polite) | Available now |
| 10 | API preview open | The panel at the bottom. Updates as fields change. Copy JSON copies the sample entry. | API preview · Where entries of this type live · A sample entry. Values come from each field's type and default. · Updates as you edit. Fields you add or remove here appear after you save. · Copy JSON · Copied | Available now |
| 11 | Saving | PUT in flight. Inputs dim, Save shows the loader, nothing can be dragged. | Saving… | Available now |
| 12 | Saved | 200. A toast confirms, the badges clear. | Saved at 11:02 · Content type saved · Events now has 8 fields. | Available now |
| 13 | Save failed | 500 or network failure. Nothing was sent as saved; the edits stay. | Save failed · Couldn't save the content type · Something went wrong on our side. Your changes are still here. Try again in a moment. · Try again | Available now |
| 14 | Key already taken | 409 content_type_key_taken on POST. | The key "events" is already used by another content type. Choose a different key. | Available now |
| 15 | Schema incompatible | 409 schema_incompatible on PUT. The review dialog (group 3) closes into this state. Changes of the kinds that can cause it are marked. | Nothing was changed · Some entries don't fit the new fields, so the whole change was refused. RenewCMS can't tell which entries. The changes that can cause this are marked. · Review changes · Possible cause | Available now |
| 16 | Offline | navigator.onLine is false. Edits are kept; Save is disabled. | You're offline. Changes will be saved when you reconnect. · Waiting for connection | Available now |
### 3 Schema change review and delete type (group "3 Review and delete", 7 states)
Route: `/schema/:key (dialogs)`. API: PUT /v1/content-type/{key}, DELETE /v1/content-type/{key}. Auth: Owner or admin.
The review opens on Save when the type already has entries (37 here). It is informational: the server decides compatibility. Destructive changes (removing a field or a choice, tightening a limit, making a field unique or required) carry a warning flag. Per-change entry counts and a full diff are later.
| # | State | Trigger | Copy | Scope |
|---|---|---|---|---|
| 1 | Review before saving | Save on a type that has entries. | Review changes to Events · Apply them to save the content type. · Add 2 fields, change 1, remove 1 · Events has 37 entries. Each one is checked against the new fields when you apply. · Add Speaker · Text, optional. · Add Room · Choice, required, default "Main hall". Existing entries get the default, so they still fit. · Change Capacity · Highest value goes from 5000 to 2000. · Entries may not fit · Remove Description · Entries stop returning its values. · Removes data · Flagged changes can be refused if existing entries don't fit. If that happens, nothing is changed. · Back to editing · Apply changes | Available now |
| 2 | Applying | PUT in flight. Dialog cannot be dismissed. | Applying… | Available now |
| 3 | Refused (schema_incompatible) | 409 schema_incompatible. States that nothing changed and names the kind of change that likely caused it, never an entry. | Nothing was changed · RenewCMS refused the changes because some entries don't fit the new fields. It doesn't say which entries. · Your content type is as it was · No field was added, changed or removed. · The change that can cause this in your edit · Possible cause · This kind of change is refused when an entry is over the new limit, a new required field has no default, a field becomes unique while entries share a value, or a removed choice is still in use. · Discard changes · Back to editing | Available now |
| 4 | Review with counts and diff | Per-change entry counts and a full diff need an API that does not exist yet. | Affects 0 entries · Affects 37 entries · Affects 3 entries · Affects 31 entries · View full diff · Per-change counts and diff come later | Later |
| 5 | Delete type: blocked | Delete content type on a type with entries. No confirm button. | You can't delete Events yet · A content type can only be deleted when it has no entries. · Events has 37 entries · Delete all of its entries first, then delete the content type. · Close · View entries | Available now |
| 6 | Delete type: confirm | Delete content type on an empty type. | Delete Recipes? · Recipes has no entries. Its fields and its API routes will be deleted. This can't be undone. · Key: recipes · Cancel · Delete content type | Available now |
| 7 | Delete type: server fallback (409) | 409 content_type_has_entries. An entry was added after the page loaded. | Recipes now has entries · Someone added an entry after this page loaded, so nothing was deleted. Delete the entries first, then try again. · Close · View entries | Available now |
### 4 Field-type gallery (group "4 Field types", 6 states)
Route: `reference board`. API: none. Auth: n/a.
One frame per type: inspector options, the entry form control (default and open states), the list cell with its empty state, the error message for each rule, and the filter widget. Filters are later: filtering on custom fields is not in the API. Mobile drops the inspector column (the builder frames show it as a sheet).
| # | State | Trigger | Copy | Scope |
|---|---|---|---|---|
| 1 | Text | type: "text" | Text · Short text, like a title or a name · Shortest · Longest · characters · 74 / 80 · Fill in Title. · Title must be text. · Title needs at least 3 characters. · Title can be up to 80 characters. · Another entry already uses this Title. Enter a different one. | Available now |
| 2 | Rich text | type: "richtext" | Rich text · Long text with formatting, written in Markdown · Write · Preview · Markdown. Switch to Preview to check the result. · 86 / 5000 · Not available for rich text. (Unique) | Available now |
| 3 | Number | type: "number" | Number · Whole or decimal numbers · Lowest value · Highest value · Enter a number · Between 1 and 5000. · Description must be a number. · Capacity must be at least 1. · Capacity must be at most 5000. | Available now |
| 4 | Yes or no | type: "boolean" | Yes or no · An on or off switch · On by default · Yes or no fields have no limits. · Not available for yes or no fields. (Unique) · Choose yes or no for Online. · Online must be yes or no. | Available now |
| 5 | Date | type: "date" | Date · A calendar day, without a time · Earliest date · Latest date · Pick a date · Pick a date for Starts on. · Starts on must be a date, like 2026-11-21. · Starts on can't be before 1 Jan 2026. · Starts on can't be after 31 Dec 2027. | Available now |
| 6 | Choice | type: "select" | Choice · One option from a list you define · Choices · Choose an option · Choose one of: Talk, Workshop or Meetup. · Another entry already uses this choice for Category. | Available now |
+5 -3
View File
@@ -14,6 +14,7 @@
<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><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>
<sc-if value="{{ contentShow }}"><div style="display:flex;flex-direction:column;gap:2px;margin-top:8px"><span style="padding:6px 10px 2px;font-size:11px;line-height:16px;font-weight:600;letter-spacing:.04em;text-transform:uppercase;color:var(--ui-text-muted)">Content</span><sc-if value="{{ contentColl }}"><div style="display:flex;align-items:center;gap:10px;height:32px;padding:0 10px;color:var(--ui-text-toned)"><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><span style="flex:1">All content types</span><span style="font-size:12px;color:var(--ui-text-muted)">{{ contentCount }}</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-right.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/chevron-right.svg') center / contain no-repeat"></span></div></sc-if><sc-for list="{{ contentRows }}" as="c" hint-placeholder-count="3"><div data-act="nav-content-{{ c.key }}" title="{{ c.name }}" style="display:flex;align-items:center;gap:10px;height:32px;padding:0 10px;background:{{ c.bg }};color:{{ c.fg }};font-weight:{{ c.fw }}"><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/{{ c.icon }}.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/{{ c.icon }}.svg') center / contain no-repeat"></span><span style="flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap">{{ c.name }}</span></div></sc-for><sc-if value="{{ contentMore }}"><div style="display:flex;align-items:center;gap:10px;height:32px;padding:0 10px;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/ellipsis.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/ellipsis.svg') center / contain no-repeat"></span><span>{{ contentMore }}</span></div></sc-if></div></sc-if>
<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>
<sc-if value="{{ notBoot }}"><div data-act="usermenu" role="button" aria-haspopup="menu" aria-expanded="{{ menuOpen }}" title="Account" style="display:flex;align-items:center;gap:10px;height:40px;padding:0 6px;background:{{ chipBg }};color:{{ chipFg }}"><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;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-weight:500">{{ who }}</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/chevrons-up-down.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/chevrons-up-down.svg') center / contain no-repeat"></span></div></sc-if>
@@ -368,7 +369,7 @@
</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><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="{{ 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><sc-if value="{{ contentShow }}"><div style="display:flex;flex-direction:column;gap:2px;margin-top:8px"><span style="padding:6px 10px 2px;font-size:11px;line-height:16px;font-weight:600;letter-spacing:.04em;text-transform:uppercase;color:var(--ui-text-muted)">Content</span><sc-if value="{{ contentColl }}"><div style="display:flex;align-items:center;gap:10px;height:44px;padding:0 10px;color:var(--ui-text-toned)"><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><span style="flex:1">All content types</span><span style="font-size:12px;color:var(--ui-text-muted)">{{ contentCount }}</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-right.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/chevron-right.svg') center / contain no-repeat"></span></div></sc-if><sc-for list="{{ contentRows }}" as="c" hint-placeholder-count="3"><div data-act="nav-content-{{ c.key }}" title="{{ c.name }}" style="display:flex;align-items:center;gap:10px;height:44px;padding:0 10px;background:{{ c.bg }};color:{{ c.fg }};font-weight:{{ c.fw }}"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:16px;height:16px;background-color:currentColor;-webkiLine truncated
<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 }}
@@ -387,9 +388,10 @@ 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'], ['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 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'], ['schema', 'shapes', 'Schema'], ['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, 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 CT = s.content || [], ctOn = s.contentOn, ctMax = 5, ctVis = CT.slice(0, Math.max(ctMax, CT.findIndex(x => x.key === ctOn) + 1)), contentRows = (m ? (s.contentOpen ? ctVis : []) : ctVis).map(x => { const on = x.key === ctOn; return { key: x.key, name: x.name, icon: x.icon || 'file-text', bg: on ? 'var(--rc-sand)' : 'transparent', fg: on ? 'var(--rc-on-sand)' : 'var(--ui-text-toned)', fw: on ? 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]
@@ -541,7 +543,7 @@ class Component extends DCLogic {
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,
upBtnDir: m ? 'column' : 'row', upBtnAlign: m ? 'stretch' : 'flex-start', cardPad: '16px', cardPadX: m ? '16px' : '20px', inH: m ? '44px' : '40px', pfCols: m ? 'minmax(0,1fr)' : 'minmax(0,1fr) minmax(0,1.4fr)', pwDir: m ? 'column' : 'row', pwAlign: m ? 'stretch' : 'flex-end', edTitle, edBody: e.body || '', sampleBody: !e.body, tabs, rows, save, counter, pub, mFields, up, toasts, endpoints, toolbar,
desk: !m, mob: m, notBoot: !s.boot,
contentShow: CT.length > 0, contentRows, contentColl: m && !s.contentOpen, contentCount: String(CT.length), contentMore: (!m || s.contentOpen) && CT.length > ctVis.length ? 'Show all ' + CT.length : '', desk: !m, mob: m, notBoot: !s.boot,
fw: m ? '390px' : '1440px', fh: m ? '844px' : '900px', dir: m ? 'column' : 'row',
mLead: s.mLead || 'menu',
navDrawer: m && !!s.drawer, isSlot: !!this.props.slotBody, slotBody: this.props.slotBody || null, slotOverlays: this.props.slotOverlays || null, isBoot: !!s.boot, isHome: k === 'home' && !s.boot, isList: k === 'articles', isEditor: k === 'editor', isInteg: k === 'integration', isKeys: k === 'apikeys', isError: k === 'error', isUsers: k === 'users',
@@ -0,0 +1,79 @@
<!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>
<helmet>
<meta name="design_doc_mode" content="canvas">
<link rel="icon" href="brand/favicon.svg">
<link href="https://fonts.googleapis.com/css2?family=IBM+Plex+Sans:wght@400;500;600&family=IBM+Plex+Mono:wght@400;500&display=swap" rel="stylesheet">
<style>body{margin:0;font-family:'IBM Plex Sans',sans-serif;font-size:13px;line-height:20px}*{box-sizing:border-box}a{color:inherit;text-underline-offset:3px}a:hover{opacity:.8}code{font-family:'IBM Plex Mono',monospace;font-size:12px}</style>
</helmet>
<div ref="{{ rootRef }}" data-screen-label="Schema screens" style="background:var(--rc-canvas);color:var(--ui-text);padding:64px;display:flex;flex-direction:column;gap:72px;width:max-content;min-width:100%">
<div style="display:flex;align-items:flex-end;gap:32px;max-width:1400px">
<div style="flex:1;display:flex;flex-direction:column;gap:10px">
<h1 style="margin:0;font:600 36px/44px 'IBM Plex Sans',sans-serif;letter-spacing:-0.02em;color:var(--ui-text-highlighted)">Screens: custom content types</h1>
<p style="margin:0;max-width:900px;font-size:16px;line-height:26px;color:var(--ui-text-toned);text-wrap:pretty">Schema list, builder, change review, field-type gallery, content navigation, entry list and entry editor, plus the later screens: relations, permissions, export and import. Every state at 1440 px (shown at 50%) and 390 px (shown at 75%); the switch shows dark. Each state is tagged <b>Available now</b> or <b>Later</b>. Spec tables at the end: scope, routes, components with their Nuxt UI mapping, errors, needs backend, decisions, accessibility. Same shell, tokens and copy tone as <a href="RenewCMS Screens Back-office.dc.html">the back-office board</a>. Changed in AppFrame: a Schema item and a Content group in the sidebar and the mobile drawer.</p>
</div>
<div role="radiogroup" aria-label="Theme" style="display:flex;border:1px solid var(--ui-border-accented);background:var(--ui-bg)">
<sc-for list="{{ modes }}" as="m" hint-placeholder-count="3">
<button role="radio" aria-checked="{{ m.on }}" onClick="{{ m.pick }}" style="all:unset;cursor:pointer;height:36px;padding:0 14px;display:flex;align-items:center;font-weight:500;font-size:14px;background:{{ m.bg }};color:{{ m.fg }}" style-focus-visible="outline:2px solid var(--ui-primary);outline-offset:2px">{{ m.label }}</button>
</sc-for>
</div>
</div>
<sc-for list="{{ groups }}" as="g" hint-placeholder-count="9">
<section data-screen-label="{{ g.label }}" style="display:flex;flex-direction:column;gap:28px">
<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)">{{ g.title }}</h2>
<div style="display:flex;gap:16px;flex-wrap:wrap;font:400 14px/22px 'IBM Plex Mono',monospace;color:var(--ui-text-toned)"><span>{{ g.route }}</span><span style="color:var(--ui-text-muted)">{{ g.api }}</span><span style="color:var(--ui-text-muted)">Auth: {{ g.auth }}</span></div>
<p style="margin:4px 0 0;font-size:15px;line-height:24px;color:var(--ui-text-toned);text-wrap:pretty">{{ g.note }}</p>
</div>
<div style="display:flex;flex-wrap:wrap;gap:48px 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;width:1037px">
<div style="display:flex;flex-direction:column;gap:2px"><span style="font:600 16px/24px 'IBM Plex Sans',sans-serif;color:var(--ui-text-highlighted)">{{ st.name }}<span style="margin-left:10px;padding:1px 6px;border:{{ st.chipBd }};color:var(--ui-text-toned);font:500 11px/16px 'IBM Plex Mono',monospace;vertical-align:middle">{{ st.scopeLabel }}</span></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"><dc-import name="SchemaFrame" s="{{ st.s }}" mobile="{{ false }}" hint-size="1440px,900px"></dc-import></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"><dc-import name="SchemaFrame" s="{{ st.s }}" mobile="{{ true }}" hint-size="390px,844px"></dc-import></div></div>
</div>
<p style="margin:0;font-size:12px;line-height:18px;color:var(--ui-text-muted);text-wrap:pretty"><b style="color:var(--ui-text-toned)">Copy:</b> {{ st.copy }}</p>
</div>
</sc-for>
</div>
</section>
</sc-for>
<sc-for list="{{ tables }}" as="t" hint-placeholder-count="3">
<section style="display:flex;flex-direction:column;gap:10px;max-width:1240px">
<h2 style="margin:0;font:600 22px/30px 'IBM Plex Sans',sans-serif;color:var(--ui-text-highlighted)">{{ t.title }}</h2>
<div style="background:var(--ui-bg);border:1px solid var(--ui-border)">
<div style="display:grid;grid-template-columns:{{ t.tpl }};gap:16px;padding:8px 12px;background:var(--ui-bg-elevated);color:var(--ui-text-muted);font-weight:500"><sc-for list="{{ t.cols }}" as="c" hint-placeholder-count="3"><span>{{ c }}</span></sc-for></div>
<sc-for list="{{ t.rows }}" as="r" hint-placeholder-count="4"><div style="display:grid;grid-template-columns:{{ t.tpl }};gap:16px;padding:10px 12px;border-top:1px solid var(--ui-border);line-height:20px"><sc-for list="{{ r.cells }}" as="c" hint-placeholder-count="3"><span style="color:var(--ui-text-highlighted);text-wrap:pretty;overflow-wrap:anywhere">{{ c }}</span></sc-for></div></sc-for>
</div>
</section>
</sc-for>
</div>
</x-dc>
<script type="text/x-dc" data-dc-script data-props="{&quot;theme&quot;:{&quot;editor&quot;:&quot;enum&quot;,&quot;default&quot;:&quot;light&quot;,&quot;options&quot;:[&quot;system&quot;,&quot;light&quot;,&quot;dark&quot;],&quot;tsType&quot;:&quot;string&quot;}}">
class Component extends DCLogic {
state = { mode: this.props.theme ?? 'light', spec: { groups: [], tables: [] } }
rootRef = React.createRef()
light = { '--ui-bg': '#ffffff', '--ui-bg-muted': '#fafafa', '--ui-bg-elevated': '#f3f2f0', '--ui-bg-accented': '#e6e4e0', '--ui-bg-inverted': '#111111', '--ui-text-dimmed': '#999999', '--ui-text-muted': '#666666', '--ui-text-toned': '#444444', '--ui-text': '#222222', '--ui-text-highlighted': '#111111', '--ui-text-inverted': '#ffffff', '--ui-border': '#e6e4e0', '--ui-border-muted': '#f3f2f0', '--ui-border-accented': '#8a8783', '--ui-primary': '#111111', '--ui-secondary': '#635643', '--ui-success': '#315b33', '--ui-info': '#34536d', '--ui-warning': '#6c4700', '--ui-error': '#882c21', '--rc-sand': '#e8dfd1', '--rc-on-sand': '#111111', '--rc-success-soft': '#eaefea', '--rc-info-soft': '#ebeef0', '--rc-warning-soft': '#f0ede6', '--rc-error-soft': '#f3eae9', '--rc-overlay': 'rgb(10 10 10 / 0.4)', '--rc-shadow-pop': '0 4px 16px rgb(17 17 17 / 0.08), 0 1px 2px rgb(17 17 17 / 0.06)', '--rc-shadow-modal': '0 16px 48px rgb(17 17 17 / 0.18)', '--rc-canvas': '#ecebe8' }
dark = { '--ui-bg': '#111111', '--ui-bg-muted': '#0a0a0a', '--ui-bg-elevated': '#1a1a1a', '--ui-bg-accented': '#222222', '--ui-bg-inverted': '#fafafa', '--ui-text-dimmed': '#666666', '--ui-text-muted': '#999999', '--ui-text-toned': '#cfccc7', '--ui-text': '#e6e4e0', '--ui-text-highlighted': '#fafafa', '--ui-text-inverted': '#111111', '--ui-border': '#333333', '--ui-border-muted': '#222222', '--ui-border-accented': '#666666', '--ui-primary': '#fafafa', '--ui-secondary': '#d4c5b0', '--ui-success': '#a3caa3', '--ui-info': '#a5c2db', '--ui-warning': '#dfb67d', '--ui-error': '#fba394', '--rc-sand': '#d4c5b0', '--rc-on-sand': '#111111', '--rc-success-soft': '#1f241f', '--rc-info-soft': '#202428', '--rc-warning-soft': '#2a251e', '--rc-error-soft': '#2c201f', '--rc-overlay': 'rgb(0 0 0 / 0.6)', '--rc-shadow-pop': '0 4px 16px rgb(0 0 0 / 0.5)', '--rc-shadow-modal': '0 16px 48px rgb(0 0 0 / 0.6)', '--rc-canvas': '#1c1c1c' }
resolved() { if (this.state.mode === 'system') return window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light'; return this.state.mode }
apply() { const el = this.rootRef.current; if (!el) return; const vars = this.resolved() === 'dark' ? this.dark : this.light; for (const k in vars) el.style.setProperty(k, vars[k]); document.body.style.background = vars['--rc-canvas'] }
componentDidMount() { this.apply(); import('./schema-spec.js').then(x => this.setState({ spec: { groups: x.groups, tables: x.tables } })).catch(() => {}) }
componentDidUpdate(p) { if (p.theme !== this.props.theme && this.props.theme) this.setState({ mode: this.props.theme }); this.apply() }
renderVals() {
const modes = [['system', 'System'], ['light', 'Light'], ['dark', 'Dark']].map(([k, label]) => { const on = this.state.mode === k; return { label, on, bg: on ? 'var(--ui-primary)' : 'transparent', fg: on ? 'var(--ui-bg)' : 'var(--ui-text-toned)', pick: () => this.setState({ mode: k }) } })
const groups = this.state.spec.groups.map(g => ({ ...g, states: g.states.map(s => ({ ...s, scopeLabel: s.scope === 'later' ? 'Later' : 'Available now', chipBd: s.scope === 'later' ? '1px dashed var(--ui-border-accented)' : '1px solid var(--ui-border-accented)' })) }))
const tables = this.state.spec.tables.map(t => ({ ...t, rows: t.rows.map(r => ({ cells: r })) }))
return { rootRef: this.rootRef, modes, groups, tables }
}
}
</script>
</body>
</html>
+426
View File
@@ -0,0 +1,426 @@
<!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>
<sc-if value="{{ framed }}" hint-placeholder-val="{{ true }}"><dc-import name="AppFrame" s="{{ shell }}" mobile="{{ mob }}" slot-body="{{ main }}" slot-overlays="{{ ov }}" hint-size="100%,100%"></dc-import></sc-if>
<sc-if value="{{ bare }}"><div style="width:{{ bw }};height:{{ bh }};overflow:hidden;position:relative;background:var(--ui-bg-muted);color:var(--ui-text);font-family:'IBM Plex Sans',sans-serif;font-size:13px;line-height:20px">{{ main }}</div></sc-if>
</x-dc>
<script type="text/x-dc" data-dc-script data-props="{&quot;$preview&quot;:{&quot;width&quot;:1440,&quot;height&quot;:900},&quot;s&quot;:{&quot;editor&quot;:null,&quot;tsType&quot;:&quot;object&quot;},&quot;mobile&quot;:{&quot;editor&quot;:null,&quot;tsType&quot;:&quot;boolean&quot;}}">
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 mono = 'font-family:\'IBM Plex Mono\',monospace;'
const bh = m ? 44 : 32, ih = m ? 44 : 32, 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)' : k === 'ghost' ? 'transparent' : '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 : k === 'ghost' ? 'transparent' : 'var(--ui-border-accented)'
return S('height:' + (o.h || bh) + 'px;' + (o.w ? 'width:' + o.w + '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;flex-shrink:0;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 IB = (ic, o = {}) => B(null, { k: 'ghost', icon: ic, w: o.w || (m ? 44 : 28), h: o.h || (m ? 44 : 28), px: 0, dis: o.dis, ring: o.ring, z: o.z || 16 })
const Alert = (tone, icon, title, text, ...actions) => 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-wrap:pretty', text)), actions.length > 0 && D('display:flex;gap:8px;flex-wrap:wrap', ...actions.map((a, i) => B(a, { icon: i === 0 && /again|Retry|Reload/.test(a) ? 'rotate-cw' : null, z: 14, h: m ? 44 : 28, fs: 12, px: 10, k: 'outline' })))))
const Later = (t = 'Later') => S('align-self:flex-start;height:20px;padding:0 6px;display:inline-flex;align-items:center;border:1px dashed var(--ui-border-accented);color:var(--ui-text-toned);white-space:nowrap;flex-shrink:0;font:500 11px/16px \'IBM Plex Mono\',monospace', t)
const BDG = { req: 'border:1px solid var(--ui-border-accented);color:var(--ui-text-toned)', uniq: 'border:1px solid var(--ui-border-accented);color:var(--ui-text-toned)', neu: 'background:var(--rc-sand);color:var(--rc-on-sand)', chg: 'background:var(--rc-info-soft);color:var(--ui-info)', err: 'background:var(--rc-error-soft);color:var(--ui-error)', warn: 'background:var(--rc-warning-soft);color:var(--ui-warning)', built: 'border:1px solid var(--ui-border-accented);color:var(--ui-text-toned)', ok: 'background:var(--rc-success-soft);color:var(--ui-success)' }
const Bd = (t, k, ic) => S('height:20px;padding:0 6px;display:inline-flex;align-items:center;gap:4px;font-size:12px;font-weight:500;white-space:nowrap;flex-shrink:0;' + BDG[k], ic && I(ic, 12), t)
const Seg = (opts, on, w) => D('display:flex;border:1px solid var(--ui-border-accented);width:' + (w || '100%'), ...opts.map(([k, t]) => S('flex:1;height:' + bh + 'px;padding:0 10px;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:' + fs + '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)') + ';' + (on ? '' : 'outline:1px solid var(--ui-border-accented);outline-offset:-1px'), S('width:14px;height:14px;background:var(--ui-bg)')), D('display:flex;flex-direction:column;gap:2px', lab && 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 Chk = on => S('width:16px;height:16px;flex-shrink:0;display:inline-flex;align-items:center;justify-content:center;box-sizing:border-box;border:1px solid ' + (on ? 'var(--ui-primary)' : 'var(--ui-border-accented)') + ';background:' + (on ? 'var(--ui-primary)' : 'var(--ui-bg)') + ';color:var(--ui-bg)', on && I('check', 12))
const Skel = (w, hh = 14) => S('display:block;height:' + hh + 'px;width:' + w + ';background:var(--ui-bg-accented)')
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.req && ' *', o.opt && S('font-weight:400;color:var(--ui-text-muted)', ' (optional)')), o.count && S(mono + 'font-size:12px;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 : 88) : 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 || o.lock ? 'var(--ui-bg-elevated)' : 'var(--ui-bg)') + ';font-size:' + fs + 'px;opacity:' + (o.dis ? 0.6 : 1), o.pre, S('flex:1;min-width:0;padding:' + (o.area ? '8px 10px' : '0 10px') + ';color:' + (o.ph || val === '' ? '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.phText ? o.phText : val), o.auto && Bd('Auto', 'neu'), o.auto && I('pencil', 14, 'margin:0 10px 0 8px;color:var(--ui-text-muted)'), o.lock && I('lock', 14, 'margin-right:10px;color:var(--ui-text-muted)'), o.sel && I('chevron-down', 14, 'margin-right:10px;color:var(--ui-text-muted)'), o.suffix && S('padding-right:10px;color:var(--ui-text-muted);font-size:12px', o.suffix), o.ico && I(o.ico, 14, 'margin-right:10px;color:var(--ui-text-muted)')),
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 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.later && Later(), 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 Sheet = (o, body, foot) => D('position:absolute;inset:0;z-index:' + (o.z || 40) + ';display:flex;align-items:flex-end;background:var(--rc-overlay)',
D('width:100%;height:92%;background:var(--ui-bg);box-shadow:var(--rc-shadow-modal);display:flex;flex-direction:column', 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:4px 6px 4px 16px;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), o.later && Later(), S('width:44px;height:44px;display:flex;align-items:center;justify-content:center;color:var(--ui-text-muted)', I('x'))),
D('flex:1;min-height:0;overflow:hidden;padding:16px;display:flex;flex-direction:column;gap:16px', body), foot && D('flex-shrink:0;padding:12px 16px;border-top:1px solid var(--ui-border);display:flex;gap:8px', foot)))
const Toast = (tone, icon, title, text, action) => D('position:absolute;z-index:60;display:flex;gap:10px;padding:12px 14px;background:var(--ui-bg);border:1px solid var(--ui-border);box-shadow:var(--rc-shadow-pop);' + (m ? 'left:16px;right:16px;bottom:' + (s.toastB || 16) + 'px' : 'right:24px;bottom:24px;width:356px'), S('margin-top:2px;display:flex;color:var(--ui-' + tone + ')', I(icon)), 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)', title), S('color:var(--ui-text-muted)', text)), action && B(action, { icon: 'rotate-cw', z: 14, h: m ? 44 : 28, fs: 12, px: 10 })), I('x'))
const Offline = () => D('flex-shrink:0;display:flex;align-items:center;gap:10px;padding:10px 16px;background:var(--ui-bg-inverted);color:var(--ui-text-inverted)', I('wifi-off'), S('flex:1', 'You\'re offline. Changes will be saved when you reconnect.'))
const Tip = t => D('position:absolute;z-index:30;width:260px;padding:8px 10px;background:var(--ui-bg-inverted);color:var(--ui-text-inverted);font-size:12px;line-height:18px;box-shadow:var(--rc-shadow-pop)', t)
const Page = (pad, ...c) => D('flex:1;min-width:0;min-height:0;display:flex;flex-direction:column;position:relative;overflow:hidden;padding:' + pad + ';gap:16px', ...c)
const Title = (t, sub, ...acts) => D('display:flex;align-items:flex-end;gap:16px;flex-wrap:wrap;flex-shrink:0', D('flex:1;min-width:200px;display:flex;flex-direction:column;gap:2px', !m && S('font:600 20px/28px \'IBM Plex Sans\',sans-serif;color:var(--ui-text-highlighted)', t), sub && S('color:var(--ui-text-muted)', sub)), ...acts)
const pad = m ? '16px' : '24px'
const Fab = l => m && D('position:absolute;left:16px;right:16px;bottom:16px;height:48px;z-index:5;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), l)
const Center = (icon, title, text, ...acts) => D('flex:1;display:flex;align-items:center;justify-content:center;padding:24px', D('max-width:420px;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:600 24px/32px \'IBM Plex Sans\',sans-serif;color:var(--ui-text-highlighted)', title), S('color:var(--ui-text-muted);text-wrap:pretty', text), D('display:flex;gap:8px', ...acts)))
const Empty = (icon, title, text, action) => D('background:var(--ui-bg);border:1px solid var(--ui-border);padding:40px 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:360px;text-wrap:pretty', text), action && B(action, { k: 'primary', icon: 'plus', px: 16 }))
// ---------- data
const FT = { text: ['type', 'Text', 'Short text, like a title or a name'], richtext: ['pilcrow', 'Rich text', 'Long text with formatting, written in Markdown'], number: ['hash', 'Number', 'Whole or decimal numbers'], boolean: ['toggle-left', 'Yes or no', 'An on or off switch'], date: ['calendar', 'Date', 'A calendar day, without a time'], select: ['list', 'Choice', 'One option from a list you define'] }
const EV = [
{ key: 'title', label: 'Title', type: 'text', req: true, uniq: true, max: 80 }, { key: 'starts_on', label: 'Starts on', type: 'date', req: true }, { key: 'ends_on', label: 'Ends on', type: 'date' },
{ key: 'online', label: 'Online', type: 'boolean', def: false }, { key: 'capacity', label: 'Capacity', type: 'number', min: 1, max: 5000 }, { key: 'category', label: 'Category', type: 'select', opts: ['Talk', 'Workshop', 'Meetup'] }, { key: 'description', label: 'Description', type: 'richtext' }].map(f => ({ ...f, saved: true }))
const RC = [{ key: 'title', label: 'Title', type: 'text', req: true }, { key: 'servings', label: 'Servings', type: 'number', min: 1 }, { key: 'vegetarian', label: 'Vegetarian', type: 'boolean' }, { key: 'method', label: 'Method', type: 'richtext' }].map(f => ({ ...f, saved: true }))
const SPK = { key: 'speaker', label: 'Speaker', type: 'text', isNew: true }, ROOM = { key: 'room', label: 'Room', type: 'select', req: true, def: 'Main hall', opts: ['Main hall', 'Studio'], isNew: true }
const CAPC = { ...EV[4], max: 2000, changed: true }
const DIRTY = [EV[0], EV[1], EV[2], EV[3], CAPC, EV[5], SPK, ROOM]
const CT = n => ['Events', 'Recipes', 'Press mentions', 'Frequently asked questions and answers', 'Job openings', 'Testimonials', 'Suppliers', 'Certifications', 'Case studies', 'Glossary terms', 'Partners', 'Downloads', 'Locations', 'Awards'].slice(0, n).map(x => ({ key: x === 'Events' ? 'events' : x.toLowerCase().replace(/[^a-z0-9]+/g, '-'), name: x, icon: 'files' }))
const shell = { kind: 'slot', display: 'Marta Alves', role: s.role || 'owner', content: CT(s.many ? 14 : 3), contentOn: 'events', navBadge: false }
const BUILTIN = [['Articles', 'articles', 5], ['Authors', 'authors', 5], ['Sites', 'sites', 8], ['Media', 'media', 6], ['Users', 'users', 6]]
const CUSTOM = [['Events', 'events', 7, '15 Oct 2026'], ['Recipes', 'recipes', 4, '2 Oct 2026'], ['Press mentions', 'press-mentions', 5, '18 Sep 2026']]
const ROWS = [
{ id: 42, title: 'Lime plaster workshop', starts_on: '21 Nov 2026', ends_on: '22 Nov 2026', online: false, capacity: 18, category: 'Workshop', description: 'Two days of hands-on work with lime putty and old stone.', c: '12 Oct 2026', u: '15 Oct 2026, 11:02', by: 'Marta Alves' },
{ id: 41, title: 'Heat pumps: what the numbers say', starts_on: '3 Nov 2026', ends_on: '', online: true, capacity: 500, category: 'Talk', description: 'A look at running costs after two winters.', c: '8 Oct 2026', u: '14 Oct 2026, 16:40', by: 'Jonas Pereira' },
{ id: 40, title: 'Open day at the Rue Verte site', starts_on: '12 Nov 2026', ends_on: '12 Nov 2026', online: false, capacity: 120, category: 'Meetup', description: '', c: '2 Oct 2026', u: '12 Oct 2026, 09:15', by: 'Inès Duarte' },
{ id: 39, title: 'Winter windows clinic', starts_on: '5 Dec 2026', ends_on: '', online: false, capacity: null, category: 'Workshop', description: 'Bring a window, leave with a plan.', c: '30 Sep 2026', u: '9 Oct 2026, 14:22', by: 'Marta Alves' },
{ id: 38, title: 'Timber joinery for beginners', starts_on: '14 Jan 2027', ends_on: '15 Jan 2027', online: false, capacity: 12, category: 'Workshop', description: 'Mortise, tenon and a lot of patience.', c: '28 Sep 2026', u: '7 Oct 2026, 10:05', by: 'Inès Duarte' },
{ id: 37, title: 'Q&A with the site managers', starts_on: '28 Oct 2026', ends_on: '', online: true, capacity: null, category: 'Meetup', description: '', c: '21 Sep 2026', u: '2 Oct 2026, 17:48', by: 'Jonas Pereira' },
{ id: 36, title: 'Reclaimed floorboards talk', starts_on: '17 Oct 2026', ends_on: '', online: false, capacity: 60, category: 'Talk', description: 'Where to find them and how to lay them.', c: '14 Sep 2026', u: '29 Sep 2026, 08:30', by: 'Marta Alves' }]
const mdSample = 'Two days of hands-on work with **lime putty** and old stone.\n\n- Bring work clothes\n- Lunch is included'
const sampleVal = f => f.type === 'text' ? (f.def ?? 'Example text') : f.type === 'richtext' ? (f.def ?? 'Markdown text') : f.type === 'number' ? (f.def ?? f.min ?? 0) : f.type === 'boolean' ? (f.def ?? false) : f.type === 'date' ? (f.def ?? '2026-11-21') : (f.def ?? (f.opts && f.opts[0]) ?? null)
const apiJson = (fs_, key) => JSON.stringify({ id: 42, content_type: key, data: Object.fromEntries(fs_.map(f => [f.key, sampleVal(f)])), created_by: 3, updated_by: 3, created_at: '2026-10-15T11:02:00Z', updated_at: '2026-10-15T11:02:00Z' }, null, 2)
const MM = t => t === 'number' ? ['Lowest value', 'Highest value', ''] : t === 'date' ? ['Earliest date', 'Latest date', ''] : ['Shortest', 'Longest', 'characters']
const dot = (t, ic) => S('display:inline-flex;align-items:center;gap:6px', I(ic, 14), t)
// ---------- inspector
const Insp = (f, o = {}) => {
const t = f.type, e = f.err || {}, one = m || o.one, locked = !!f.saved
const [mnL, mxL, suf] = MM(t), canU = ['text', 'number', 'date', 'select'].includes(t), hasMM = ['text', 'richtext', 'number', 'date'].includes(t)
const g2 = one ? '1fr' : '1fr 1fr'
const tile = k => { const on = k === t, dim = locked && !on; return D('display:flex;gap:10px;align-items:flex-start;padding:10px;min-height:56px;border:1px solid ' + (on ? 'var(--ui-primary)' : 'var(--ui-border-accented)') + ';background:' + (on ? 'var(--rc-sand)' : 'var(--ui-bg)') + ';color:' + (on ? 'var(--rc-on-sand)' : 'var(--ui-text-highlighted)') + ';opacity:' + (dim ? 0.4 : 1), I(FT[k][0], 16, 'margin-top:2px'), D('display:flex;flex-direction:column;min-width:0', S('font-weight:500', FT[k][1]), S('font-size:12px;line-height:16px;color:' + (on ? 'var(--rc-on-sand)' : 'var(--ui-text-muted)') + ';text-wrap:pretty', FT[k][2]))) }
const mmErr = e.min || ''
const minV = f.min != null ? String(f.min) : '', maxV = f.max != null ? String(f.max) : ''
const defCtl = t === 'boolean' ? Sw(!!f.def, 'On by default', 'New entries start with this switch ' + (f.def ? 'on' : 'off') + ' when the field is left out.') : F('Default value', f.def != null ? String(f.def) : '', { opt: true, ph: f.def == null, phText: t === 'select' ? 'None' : t === 'date' ? 'No default' : 'No default', sel: t === 'select', ico: t === 'date' ? 'calendar' : null, area: t === 'richtext', err: e.def, dis: !!f.uniq, help: f.uniq ? 'A field with unique values can\'t have a default.' : e.def ? '' : 'Used when an entry is created and this field is left out.' })
const left = D('display:flex;flex-direction:column;gap:14px;min-width:0', Sw(!!f.req, 'Required', 'An entry can\'t be saved with this field empty.'), Sw(!!f.uniq, 'Unique values', canU ? 'Each entry needs a different value.' : t === 'richtext' ? 'Not available for rich text.' : 'Not available for yes or no fields.', !canU), defCtl)
const right = hasMM ? D('display:flex;flex-direction:column;gap:14px;min-width:0', F(mnL, minV, { suffix: suf, ph: minV === '', phText: 'No minimum', err: mmErr, help: mmErr ? '' : null }), F(mxL, maxV, { suffix: suf, ph: maxV === '', phText: 'No maximum', help: mmErr ? '' : t === 'text' || t === 'richtext' ? 'Counted in characters. Entries show a counter.' : t === 'number' ? 'Entries outside the range are refused.' : 'Entries outside the range are refused.' })) : D('display:flex;flex-direction:column;gap:6px;min-width:0', S('font-weight:500;color:var(--ui-text-highlighted)', 'Limits'), S('color:var(--ui-text-muted);font-size:12px;line-height:18px', t === 'boolean' ? 'Yes or no fields have no limits.' : 'Limits come from the choices below.'))
const ch = t === 'select' ? Choices(f) : null
return D('display:flex;flex-direction:column;gap:' + (m ? 16 : 14) + 'px;min-width:0',
D('display:grid;grid-template-columns:' + g2 + ';gap:14px', F('Label', f.label, { req: true, err: e.label, focus: o.focus === 'label', ph: !f.label, phText: 'For example, Title' }),
D('display:flex;flex-direction:column;gap:6px;min-width:0', F('Key', f.key || '', { mono: true, auto: !locked && !e.key && !!f.key, lock: locked, err: e.key, ph: !f.key, phText: 'title', dis: false, help: locked ? 'Used in the API, so it can\'t change.' : e.key ? '' : 'The name used in the API. Lowercase letters, digits and underscores.' }))),
D('display:flex;flex-direction:column;gap:6px', D('display:flex;justify-content:space-between;gap:8px', S('font-weight:500;color:var(--ui-text-highlighted)', 'Type'), locked && S('color:var(--ui-text-muted);font-size:12px;display:flex;gap:4px;align-items:center', I('lock', 12), 'Can\'t change after saving')), D('display:grid;grid-template-columns:repeat(' + (one ? 2 : 3) + ',minmax(0,1fr));gap:8px', ...Object.keys(FT).map(tile))),
D('display:grid;grid-template-columns:' + g2 + ';gap:14px;align-items:start', left, right),
ch)
}
const Choices = f => {
const e = f.err || {}, ops = f.opts || [], bad = e.choices || {}
return D('display:flex;flex-direction:column;gap:8px', D('display:flex;justify-content:space-between', S('font-weight:500;color:var(--ui-text-highlighted)', 'Choices', ' *'), S(mono + 'font-size:12px;color:var(--ui-text-muted)', ops.length + ' of 50')),
...ops.map((o_, i) => D('display:flex;flex-direction:column;gap:4px', D('display:flex;align-items:center;gap:4px', 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('grip-vertical', 16)), D('flex:1;height:' + ih + 'px;display:flex;align-items:center;padding:0 10px;font-size:' + fs + 'px;border:1px solid ' + (bad[i] ? 'var(--ui-error)' : 'var(--ui-border-accented)') + ';background:var(--ui-bg);color:' + (o_ ? 'var(--ui-text-highlighted)' : 'var(--ui-text-muted)'), o_ || 'Choice'), IB('x')), bad[i] && S('margin-left:' + (m ? 48 : 32) + 'px;display:flex;gap:6px;color:var(--ui-error);font-size:12px;line-height:18px', I('circle-alert', 14, 'margin-top:2px'), bad[i]))),
D('display:flex;gap:8px;padding-left:' + (m ? 48 : 32) + 'px', D('flex:1;height:' + ih + 'px;display:flex;align-items:center;padding:0 10px;border:1px dashed var(--ui-border-accented);color:var(--ui-text-muted);font-size:' + fs + 'px', 'Add a choice'), B('Add', { icon: 'plus' })),
S('color:var(--ui-text-muted);font-size:12px;line-height:18px', 'Add 1 to 50 choices. Each one needs a different name. Removing a choice that entries use will be refused when you save.'))
}
// ---------- field list
const FRow = (f, i, o = {}) => {
const on = o.sel === i, err = !!f.err, kb = o.kb === i
const rm = on && D('display:flex;gap:2px;margin-left:auto', IB('chevron-up', { dis: i === 0 }), IB('chevron-down'), IB('trash-2'))
return D('display:flex;align-items:center;gap:' + (m ? 4 : 2) + 'px;min-height:' + (m ? 64 : 56) + 'px;padding:6px 8px 6px 4px;border:1px solid ' + (err ? 'var(--ui-error)' : kb ? 'var(--ui-primary)' : 'var(--ui-border)') + ';' + (kb ? 'outline:2px solid var(--ui-primary);outline-offset:-1px;box-shadow:var(--rc-shadow-pop);' : '') + 'background:' + (on ? 'var(--rc-sand)' : 'var(--ui-bg)') + ';color:' + (on ? 'var(--rc-on-sand)' : 'var(--ui-text-highlighted)') + ';opacity:' + (o.dim ? 0.6 : 1),
S('width:' + (m ? 36 : 24) + 'px;height:32px;display:flex;align-items:center;justify-content:center;flex-shrink:0;color:' + (on ? 'var(--rc-on-sand)' : 'var(--ui-text-muted)'), I('grip-vertical', 16)),
S('width:28px;height:28px;flex-shrink:0;display:flex;align-items:center;justify-content:center;background:' + (on ? 'var(--ui-bg)' : 'var(--ui-bg-elevated)') + ';color:var(--ui-text-highlighted)', I(FT[f.type][0], 16)),
D('flex:1;min-width:0;display:flex;flex-direction:column;margin-left:8px', S('font-weight:500;overflow:hidden;text-overflow:ellipsis;white-space:nowrap', f.label || 'Untitled field'), S(mono + 'font-size:12px;line-height:16px;color:' + (on ? 'var(--rc-on-sand)' : 'var(--ui-text-muted)') + ';overflow:hidden;text-overflow:ellipsis;white-space:nowrap', f.key || '–')),
!on && D('display:flex;gap:4px;flex-shrink:0;align-items:center', f.isNew && Bd('New', 'neu'), f.changed && Bd('Changed', 'chg'), o.cause && f.changed && Bd('Possible cause', 'warn', 'triangle-alert'), f.req && Bd('Required', 'req'), f.uniq && Bd('Unique', 'uniq'), err && I('circle-alert', 16, 'color:var(--ui-error)')),
on && D('display:flex;gap:4px;flex-shrink:0;align-items:center;margin-right:2px', f.isNew && Bd('New', 'neu'), f.changed && Bd('Changed', 'chg'), f.req && Bd('Required', 'req'), f.uniq && Bd('Unique', 'uniq')), on && !m && rm)
}
const ApiPanel = (fl, key, open) => {
const routes = [['GET', '/v1/content-type/' + key + '/entry'], ['POST', '/v1/content-type/' + key + '/entry'], ['GET', '/v1/content-type/' + key + '/entry/{id}'], ['PUT', '/v1/content-type/' + key + '/entry/{id}'], ['DELETE', '/v1/content-type/' + key + '/entry/{id}']]
const head = D('height:44px;flex-shrink:0;display:flex;align-items:center;gap:10px;padding:0 ' + (m ? 12 : 24) + 'px;border-top:1px solid var(--ui-border);background:var(--ui-bg);color:var(--ui-text-highlighted)', I(open ? 'chevron-down' : 'chevron-right', 14), S('font-weight:600', 'API preview'), !m && S(mono + 'font-size:12px;color:var(--ui-text-muted);flex:1;overflow:hidden;text-overflow:ellipsis;white-space:nowrap', 'GET /v1/content-type/' + key + '/entry'), m && S('flex:1'), B('Copy JSON', { icon: 'copy', h: m ? 44 : 28, fs: 12, px: 10 }))
if (!open) return head
return D('flex-shrink:0;display:flex;flex-direction:column', head, D('display:grid;grid-template-columns:1fr 1.4fr;gap:16px;height:248px;padding:0 24px 16px;background:var(--ui-bg)', D('display:flex;flex-direction:column;gap:6px;min-width:0', S('color:var(--ui-text-muted);font-size:12px', 'Where entries of this type live'), D('display:flex;flex-direction:column;gap:2px;padding:10px 12px;background:var(--ui-bg-elevated);border:1px solid var(--ui-border)', ...routes.map(r => S(mono + 'font-size:12px;line-height:19px;color:var(--ui-text-highlighted);white-space:nowrap;overflow:hidden;text-overflow:ellipsis', S('display:inline-block;width:56px;color:var(--ui-text-muted)', r[0]), r[1]))), S('color:var(--ui-text-muted);font-size:12px;line-height:18px;text-wrap:pretty', 'Updates as you edit. Fields you add or remove here appear after you save.')), D('display:flex;flex-direction:column;gap:6px;min-width:0', S('color:var(--ui-text-muted);font-size:12px', 'A sample entry. Values come from each field\'s type and default.'), S('display:block;flex:1;overflow:hidden;padding:10px 12px;background:var(--ui-bg-elevated);border:1px solid var(--ui-border);white-space:pre;' + mono + 'font-size:12px;line-height:19px;color:var(--ui-text-highlighted)', apiJson(fl, key)))))
}
const stChip = (kind, n) => { const M = { 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)'], fail: ['circle-alert', 'Save failed', 'var(--ui-error)'], offline: ['wifi-off', 'Waiting for connection', 'var(--ui-text-muted)'], errs: ['circle-alert', n + (n === 1 ? ' problem' : ' problems') + ' to fix', 'var(--ui-error)'] }[kind]; return S('display:flex;align-items:center;gap:6px;white-space:nowrap;font-size:12px;color:' + M[2], I(M[0], 14), M[1]) }
// ---------- entry controls
const hint = f => { const t = f.type; if (t === 'text' || t === 'richtext') return [f.min && 'At least ' + f.min + ' characters', f.max && 'Up to ' + f.max + ' characters', f.uniq && 'Each entry needs a different one'].filter(Boolean).join('. ') + (f.min || f.max || f.uniq ? '.' : ''); if (t === 'number') return f.min != null && f.max != null ? 'Between ' + f.min + ' and ' + f.max + '.' : f.min != null ? 'At least ' + f.min + '.' : f.max != null ? 'At most ' + f.max + '.' : ''; if (t === 'date') return [f.min && 'From ' + f.min, f.max && 'until ' + f.max].filter(Boolean).join(' ') ; return t === 'select' ? '' : '' }
const MdBox = (o, val) => D('display:flex;flex-direction:column;border:1px solid ' + (o.err ? 'var(--ui-error)' : o.focus ? 'var(--ui-primary)' : 'var(--ui-border-accented)') + ';background:' + (o.dis ? 'var(--ui-bg-elevated)' : 'var(--ui-bg)') + (o.err ? ';box-shadow:inset 0 0 0 1px var(--ui-error)' : ''),
D('display:flex;align-items:center;border-bottom:1px solid var(--ui-border);padding:0 6px;gap:2px;overflow:hidden', D('display:flex;gap:14px;padding:0 6px;margin-right:8px', ...[['write', 'Write'], ['preview', 'Preview']].map(([k, t]) => S('height:' + (m ? 44 : 32) + 'px;display:flex;align-items:center;font-weight:' + (o.tab === k || (!o.tab && k === 'write') ? 500 : 400) + ';color:' + (o.tab === k || (!o.tab && k === 'write') ? 'var(--ui-text-highlighted)' : 'var(--ui-text-toned)') + ';border-bottom:2px solid ' + (o.tab === k || (!o.tab && k === 'write') ? 'var(--ui-primary)' : 'transparent'), t))), ...(o.tab === 'preview' ? [] : ['bold', 'italic', 'heading', 'link', 'list'].map(ic => S('width:' + (m ? 40 : 28) + 'px;height:' + (m ? 40 : 28) + 'px;display:flex;align-items:center;justify-content:center;color:var(--ui-text-toned)', I(ic, 16))))),
o.tab === 'preview' ? D('padding:10px 12px;min-height:' + (m ? 120 : 96) + 'px;display:flex;flex-direction:column;gap:8px;font-size:' + fs + 'px', S('', 'Two days of hands-on work with ', S('font-weight:600', 'lime putty'), ' and old stone.'), D('display:flex;flex-direction:column;gap:2px;padding-left:18px', S('display:list-item;list-style:square', 'Bring work clothes'), S('display:list-item;list-style:square', 'Lunch is included'))) : S('display:block;white-space:pre-wrap;padding:8px 10px;min-height:' + (m ? 120 : 96) + 'px;font-size:' + (m ? 14 : 12) + 'px;line-height:' + (m ? 22 : 19) + 'px;' + mono + 'color:' + (val ? 'var(--ui-text-highlighted)' : 'var(--ui-text-muted)'), val || 'Write in Markdown'))
const Cal = () => { const cells = [...Array(6).fill(''), ...Array.from({ length: 30 }, (_, i) => i + 1)]; return D('width:' + (m ? 280 : 252) + 'px;padding:8px;background:var(--ui-bg);border:1px solid var(--ui-border);box-shadow:var(--rc-shadow-pop)', D('display:flex;align-items:center;justify-content:space-between;height:32px', IB('chevron-left'), S('font-weight:600', 'November 2026'), IB('chevron-right')), D('display:grid;grid-template-columns:repeat(7,1fr)', ...['Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa', 'Su'].map(d => S('height:28px;display:flex;align-items:center;justify-content:center;font-size:12px;color:var(--ui-text-muted)', d)), ...cells.map(c => S('height:' + (m ? 34 : 30) + 'px;display:flex;align-items:center;justify-content:center;background:' + (c === 21 ? 'var(--ui-primary)' : 'transparent') + ';color:' + (c === 21 ? 'var(--ui-bg)' : 'var(--ui-text-highlighted)'), c))) ) }
const Ctl = (f, o = {}) => {
const t = f.type, v = o.v == null ? '' : String(o.v)
const lab = D('display:flex;justify-content:space-between;gap:8px', S('font-weight:500;color:var(--ui-text-highlighted)', f.label, f.req && ' *'), o.count && S(mono + 'font-size:12px;color:' + (o.countErr ? 'var(--ui-error)' : 'var(--ui-text-muted)'), o.count), o.def && Bd('Default', 'neu'))
const bd = o.err ? 'var(--ui-error)' : o.focus ? 'var(--ui-primary)' : 'var(--ui-border-accented)'
const box = (...inner) => D('display:flex;align-items:center;min-height:' + ih + 'px;border:1px solid ' + bd + ';background:' + (o.dis ? 'var(--ui-bg-elevated)' : 'var(--ui-bg)') + ';font-size:' + fs + 'px;' + (o.err ? 'box-shadow:inset 0 0 0 1px var(--ui-error);' : o.focus ? 'box-shadow:inset 0 0 0 1px var(--ui-primary);' : ''), ...inner)
const txt = (val, ph) => S('flex:1;min-width:0;padding:0 10px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;color:' + (val ? 'var(--ui-text-highlighted)' : 'var(--ui-text-muted)'), val || ph || '')
let ctl
if (t === 'boolean') ctl = Sw(v === 'true', v === 'true' ? 'On' : 'Off', null, o.dis)
else if (t === 'richtext') ctl = MdBox(o, v)
else if (t === 'number') ctl = box(txt(v, 'Enter a number'), D('display:flex;border-left:1px solid var(--ui-border);height:' + ih + 'px;color:var(--ui-text-muted)', S('width:' + (m ? 40 : 28) + 'px;display:flex;align-items:center;justify-content:center', I('minus', 14)), S('width:' + (m ? 40 : 28) + 'px;display:flex;align-items:center;justify-content:center;border-left:1px solid var(--ui-border)', I('plus', 14))))
else if (t === 'date') ctl = box(txt(v, 'Pick a date'), I('calendar', 14, 'margin-right:10px;color:var(--ui-text-muted)'))
else if (t === 'select') ctl = box(txt(v, 'Choose an option'), I('chevron-down', 14, 'margin-right:10px;color:var(--ui-text-muted)'))
else ctl = box(txt(v, ''))
const hp = o.help === undefined ? hint(f) : o.help
return D('display:flex;flex-direction:column;gap:6px;min-width:0;position:relative', lab, ctl, 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.err && hp && S('color:var(--ui-text-muted);font-size:12px;line-height:18px;text-wrap:pretty', hp), o.extra)
}
const Cell = (f, v) => {
if (v === undefined || v === null || v === '') return S('color:var(--ui-text-muted)', '–')
if (f.type === 'boolean') return S('display:flex;align-items:center;gap:6px', I(v ? 'check' : 'minus', 14, 'color:var(--ui-text-muted)'), v ? 'Yes' : 'No')
if (f.type === 'select') return S('height:20px;padding:0 6px;display:inline-flex;align-items:center;border:1px solid var(--ui-border-accented);color:var(--ui-text-toned);font-size:12px;justify-self:start', v)
if (f.type === 'number') return S('justify-self:end;font-variant-numeric:tabular-nums', v)
return S('overflow:hidden;text-overflow:ellipsis;white-space:nowrap;' + (f.type === 'richtext' ? 'color:var(--ui-text-toned)' : ''), v)
}
const mt = (k) => k === 'true' || k === 'false'
// ---------- pages
let main = null; const ov = []; let bare = false, bw = '1440px', bhh = '900px'
const v = s.v, k = s.k
// 1 schema list
const typesTable = (custom) => {
const cols = '24px minmax(0,1.4fr) minmax(0,1fr) 90px 150px 24px'
const hdr = 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', S('', ''), S('', 'Name'), S('', 'Key'), S('', 'Fields'), S('', 'Last updated'), S('', ''))
const r = (name, key, n, up, built) => D('display:grid;grid-template-columns:' + cols + ';gap:12px;height:48px;align-items:center;padding:0 12px;border-top:1px solid var(--ui-border)', I(built ? 'lock' : 'file-stack', 16, 'color:var(--ui-text-muted)'), D('display:flex;align-items:center;gap:8px;min-width:0', S('font-weight:500;color:var(--ui-text-highlighted)', name), built && Bd('Built-in', 'built', 'lock')), S(mono + 'font-size:12px;color:var(--ui-text-muted)', key), S('', String(n)), S('color:var(--ui-text-muted)', up || 'Managed by RenewCMS'), I('chevron-right', 14, 'color:var(--ui-text-muted)'))
const mr = (name, key, n, up, built) => D('display:flex;align-items:center;gap:12px;padding:12px 8px 12px 16px;border-top:1px solid var(--ui-border);min-height:68px', D('flex:1;min-width:0;display:flex;flex-direction:column;gap:4px', D('display:flex;align-items:center;gap:8px;flex-wrap:wrap', S('font-weight:500;font-size:15px;line-height:21px;color:var(--ui-text-highlighted)', name), built && Bd('Built-in', 'built', 'lock')), S('font-size:12px;color:var(--ui-text-muted)', S(mono, key), ' · ' + n + ' fields' + (up ? ' · Updated ' + up : ''))), S('width:36px;height:44px;display:flex;align-items:center;justify-content:center;color:var(--ui-text-muted)', I('chevron-right', 18)))
const note = D('display:flex;align-items:center;gap:8px;padding:10px 12px;border-top:1px solid var(--ui-border);background:var(--ui-bg-muted);color:var(--ui-text-toned);font-size:12px;line-height:18px', I('lock', 14, 'flex-shrink:0'), S('', 'Built-in types are managed by RenewCMS. You can read their fields, but not change them.'))
const rr = m ? mr : r
return D('background:var(--ui-bg);border:1px solid var(--ui-border)', !m && hdr, ...(custom ? CUSTOM.map(x => rr(x[0], x[1], x[2], x[3])) : []), note, ...BUILTIN.map(x => rr(x[0], x[1], x[2], '', true)))
}
if (v === 'types') {
Object.assign(shell, { nav: 'schema', crumbs: ['Schema'], mTitle: 'Schema' })
const newBtn = B('New content type', { k: 'primary', icon: 'plus', px: 14, dis: k === 'loading' })
const impExp = s.later ? [B('Import', { icon: 'upload' }), B('Export', { icon: 'download' })] : []
if (k === 'forbidden') { shell.role = 'user'; shell.crumbs = ['Schema']; main = Center('lock', 'You don\'t have access to Schema', 'Only owners and admins can change content types. You can still add and edit entries from the Content menu.', B('Go to Home', { k: 'primary', px: 16 })) }
else if (k === 'builtin') {
shell.crumbs = ['Schema', 'Articles']; shell.mTitle = 'Articles'; shell.mLead = 'arrow-left'
const AF = [['Title', 'title', 'text', 'Required · up to 200 characters'], ['Slug', 'slug', 'text', 'Required · unique'], ['Body', 'body', 'richtext', 'Up to 10,000 characters'], ['Online', 'online', 'boolean', 'Off by default'], ['Published on', 'published_on', 'date', '']]
const cols = '28px minmax(0,1fr) minmax(0,1fr) 120px minmax(0,1.2fr)'
main = Page(pad, D('display:flex;align-items:center;gap:12px;flex-shrink:0', I('lock', 18, 'color:var(--ui-text-muted)'), S('font:600 20px/28px \'IBM Plex Sans\',sans-serif;color:var(--ui-text-highlighted)', 'Articles'), Bd('Built-in', 'built', 'lock')),
Alert('info', 'info', 'Managed by RenewCMS', 'Articles is a built-in type. You can read its fields here, but you can\'t edit it, delete it or add fields.'),
m ? D('background:var(--ui-bg);border:1px solid var(--ui-border)', ...AF.map(f => D('display:flex;gap:12px;align-items:center;padding:12px 16px;border-top:1px solid var(--ui-border);min-height:64px', S('width:28px;height:28px;display:flex;align-items:center;justify-content:center;background:var(--ui-bg-elevated)', I(FT[f[2]][0], 16)), D('flex:1;min-width:0;display:flex;flex-direction:column', S('font-weight:500', f[0]), S('font-size:12px;color:var(--ui-text-muted)', S(mono, f[1]), f[3] ? ' · ' + f[3] : ''))))) :
D('background:var(--ui-bg);border:1px solid var(--ui-border)', 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', S('', ''), S('', 'Label'), S('', 'Key'), S('', 'Type'), S('', 'Rules')), ...AF.map(f => D('display:grid;grid-template-columns:' + cols + ';gap:12px;height:48px;align-items:center;padding:0 12px;border-top:1px solid var(--ui-border)', I(FT[f[2]][0], 16, 'color:var(--ui-text-toned)'), S('font-weight:500', f[0]), S(mono + 'font-size:12px;color:var(--ui-text-muted)', f[1]), S('', FT[f[2]][1]), S('color:var(--ui-text-muted)', f[3] || '–')))), S('color:var(--ui-text-muted);font-size:12px', 'Entries of built-in types are managed from their own screens, like Articles and Authors.'))
} else {
const body = []
if (k === 'loading') body.push(D('background:var(--ui-bg);border:1px solid var(--ui-border)', ...Array.from({ length: m ? 6 : 8 }, (_, i) => D('height:' + (m ? 68 : 48) + 'px;display:flex;align-items:center;gap:16px;padding:0 16px;border-top:' + (i ? '1px solid var(--ui-border)' : 'none'), Skel('18px', 16), Skel(i % 2 ? '28%' : '20%'), Skel('14%', 12), !m && Skel('40px', 12), !m && Skel('90px', 12)))))
else if (k === 'error') body.push(Alert('error', 'circle-x', 'Couldn\'t load content types', 'GET /v1/content-type failed. Check your connection and try again.', 'Try again'))
else if (k === 'empty') body.push(Empty('shapes', 'No content types yet', 'Create a content type to manage your own kind of content, like events or recipes. The built-in types stay as they are.', 'New content type'), typesTable(false))
else body.push(typesTable(true), S('color:var(--ui-text-muted)', CUSTOM.length + ' content types · ' + BUILTIN.length + ' built-in'))
main = Page(pad, Title('Schema', 'Content types and the fields they are made of.', ...impExp, s.later && Later(), newBtn), ...body)
if (m && k !== 'loading' && k !== 'error' && k !== 'empty') ov.push(Fab('New content type'))
}
}
// 2 builder
const bld = () => {
let fl = EV, name = 'Events', key = 'events', sel = 0, st = 'clean', isNew = false, api = k === 'api', kb = -1, tErr = {}, banner = null, removed = null, cause = false, tip = false, toast = null, info = true, nErr = 0
if (v === 'review') { const rk = k; if (rk === 'confirm' || rk === 'fallback') { fl = RC; name = 'Recipes'; key = 'recipes'; info = false } else if (rk === 'blocked') { sel = 0 } else { fl = DIRTY; sel = 4; st = 'dirty'; removed = EV[6] } }
if (v === 'rel') { }
if (v === 'builder') {
if (k === 'locked') { sel = 1; tip = true }
if (['dirty', 'saving', 'saved', 'fail', 'incompat', 'offline'].includes(k)) { fl = DIRTY; sel = 4; st = k === 'incompat' ? 'dirty' : k; removed = EV[6] }
if (k === 'saved') { removed = null; st = 'saved'; fl = DIRTY.map(f => ({ ...f, isNew: false, changed: false, saved: true })); toast = Toast('success', 'circle-check', 'Content type saved', 'Events now has 8 fields.') }
if (k === 'fail') banner = Alert('error', 'circle-x', 'Couldn\'t save the content type', 'Something went wrong on our side. Your changes are still here. Try again in a moment.', 'Try again')
if (k === 'incompat') { banner = Alert('error', 'circle-x', 'Nothing was changed', 'Some entries don\'t fit the new fields, so the whole change was refused. RenewCMS can\'t tell which entries. The changes that can cause this are marked.', 'Review changes'); cause = true }
if (k === 'offline') { }
if (k === 'ferr') { fl = EV.map((f, i) => i === 2 ? { ...f, label: '', err: { label: 'Give the field a label.' } } : i === 4 ? { ...f, min: 6000, err: { min: 'Lowest value can\'t be above the highest value.' } } : i === 5 ? { ...f, opts: ['Talk', 'Workshop', '', 'Talk'], err: { choices: { 2: 'Choices can\'t be blank.', 3: 'Two choices are the same.' } } } : f); sel = 4; st = 'errs'; nErr = 3 }
if (k === 'choices') { fl = EV.map((f, i) => i === 5 ? { ...f, opts: ['Talk', 'Workshop', 'Meetup', '', 'Talk'], err: { choices: { 3: 'Choices can\'t be blank.', 4: 'Two choices are the same.' } } } : f); sel = 5; st = 'errs'; nErr = 1 }
if (k === 'kb') { fl = [EV[0], EV[2], EV[1], ...EV.slice(3)]; sel = 1; kb = 1; st = 'dirty' }
if (k === 'new') { fl = [{ key: 'title', label: 'Title', type: 'text', isNew: true }]; name = ''; key = ''; isNew = true; sel = 0; st = 'clean'; info = false }
if (k === 'terr') { fl = []; name = ''; key = 'e'; isNew = true; sel = -1; st = 'errs'; nErr = 3; info = false; tErr = { name: 'Give the content type a name.', key: 'Use 2 to 40 lowercase letters, digits or hyphens.', fields: 'A content type needs at least one field.' } }
if (k === 'taken') { fl = [{ key: 'title', label: 'Title', type: 'text', req: true, isNew: true }, { key: 'starts_on', label: 'Starts on', type: 'date', isNew: true }]; name = 'Events'; key = 'events'; isNew = true; sel = 0; st = 'errs'; nErr = 1; info = false; tErr = { key: 'The key "events" is already used by another content type. Choose a different key.' } }
}
const f = fl[sel], dim = st === 'saving'
const nameF = F('Name', name, { req: true, err: tErr.name, ph: !name, phText: 'For example, Events', dis: dim })
const keyF = F('Key', key, { mono: true, lock: !isNew, auto: isNew && !!key && !tErr.key, err: tErr.key, ph: !key, phText: 'events', dis: dim, help: tErr.key ? '' : isNew ? 'Used in URLs and the API. Choose it carefully: it can\'t change after you save.' : null })
const save = D('display:flex;align-items:center;gap:' + (m ? 8 : 12) + 'px;flex-shrink:0', !m && stChip(st, nErr), !m && B('Discard', { dis: st === 'clean' || st === 'saving' || st === 'saved' || (st === 'errs' && isNew && k === 'new') }), !m && B(st === 'saving' ? 'Saving…' : 'Save', { k: 'primary', icon: st === 'saving' ? 'loader-circle' : null, px: 16, dis: st === 'clean' || st === 'saved' || st === 'saving' || st === 'errs' || st === 'offline' }))
const top = m ? D('display:flex;flex-direction:column;gap:12px;padding:16px;flex-shrink:0;background:var(--ui-bg);border-bottom:1px solid var(--ui-border)', nameF, keyF) : D('display:flex;align-items:' + (tErr.name || tErr.key ? 'flex-start' : 'flex-end') + ';gap:16px;padding:16px 24px;flex-shrink:0;background:var(--ui-bg);border-bottom:1px solid var(--ui-border);position:relative', D('width:320px', nameF), D('width:' + (tErr.key ? 360 : 240) + 'px', keyF), D('flex:1'), D('display:flex;align-items:center;gap:12px;height:32px;margin-top:' + (tErr.name || tErr.key ? 22 : 0) + 'px', save, IB('ellipsis')), tip && D('position:absolute;left:352px;top:84px;z-index:30', Tip('The key is used in URLs and the API, so it can\'t change after the type is created.')))
const infoBar = info && !isNew && D('flex-shrink:0;display:flex;align-items:center;gap:8px;padding:8px ' + (m ? 16 : 24) + 'px;background:var(--rc-info-soft);color:var(--ui-info);font-size:12px;line-height:18px', I('info', 14, 'flex-shrink:0'), S('color:var(--ui-text-toned)', '37 entries use this content type. Changes are checked against them when you save.'))
const listHdr = D('display:flex;align-items:center;justify-content:space-between;height:28px', S('font-weight:600;color:var(--ui-text-highlighted)', 'Fields'), S(mono + 'font-size:12px;color:var(--ui-text-muted)', fl.length + ' of 50'))
const live = kb >= 0 && D('padding:8px 10px;background:var(--ui-bg-inverted);color:var(--ui-text-inverted);font-size:12px;line-height:18px', S('font-weight:600', 'Moving Ends on. Position 2 of 7.'), ' Press Up or Down to move, Space to drop, Esc to cancel.')
const rows = fl.length ? fl.map((x, i) => FRow(x, i, { sel: m ? -1 : sel, kb, dim, cause })) : [D('display:flex;flex-direction:column;align-items:center;gap:8px;text-align:center;padding:32px 16px;border:1px dashed ' + (tErr.fields ? 'var(--ui-error)' : 'var(--ui-border-accented)'), I('rows-3', 20, 'color:var(--ui-text-muted)'), S('font-weight:600', 'No fields yet'), S('color:' + (tErr.fields ? 'var(--ui-error)' : 'var(--ui-text-muted)'), tErr.fields || 'Add the first field.'))]
const rem = removed && D('display:flex;align-items:center;gap:8px;min-height:44px;padding:0 12px;border:1px dashed var(--ui-border-accented);color:var(--ui-text-toned)', I('minus', 14), S('flex:1', removed.label + ' will be removed'), S('text-decoration:underline;text-underline-offset:3px;font-weight:500;color:var(--ui-text-highlighted)', 'Undo'))
const addB = B('Add field', { icon: 'plus', full: false, dis: dim })
const apiRow = m && D('display:flex;align-items:center;gap:10px;min-height:44px;padding:0 12px;border:1px solid var(--ui-border);background:var(--ui-bg);color:var(--ui-text-highlighted)', I('braces', 16), S('flex:1;font-weight:500', 'API preview'), I('chevron-right', 14, 'color:var(--ui-text-muted)'))
const list = D('display:flex;flex-direction:column;gap:8px;' + (m ? 'padding:16px;flex:1;min-height:0;overflow:hidden' : 'width:380px;flex-shrink:0;border-right:1px solid var(--ui-border);padding:16px;overflow:hidden;background:var(--ui-bg-muted)'), listHdr, live, ...rows, rem, addB, apiRow)
const inspPane = !m && D('flex:1;min-width:0;overflow:hidden;padding:16px 24px;background:var(--ui-bg);display:flex;flex-direction:column;gap:14px', f ? D('display:flex;align-items:center;gap:8px', S('font:600 15px/24px \'IBM Plex Sans\',sans-serif;color:var(--ui-text-highlighted)', 'Field: ' + (f.label || 'Untitled field')), f.isNew && Bd('New', 'neu')) : S('font:600 15px/24px \'IBM Plex Sans\',sans-serif;color:var(--ui-text-highlighted)', 'Field settings'), f ? D('opacity:' + (dim ? 0.6 : 1), Insp(f)) : S('color:var(--ui-text-muted)', 'Add a field, then choose its type and rules here.'))
const bar = m && D('flex-shrink:0;display:flex;align-items:center;gap:8px;padding:12px 16px;border-top:1px solid var(--ui-border);background:var(--ui-bg)', stChip(st, nErr), D('flex:1'), B('Discard', { dis: st === 'clean' || st === 'saved' || st === 'saving' || k === 'new' }), B(st === 'saving' ? 'Saving…' : 'Save', { k: 'primary', icon: st === 'saving' ? 'loader-circle' : null, px: 16, dis: ['clean', 'saved', 'saving', 'errs', 'offline'].includes(st) }))
shell.nav = 'schema'; shell.crumbs = ['Schema', isNew ? 'New content type' : name]; shell.mTitle = isNew ? 'New content type' : name; shell.mLead = 'arrow-left'; shell.mAction = 'ellipsis'
shell.offline = false
main = D('flex:1;min-width:0;min-height:0;display:flex;flex-direction:column;position:relative', st === 'offline' && Offline(), top, infoBar, banner && D('padding:12px ' + (m ? 16 : 24) + 'px 0', banner), D('flex:1;min-height:0;display:flex;' + (m ? 'flex-direction:column' : ''), list, inspPane), m ? bar : ApiPanel(fl, key || 'events', api))
if (m && f && (s.sheet || (v === 'builder' && ['edit-sheet', 'choices'].includes(k)))) ov.push(Sheet({ title: 'Field: ' + (f.label || 'Untitled field') }, Insp(f), [B('Done', { k: 'primary', full: true })]))
if (m && api) ov.push(Sheet({ title: 'API preview' }, [S('color:var(--ui-text-muted);font-size:12px', 'GET /v1/content-type/' + key + '/entry'), S('display:block;flex:1;overflow:hidden;padding:10px 12px;background:var(--ui-bg-elevated);border:1px solid var(--ui-border);white-space:pre;' + mono + 'font-size:12px;line-height:19px;color:var(--ui-text-highlighted)', apiJson(fl, key))], [B('Copy JSON', { k: 'primary', full: true, icon: 'copy' })]))
if (toast) ov.push(toast)
}
if (v === 'builder') { bld() }
// 3 review
const chg = (icon, tone, title, text, flag, extra) => D('display:flex;gap:10px;padding:10px 12px;border:1px solid var(--ui-border);background:' + (flag ? 'var(--rc-warning-soft)' : 'var(--ui-bg)'), S('margin-top:2px;display:flex;color:' + (flag ? 'var(--ui-warning)' : 'var(--ui-text-toned)'), I(icon)), D('flex:1;min-width:0;display:flex;flex-direction:column;gap:2px', D('display:flex;align-items:center;gap:8px;flex-wrap:wrap', S('font-weight:600;color:var(--ui-text-highlighted)', title), flag && Bd(flag, 'warn', 'triangle-alert'), extra), S('color:var(--ui-text-toned);text-wrap:pretty', text)))
if (v === 'review') {
bld()
const sum = D('display:flex;flex-direction:column;gap:2px', S('font-weight:600;font-size:15px;color:var(--ui-text-highlighted)', 'Add 2 fields, change 1, remove 1'), S('color:var(--ui-text-muted)', 'Events has 37 entries. Each one is checked against the new fields when you apply.'))
const lat = t => k === 'later' ? Later(t) : null
const list = [chg('plus', 'n', 'Add Speaker', 'Text, optional.', null, lat('Affects 0 entries')), chg('plus', 'n', 'Add Room', 'Choice, required, default "Main hall". Existing entries get the default, so they still fit.', null, lat('Affects 37 entries')), chg('pencil', 'n', 'Change Capacity', 'Highest value goes from 5000 to 2000.', 'Entries may not fit', lat('Affects 3 entries')), chg('minus', 'n', 'Remove Description', 'Entries stop returning its values.', 'Removes data', lat('Affects 31 entries'))]
if (k === 'review' || k === 'later') ov.push(Shell({ title: 'Review changes to Events', desc: 'Apply them to save the content type.', w: k === 'later' ? 640 : 560, top: 60, cancel: 'Back to editing', confirm: 'Apply changes', later: false }, [sum, D('display:flex;flex-direction:column;gap:8px', ...list), k === 'later' ? D('display:flex;align-items:center;gap:8px', B('View full diff', { icon: 'git-compare', h: m ? 44 : 28, fs: 12, px: 10 }), Later('Per-change counts and diff come later')) : S('color:var(--ui-text-muted);font-size:12px;line-height:18px', 'Flagged changes can be refused if existing entries don\'t fit. If that happens, nothing is changed.')]))
if (k === 'applying') ov.push(Shell({ title: 'Review changes to Events', desc: 'Apply them to save the content type.', w: 560, top: 60, cancel: 'Back to editing', confirm: 'Applying…', loading: true, cdis: true }, [sum, D('display:flex;flex-direction:column;gap:8px', ...list)]))
if (k === 'refused') ov.push(Shell({ title: 'Nothing was changed', desc: 'RenewCMS refused the changes because some entries don\'t fit the new fields. It doesn\'t say which entries.', w: 560, top: 60, close: true, cancel: 'Discard changes', confirm: 'Back to editing' }, [Alert('error', 'circle-x', 'Your content type is as it was', 'No field was added, changed or removed.'), S('font-weight:600;color:var(--ui-text-highlighted)', 'The change that can cause this in your edit'), chg('pencil', 'n', 'Change Capacity', 'Highest value goes from 5000 to 2000. An entry may have a higher value.', 'Possible cause'), S('color:var(--ui-text-muted);font-size:12px;line-height:18px;text-wrap:pretty', 'This kind of change is refused when an entry is over the new limit, a new required field has no default, a field becomes unique while entries share a value, or a removed choice is still in use.')]))
if (k === 'blocked') ov.push(Shell({ title: 'You can\'t delete Events yet', desc: 'A content type can only be deleted when it has no entries.', close: true, cancel: 'Close', confirm: 'View entries' }, [Alert('warning', 'triangle-alert', 'Events has 37 entries', 'Delete all of its entries first, then delete the content type.')]))
if (k === 'confirm') ov.push(Shell({ title: 'Delete Recipes?', desc: 'Recipes has no entries. Its fields and its API routes will be deleted. This can\'t be undone.', close: true, cancel: 'Cancel', confirm: 'Delete content type', tone: 'danger' }, [S('color:var(--ui-text-toned)', 'Key: ', S(mono + 'font-size:12px', 'recipes'))]))
if (k === 'fallback') ov.push(Shell({ title: 'Delete Recipes?', desc: 'Recipes has no entries. Its fields and its API routes will be deleted. This can\'t be undone.', close: true, cancel: 'Close', confirm: 'View entries' }, [Alert('error', 'circle-x', 'Recipes now has entries', 'Someone added an entry after this page loaded, so nothing was deleted. Delete the entries first, then try again.')]))
}
// 4 gallery
const GF = { text: EV[0], richtext: { key: 'description', label: 'Description', type: 'richtext', max: 5000 }, number: EV[4], boolean: EV[3], date: { key: 'starts_on', label: 'Starts on', type: 'date', req: true, max: '31 Dec 2027' }, select: { ...EV[5], req: false } }
if (v === 'gallery') {
bare = true; if (m) { bw = '390px'; bhh = '844px' }
const f = { ...GF[k], saved: false }, t = k, L = f.label
const ERR = { text: [['required', 422, 'Fill in ' + L + '.'], ['type', 422, L + ' must be text.'], ['min', 422, L + ' needs at least 3 characters.'], ['max', 422, L + ' can be up to 80 characters.'], ['options', '', 'Not used for text.'], ['unique', 409, 'Another entry already uses this ' + L + '. Enter a different one.']], richtext: [['required', 422, 'Fill in ' + L + '.'], ['type', 422, L + ' must be text.'], ['min', 422, L + ' needs at least 10 characters.'], ['max', 422, L + ' can be up to 5000 characters.'], ['options', '', 'Not used for rich text.'], ['unique', '', 'Not used for rich text.']], number: [['required', 422, 'Fill in ' + L + '.'], ['type', 422, L + ' must be a number.'], ['min', 422, L + ' must be at least 1.'], ['max', 422, L + ' must be at most 5000.'], ['options', '', 'Not used for numbers.'], ['unique', 409, 'Another entry already uses this ' + L + '.']], boolean: [['required', 422, 'Choose yes or no for ' + L + '.'], ['type', 422, L + ' must be yes or no.'], ['min', '', 'Not used for yes or no.'], ['max', '', 'Not used for yes or no.'], ['options', '', 'Not used for yes or no.'], ['unique', '', 'Not used for yes or no.']], date: [['required', 422, 'Pick a date for ' + L + '.'], ['type', 422, L + ' must be a date, like 2026-11-21.'], ['min', 422, L + ' can\'t be before 1 Jan 2026.'], ['max', 422, L + ' can\'t be after 31 Dec 2027.'], ['options', '', 'Not used for dates.'], ['unique', 409, 'Another entry already uses this date for ' + L + '.']], select: [['required', 422, 'Choose an option for ' + L + '.'], ['type', 422, L + ' must be one of the choices.'], ['min', '', 'Not used for choices.'], ['max', '', 'Not used for choices.'], ['options', 422, 'Choose one of: Talk, Workshop or Meetup.'], ['unique', 409, 'Another entry already uses this choice for ' + L + '.']] }[t]
const SAMPLE = { text: ['Lime plaster workshop', ''], richtext: [mdSample, ''], number: ['18', ''], boolean: ['true', 'false'], date: ['21 Nov 2026', ''], select: ['Workshop', ''] }[t]
const sec = (title, ...c) => D('display:flex;flex-direction:column;gap:10px;min-width:0', S('font:600 15px/24px \'IBM Plex Sans\',sans-serif;color:var(--ui-text-highlighted)', title), ...c)
const card = (...c) => D('background:var(--ui-bg);border:1px solid var(--ui-border);padding:16px;display:flex;flex-direction:column;gap:14px', ...c)
const specCtl = { text: Ctl(f, { v: 'Lime plaster workshop, two days of work with the whole team on site', count: '74 / 80', focus: true }), richtext: Ctl({ ...f, max: 5000 }, { v: mdSample, tab: 'write', count: '86 / 5000', help: 'Markdown. Switch to Preview to check the result.' }), number: Ctl(f, { v: '18', focus: true }), boolean: Ctl(f, { v: 'true' }), date: Ctl(f, { v: '21 Nov 2026', focus: true, extra: D('position:absolute;left:0;top:68px;z-index:3', Cal()) }), select: Ctl(f, { v: 'Workshop', focus: true, extra: D('position:absolute;left:0;top:66px;right:0;z-index:3;border:1px solid var(--ui-border);background:var(--ui-bg);box-shadow:var(--rc-shadow-pop);padding:4px', ...['Talk', 'Workshop', 'Meetup'].map(o_ => D('height:' + (m ? 44 : 32) + 'px;padding:0 8px;display:flex;align-items:center;justify-content:space-between;background:' + (o_ === 'Workshop' ? 'var(--ui-bg-elevated)' : 'transparent'), o_, o_ === 'Workshop' && I('check', 14)))) }) }[t]
const spacer = { date: 'height:236px', select: 'height:120px', richtext: '', text: '', number: '', boolean: '' }[t]
const stateLbl = { text: 'Typing, close to the limit', richtext: 'Write tab, with counter', number: 'Focused', boolean: 'On', date: 'Date picker open', select: 'Choices open' }[t]
const ctlCol = sec('Entry form control', card(S('font-size:12px;color:var(--ui-text-muted)', stateLbl), D('', specCtl, spacer && D(spacer)), D('border-top:1px solid var(--ui-border)'), S('font-size:12px;color:var(--ui-text-muted)', t === 'richtext' ? 'Preview tab' : t === 'boolean' ? 'Off, and not set' : 'Empty'), t === 'richtext' ? Ctl(f, { v: mdSample, tab: 'preview', help: '' }) : t === 'boolean' ? Ctl(f, { v: 'false' }) : Ctl(f, { v: '' })))
const cell = (val, lab) => D('display:grid;grid-template-columns:' + (m ? '90px' : '110px') + ' minmax(0,1fr);gap:12px;align-items:center;min-height:40px;padding:0 12px;border-top:1px solid var(--ui-border)', S('font-size:12px;color:var(--ui-text-muted)', lab), Cell(f, val))
const cellVals = { text: ['Lime plaster workshop', ''], richtext: ['Two days of hands-on work with lime putty and old stone.', ''], number: [18, null], boolean: [true, null], date: ['21 Nov 2026', ''], select: ['Workshop', ''] }[t]
const listCol = sec('List cell', D('background:var(--ui-bg);border:1px solid var(--ui-border)', D('display:grid;grid-template-columns:' + (m ? '90px' : '110px') + ' minmax(0,1fr);gap:12px;height:36px;align-items:center;padding:0 12px;background:var(--ui-bg-elevated);color:var(--ui-text-muted);font-weight:500', S('', 'Value'), S('', L)), D('', cell(cellVals[0], 'Filled'), cell(cellVals[1], 'Empty'))), S('font-size:12px;color:var(--ui-text-muted)', { text: 'Truncated on one line, full text on hover.', richtext: 'First line as plain text, truncated.', number: 'Right-aligned, tabular figures.', boolean: 'Yes or No with an icon. Empty only when the field has no value.', date: 'Day, month and year.', select: 'The chosen option as a small tag.' }[t]))
const errCol = sec('Errors by rule', D('background:var(--ui-bg);border:1px solid var(--ui-border)', D('display:grid;grid-template-columns:' + (m ? '64px 38px' : '72px 40px') + ' minmax(0,1fr);gap:10px;height:32px;align-items:center;padding:0 12px;background:var(--ui-bg-elevated);color:var(--ui-text-muted);font-weight:500', S('', 'Rule'), S('', 'HTTP'), S('', 'Message')), ...ERR.map(r => D('display:grid;grid-template-columns:' + (m ? '64px 38px' : '72px 40px') + ' minmax(0,1fr);gap:10px;padding:8px 12px;border-top:1px solid var(--ui-border);align-items:start;line-height:18px', S(mono + 'font-size:12px;color:var(--ui-text-highlighted)', r[0]), S(mono + 'font-size:12px;color:var(--ui-text-muted)', String(r[1] || '–')), S('color:' + (r[1] ? 'var(--ui-error)' : 'var(--ui-text-muted)') + ';text-wrap:pretty', r[2])))))
const FW = { text: [['contains', 'Any text'], 'text'], richtext: [['contains', 'Any text'], 'text'], number: [['between'], 'num'], boolean: [['is'], 'bool'], date: [['between'], 'date'], select: [['is one of'], 'sel'] }[t]
const fw = FW[1] === 'bool' ? Seg([['any', 'Any'], ['yes', 'Yes'], ['no', 'No']], 'any') : FW[1] === 'sel' ? D('display:flex;gap:6px;flex-wrap:wrap', ...['Talk', 'Workshop', 'Meetup'].map((o_, i) => S('height:28px;padding:0 10px;display:flex;align-items:center;gap:6px;border:1px solid ' + (i === 1 ? 'var(--ui-primary)' : 'var(--ui-border-accented)') + ';background:' + (i === 1 ? 'var(--rc-sand)' : 'var(--ui-bg)') + ';color:' + (i === 1 ? 'var(--rc-on-sand)' : 'var(--ui-text-toned)'), i === 1 && I('check', 12), o_))) : FW[1] === 'num' || FW[1] === 'date' ? D('display:flex;gap:8px;align-items:center', F('', '', { ph: true, phText: FW[1] === 'date' ? 'From' : 'Min', ico: FW[1] === 'date' ? 'calendar' : null }), S('color:var(--ui-text-muted)', 'to'), F('', '', { ph: true, phText: FW[1] === 'date' ? 'Until' : 'Max', ico: FW[1] === 'date' ? 'calendar' : null })) : F('', '', { ph: true, phText: 'Contains…', ico: 'search' })
const filtCol = sec('Filter in the entry list', D('border:1px dashed var(--ui-border-accented);padding:14px;display:flex;flex-direction:column;gap:10px', D('display:flex;align-items:center;gap:8px', S('font-weight:500;color:var(--ui-text-highlighted)', L + ': ' + FW[0][0]), Later('Later')), fw, S('font-size:12px;color:var(--ui-text-muted);line-height:18px', 'Filtering on custom fields isn\'t available yet. The list only sorts by ID, created and updated.')))
const head = D('display:flex;align-items:center;gap:14px;flex-shrink:0', S('width:44px;height:44px;display:flex;align-items:center;justify-content:center;background:var(--rc-sand);color:var(--rc-on-sand)', I(FT[t][0], 22)), D('flex:1;display:flex;flex-direction:column', S('font:600 ' + (m ? 20 : 24) + 'px/32px \'IBM Plex Sans\',sans-serif;color:var(--ui-text-highlighted)', FT[t][1]), S('color:var(--ui-text-muted)', FT[t][2])), !m && S(mono + 'font-size:12px;color:var(--ui-text-toned)', 'type: "' + t + '"'))
const inspCol = !m && sec('Inspector options', card(Insp(f, { one: true })))
main = D('position:absolute;inset:0;padding:' + (m ? '16px' : '32px') + ';display:flex;flex-direction:column;gap:' + (m ? 14 : 20) + 'px;overflow:hidden', head, m ? D('display:flex;flex-direction:column;gap:14px', ctlCol, listCol, errCol, filtCol) : D('display:grid;grid-template-columns:400px 440px minmax(0,1fr);gap:24px;align-items:start;flex:1;min-height:0;overflow:hidden', inspCol, D('display:flex;flex-direction:column;gap:20px;min-width:0', ctlCol, listCol), D('display:flex;flex-direction:column;gap:20px;min-width:0', errCol, filtCol)))
}
// 5 entries
const visCols = k === 'cols' ? [EV[0], EV[1], EV[2], EV[3]] : [EV[0], EV[1], EV[2], EV[3]]
if (v === 'entries') {
shell.nav = 'content'; shell.crumbs = ['Content', 'Events']; shell.mTitle = 'Events'; shell.contentOn = k === 'notfound' ? null : 'events'
if (s.many && m) { shell.drawer = true; shell.contentOpen = true }
if (k === 'forbidden') main = Center('lock', 'You don\'t have access to Events', 'Your account can\'t open this content right now. If you think this is a mistake, ask an owner or an admin.', B('Go to Home', { k: 'primary', px: 16 }))
else if (k === 'notfound') { shell.crumbs = ['Content']; shell.mTitle = 'Content'; main = Center('file-x', 'Content type not found', 'It may have been deleted, or the address may be mistyped.', B('Go to Home', { k: 'primary', px: 16 })) }
else {
const paged = k === 'paged', total = paged ? 37 : 7, size = paged ? 5 : 25
const editB = B('Edit content type', { icon: 'settings-2', k: 'ghost' })
const sortB = D('display:flex;align-items:center;gap:8px;height:' + bh + 'px;padding:0 10px;border:1px solid var(--ui-border-accented);background:var(--ui-bg);color:var(--ui-text-highlighted);white-space:nowrap;' + (m ? 'flex:1' : 'width:220px;flex-shrink:0'), S('color:var(--ui-text-muted)', 'Sort by'), S('font-weight:500;flex:1', 'Last updated'), I('chevron-down', 14, 'color:var(--ui-text-muted)'))
const dirB = B(null, { icon: 'arrow-down-wide-narrow', w: bh, px: 0 }), colB = B(m ? null : 'Columns', { icon: 'columns-3', w: m ? 44 : null, px: m ? 0 : 12, ring: false })
const toolbar = D('display:flex;align-items:center;gap:8px;flex-shrink:0;position:relative', sortB, dirB, colB, !m && D('flex:1'), !m && editB)
let body
if (k === 'loading') body = D('background:var(--ui-bg);border:1px solid var(--ui-border);flex:1;min-height:0;overflow:hidden', ...Array.from({ length: m ? 6 : 8 }, (_, i) => D('height:' + (m ? 68 : 48) + 'px;display:flex;align-items:center;gap:20px;padding:0 16px;border-top:' + (i ? '1px solid var(--ui-border)' : 'none'), !m && Skel('32px', 12), Skel(i % 2 ? '30%' : '24%'), !m && Skel('90px', 12), !m && Skel('90px', 12), !m && Skel('50px', 12))))
else if (k === 'error') body = Alert('error', 'circle-x', 'Couldn\'t load entries', 'GET /v1/content-type/events/entry failed. Check your connection and try again.', 'Try again')
else if (k === 'empty') body = Empty('file-plus', 'No entries yet', 'Use New entry to add the first event. Each entry follows the fields of this content type.', 'New entry')
else {
const rows = ROWS.slice(0, size > 7 ? 7 : 5)
const gc = '48px ' + visCols.map((f, i) => i === 0 ? 'minmax(0,1.6fr)' : f.type === 'boolean' || f.type === 'number' ? '80px' : '120px').join(' ') + ' 110px 150px 130px'
const hdrC = (t, o = {}) => S('display:flex;align-items:center;gap:4px;' + (o.r ? 'justify-content:flex-end;' : ''), t, o.sort && I('arrow-down', 12))
const tbl = D('background:var(--ui-bg);border:1px solid var(--ui-border)', D('display:grid;grid-template-columns:' + gc + ';gap:12px;height:36px;align-items:center;padding:0 12px;background:var(--ui-bg-elevated);color:var(--ui-text-muted);font-weight:500', hdrC('ID'), ...visCols.map(f => hdrC(f.label, { r: f.type === 'number' })), hdrC('Created'), hdrC('Updated', { sort: true }), hdrC('Updated by')),
...rows.map((r, i) => D('display:grid;grid-template-columns:' + gc + ';gap:12px;height:48px;align-items:center;padding:0 12px;border-top:1px solid var(--ui-border);background:' + (i === 0 && false ? 'var(--ui-bg-elevated)' : 'transparent'), S(mono + 'font-size:12px;color:var(--ui-text-muted)', String(r.id)), ...visCols.map((f, j) => D('min-width:0;' + (j === 0 ? 'font-weight:500;color:var(--ui-text-highlighted);display:flex' : 'display:grid'), Cell(f, r[f.key]))), S('color:var(--ui-text-muted);white-space:nowrap', r.c), S('color:var(--ui-text-muted);white-space:nowrap', r.u.split(',')[0]), S('overflow:hidden;text-overflow:ellipsis;white-space:nowrap', r.by))))
const cards = D('background:var(--ui-bg);border:1px solid var(--ui-border)', ...ROWS.slice(0, 6).map((r, i) => D('display:flex;align-items:center;gap:8px;padding:12px 4px 12px 16px;border-top:' + (i ? '1px solid var(--ui-border)' : 'none') + ';min-height:68px', D('flex:1;min-width:0;display:flex;flex-direction:column;gap:4px', S('font-weight:500;font-size:15px;line-height:21px;color:var(--ui-text-highlighted);overflow:hidden;text-overflow:ellipsis;white-space:nowrap', r.title), D('display:flex;align-items:center;gap:8px;font-size:12px;color:var(--ui-text-muted)', S('', r.starts_on), r.category && Cell(EV[5], r.category), S('overflow:hidden;text-overflow:ellipsis;white-space:nowrap', '· ' + r.by))), S('width:36px;height:44px;display:flex;align-items:center;justify-content:center;color:var(--ui-text-muted)', I('chevron-right', 18)))))
const pgB = (c, on, dis) => S('width:' + bh + 'px;height:' + bh + 'px;display:flex;align-items:center;justify-content:center;border:1px solid ' + (on ? 'var(--ui-primary)' : 'var(--ui-border-accented)') + ';background:' + (on ? 'var(--rc-sand)' : 'var(--ui-bg)') + ';color:' + (on ? 'var(--rc-on-sand)' : 'var(--ui-text-highlighted)') + ';opacity:' + (dis ? 0.4 : 1) + ';font-weight:' + (on ? 500 : 400), typeof c === 'string' && c.length > 2 ? I(c, 14) : c)
const pager = !paged ? S('color:var(--ui-text-muted)', '7 entries') : m ? D('display:flex;align-items:center;justify-content:space-between;gap:8px', pgB('chevron-left', false, true), S('color:var(--ui-text-muted)', 'Page 1 of 8'), pgB('chevron-right')) : D('display:flex;align-items:center;gap:16px', S('flex:1;color:var(--ui-text-muted)', 'Showing 1–5 of 37'), D('display:flex;align-items:center;gap:8px;height:32px;padding:0 10px;border:1px solid var(--ui-border-accented);background:var(--ui-bg)', '5 per page', I('chevron-down', 14, 'color:var(--ui-text-muted)')), D('display:flex;gap:4px', pgB('chevrons-left', false, true), pgB('chevron-left', false, true), pgB('1', true), pgB('2'), pgB('3'), pgB('…'), pgB('8'), pgB('chevron-right'), pgB('chevrons-right')))
body = D('display:flex;flex-direction:column;gap:12px;min-height:0', m ? cards : tbl, pager)
}
main = Page(pad, Title('Events', 'events · 7 fields', !m && B('New entry', { k: 'primary', icon: 'plus', px: 14, dis: k === 'loading' })), ...(k === 'error' || k === 'empty' || k === 'loading' ? [k !== 'error' ? toolbar : null, body] : [toolbar, body]))
if (m && k !== 'error' && k !== 'loading') ov.push(Fab('New entry'))
if (k === 'cols') {
const items = EV.map((f, i) => [f, i < 4])
const lst = D('display:flex;flex-direction:column', ...items.map(([f, on]) => D('display:flex;align-items:center;gap:10px;min-height:' + (m ? 48 : 36) + 'px;padding:0 8px', Chk(on), I(FT[f.type][0], 14, 'color:var(--ui-text-muted)'), S('flex:1', f.label), S(mono + 'font-size:12px;color:var(--ui-text-muted)', f.key))), D('display:flex;align-items:center;gap:10px;min-height:' + (m ? 48 : 36) + 'px;padding:0 8px;color:var(--ui-text-muted)', Chk(false), I('clock', 14), S('', 'Created and updated dates always show')))
if (m) ov.push(Sheet({ title: 'Columns', z: 45 }, [S('color:var(--ui-text-muted)', 'Choose up to 6 fields to show. 4 selected.'), lst], [B('Reset', { full: true }), B('Done', { k: 'primary', full: true })]))
else ov.push(D('position:absolute;z-index:40;left:' + (224 + 24 + 330) + 'px;top:' + (48 + 24 + 28 + 18 + 16 + 40) + 'px;width:300px;background:var(--ui-bg);border:1px solid var(--ui-border);box-shadow:var(--rc-shadow-pop);padding:8px;display:flex;flex-direction:column;gap:8px', D('display:flex;justify-content:space-between;padding:4px 8px', S('font-weight:600', 'Columns'), S('color:var(--ui-text-muted);font-size:12px', '4 of 6')), lst, D('display:flex;justify-content:flex-end;padding:4px 8px', B('Reset', { h: 28, fs: 12 }))))
}
}
}
// 6 entry
if (v === 'entry') {
shell.nav = 'content'; shell.contentOn = 'events'; shell.crumbs = ['Content', 'Events', k === 'new' || k === 'required' ? 'New entry' : 'Lime plaster workshop']; shell.mTitle = k === 'new' || k === 'required' ? 'New entry' : 'Lime plaster workshop'; shell.mLead = 'arrow-left'; shell.mAction = k === 'new' || k === 'required' ? null : 'trash-2'
if (k === 'notfound') main = Center('file-x', 'Entry not found', 'It may have been deleted by someone else.', B('Back to Events', { k: 'primary', px: 16 }))
else {
const isNew = k === 'new' || k === 'required'
const val = { title: isNew ? '' : 'Lime plaster workshop', starts_on: isNew ? '' : '21 Nov 2026', ends_on: isNew ? '' : '22 Nov 2026', online: 'false', capacity: isNew ? '' : '18', category: isNew ? '' : 'Workshop', description: isNew ? '' : mdSample }
const E = {}
if (k === 'dirty' || k === 'saving' || k === 'fail') val.title = 'Lime plaster workshop, two days'
if (k === 'required') { E.title = 'Fill in Title.'; E.starts_on = 'Pick a date for Starts on.' }
if (k === 'rules') { val.title = 'Lime plaster workshop, two days of hands-on work with the whole team on site and lunch'; E.title = 'Title can be up to 80 characters.'; val.ends_on = '31/11/2026'; E.ends_on = 'Ends on must be a date, like 2026-11-21.'; val.capacity = '6000'; E.capacity = 'Capacity must be at most 5000.'; val.category = 'Seminar'; E.category = 'Choose one of: Talk, Workshop or Meetup.' }
if (k === 'unique') { val.title = 'Heat pumps: what the numbers say'; E.title = 'Another entry already uses this Title. Enter a different one.' }
const dis = k === 'saving' || k === 'changed'
const sk = k === 'dirty' ? 'dirty' : k === 'saving' ? 'saving' : k === 'saved' ? 'saved' : k === 'fail' ? 'fail' : (k === 'required' || k === 'rules' || k === 'unique') ? 'fail' : 'clean'
const chip = k === 'required' || k === 'rules' || k === 'unique' ? S('display:flex;align-items:center;gap:6px;font-size:12px;color:var(--ui-error);white-space:nowrap', I('circle-alert', 14), 'Not saved') : isNew ? S('font-size:12px;color:var(--ui-text-muted);white-space:nowrap', 'New entry') : stChip(sk)
const canSave = k === 'dirty' || k === 'fail' || k === 'new' || k === 'required' || k === 'rules' || k === 'unique'
const acts = D('display:flex;align-items:center;gap:' + (m ? 8 : 12) + 'px', !m && chip, !m && !isNew && B('Delete', { k: 'del', icon: 'trash-2' }), !m && B('Cancel', { dis: dis }), !m && B(k === 'saving' ? 'Saving…' : 'Save', { k: 'primary', icon: k === 'saving' ? 'loader-circle' : null, px: 16, dis: !canSave && k !== 'saving' }))
const fieldsUI = EV.map(f => { const vv = val[f.key], e = E[f.key]; const o = { v: vv, err: e, dis, def: isNew && f.key === 'online', focus: k === 'dirty' && f.key === 'title' }; if (f.key === 'title') { const n = (vv || '').length; o.count = n + ' / 80'; o.countErr = n > 80; if (k === 'unique') o.count = n + ' / 80' } if (f.key === 'description') { o.tab = k === 'preview' ? 'preview' : 'write'; o.help = 'Markdown. Switch to Preview to check the result.' } if (f.key === 'capacity') o.help = 'Between 1 and 5000.'; if (f.key === 'title' && !e) o.help = 'Each entry needs a different title.'; return Ctl(f, o) })
const grid = (a, b) => D('display:grid;grid-template-columns:' + (m ? '1fr' : '1fr 1fr') + ';gap:16px', a, b)
const form = D('background:var(--ui-bg);border:1px solid var(--ui-border);padding:' + (m ? 16 : 24) + 'px;display:flex;flex-direction:column;gap:20px;max-width:760px;opacity:' + (dis ? 0.7 : 1), fieldsUI[0], grid(fieldsUI[1], fieldsUI[2]), grid(fieldsUI[3], fieldsUI[4]), fieldsUI[5], fieldsUI[6], D('border-top:1px solid var(--ui-border);padding-top:16px;display:grid;grid-template-columns:' + (m ? '1fr' : 'auto 1fr') + ';gap:6px 16px;font-size:12px;line-height:18px', S('color:var(--ui-text-muted)', 'Entry'), S('', isNew ? 'Not saved yet' : S(mono, 'events / 42')), S('color:var(--ui-text-muted)', 'Created by'), S('', isNew ? '–' : 'Inès Duarte · 12 Oct 2026, 09:14'), S('color:var(--ui-text-muted)', 'Updated by'), S('', isNew ? '–' : k === 'saved' ? 'Marta Alves · 19 Oct 2026, 11:02' : 'Marta Alves · 15 Oct 2026, 11:02')))
const ban = k === 'fail' ? Alert('error', 'circle-x', 'Couldn\'t save the entry', 'Something went wrong on our side. Your changes are still here. Try again in a moment.', 'Try again') : k === 'changed' ? Alert('warning', 'triangle-alert', 'The fields of Events changed', 'A field was removed and a new required field, Room, was added after you opened this form. Reload the form to continue. What you typed here can\'t be saved against the old fields.', 'Reload form') : k === 'unique' ? Alert('error', 'circle-x', 'Not saved', 'Another entry already uses this title. Change it and save again.') : null
const bar = m && D('flex-shrink:0;display:flex;align-items:center;gap:8px;padding:12px 16px;border-top:1px solid var(--ui-border);background:var(--ui-bg);position:relative;z-index:1', B('Cancel', { full: true, dis }), B(k === 'saving' ? 'Saving…' : 'Save', { k: 'primary', full: true, icon: k === 'saving' ? 'loader-circle' : null, dis: !canSave && k !== 'saving' }))
main = D('flex:1;min-width:0;min-height:0;display:flex;flex-direction:column;position:relative', Page(pad, Title(isNew ? 'New entry' : 'Lime plaster workshop', isNew ? 'Events · Fields marked * are required.' : 'Events · Entry 42', acts), m && D('display:flex;align-items:center;justify-content:space-between', chip), ban, form), bar)
if (k === 'delete') ov.push(Shell({ title: 'Delete this entry?', desc: '"Lime plaster workshop" will be deleted from Events. This can\'t be undone.', close: true, cancel: 'Cancel', confirm: 'Delete entry', tone: 'danger' }, []))
if (k === 'saved') ov.push(Toast('success', 'circle-check', 'Entry saved', '"Lime plaster workshop" is up to date.'))
}
}
// 7 relation (later)
if (v === 'rel') {
shell.nav = 'schema'
if (k === 'builder') {
shell.crumbs = ['Schema', 'Events']; shell.mTitle = 'Events'; shell.mLead = 'arrow-left'
const shape = (on, a, b, diag) => D('display:flex;flex-direction:column;gap:6px;padding:10px;border:1px solid ' + (on ? 'var(--ui-primary)' : 'var(--ui-border-accented)') + ';background:' + (on ? 'var(--rc-sand)' : 'var(--ui-bg)') + ';color:' + (on ? 'var(--rc-on-sand)' : 'var(--ui-text-highlighted)'), diag, S('font-weight:500', a), S('font-size:12px;line-height:16px;color:' + (on ? 'var(--rc-on-sand)' : 'var(--ui-text-muted)'), b))
const sq = (n, c) => D('display:flex;gap:3px', ...Array.from({ length: n }, () => S('width:10px;height:10px;background:' + c)))
const dg = (l, r) => D('display:flex;align-items:center;gap:6px', sq(l, 'currentColor'), S('width:20px;height:1px;background:currentColor'), sq(r, 'currentColor'))
const sel = (t) => S('display:inline-flex;align-items:center;gap:6px;height:28px;padding:0 8px;margin:0 4px;border:1px solid var(--ui-border-accented);background:var(--ui-bg);font-weight:500;color:var(--ui-text-highlighted)', t, I('chevron-down', 12))
const card_ = (t, ...c) => D('flex:1;min-width:0;padding:12px;background:var(--ui-bg);border:1px solid var(--ui-border);display:flex;flex-direction:column;gap:8px', S('font-weight:600;color:var(--ui-text-highlighted)', t), ...c)
const chipR = t => S('height:22px;padding:0 8px;display:inline-flex;align-items:center;gap:4px;background:var(--rc-sand);color:var(--rc-on-sand);font-size:12px;font-weight:500', t)
const insp = D('display:flex;flex-direction:column;gap:14px;min-width:0', D('display:flex;align-items:center;gap:8px', S('font:600 15px/24px \'IBM Plex Sans\',sans-serif;color:var(--ui-text-highlighted)', 'Field: Venue'), Later()), D('display:grid;grid-template-columns:' + (m ? '1fr' : '1fr 1fr') + ';gap:14px', F('Label', 'Venue', { req: true }), F('Key', 'venue', { mono: true, auto: true })),
D('display:flex;flex-direction:column;gap:6px', S('font-weight:500;color:var(--ui-text-highlighted)', 'Type'), D('display:grid;grid-template-columns:repeat(' + (m ? 2 : 4) + ',minmax(0,1fr));gap:8px', ...['text', 'number', 'date', 'select'].map(t => D('display:flex;gap:8px;align-items:center;padding:8px 10px;border:1px solid var(--ui-border-accented);opacity:.6', I(FT[t][0], 16), FT[t][1])), D('display:flex;gap:8px;align-items:center;padding:8px 10px;border:1px solid var(--ui-primary);background:var(--rc-sand);color:var(--rc-on-sand)', I('link', 16), S('font-weight:500', 'Relation'), S('margin-left:auto;font-size:11px', 'Later')))),
F('Related content type', 'Venue', { sel: true, help: 'Choose the content type this field points to.' }),
D('display:flex;flex-direction:column;gap:6px', S('font-weight:500;color:var(--ui-text-highlighted)', 'How are they connected?'), D('display:grid;grid-template-columns:' + (m ? '1fr' : 'repeat(3,minmax(0,1fr))') + ';gap:8px', shape(false, 'One to one', 'Each Event has one Venue, and each Venue has one Event.', dg(1, 1)), shape(true, 'One to many', 'Each Event has one Venue. A Venue has many Events.', dg(3, 1)), shape(false, 'Many to many', 'Each Event has many Venues, and each Venue has many Events.', dg(2, 2)))),
D('display:flex;flex-direction:column;gap:8px;padding:12px;background:var(--ui-bg-elevated)', S('', 'Each Event has', sel('one'), 'Venue'), S('', 'Each Venue has', sel('many'), 'Events', S('color:var(--ui-text-muted)', ' · shown on Venue as the field "Events"'))),
D('display:flex;gap:12px;flex-direction:' + (m ? 'column' : 'row'), card_('Event', S('color:var(--ui-text-muted);font-size:12px', 'Venue'), D('display:flex;gap:6px', chipR('Rue Verte hall'))), card_('Venue', S('color:var(--ui-text-muted);font-size:12px', 'Events'), D('display:flex;gap:6px;flex-wrap:wrap', chipR('Open day'), chipR('Lime plaster workshop'), S('font-size:12px;color:var(--ui-text-muted);align-self:center', '+1')))))
main = Page(pad, Title('Edit content type', 'Events · Relation field, shown as it will work later.'), D('background:var(--ui-bg);border:1px solid var(--ui-border);padding:16px;overflow:hidden', insp))
} else if (k === 'form') {
shell.nav = 'content'; shell.crumbs = ['Content', 'Events', 'Lime plaster workshop']; shell.mTitle = 'Lime plaster workshop'; shell.contentOn = 'events'
const res = D('position:absolute;left:0;right:0;top:64px;z-index:5;border:1px solid var(--ui-border);background:var(--ui-bg);box-shadow:var(--rc-shadow-pop);padding:4px', ...[['Rue Verte hall', 'Lyon · 120 seats'], ['Rue Verte yard', 'Lyon · outdoor'], ['Rue du Port studio', 'Nantes · 24 seats']].map(([a, b], i) => D('min-height:' + (m ? 48 : 40) + 'px;padding:4px 8px;display:flex;flex-direction:column;justify-content:center;background:' + (i === 0 ? 'var(--ui-bg-elevated)' : 'transparent'), S('font-weight:500', a), S('font-size:12px;color:var(--ui-text-muted)', b))))
const chipX = t => S('height:' + (m ? 32 : 24) + 'px;padding:0 4px 0 8px;display:inline-flex;align-items:center;gap:6px;background:var(--rc-sand);color:var(--rc-on-sand);font-weight:500', t, I('x', 14))
main = Page(pad, Title('Lime plaster workshop', 'Events · Entry 42', Later('Relation field: later')), D('background:var(--ui-bg);border:1px solid var(--ui-border);padding:' + (m ? 16 : 24) + 'px;display:flex;flex-direction:column;gap:' + (m ? 16 : 20) + 'px;max-width:760px;overflow:visible;flex:1;min-height:0', Ctl(EV[0], { v: 'Lime plaster workshop', count: '21 / 80' }),
D('display:flex;flex-direction:column;gap:6px;position:relative', S('font-weight:500;color:var(--ui-text-highlighted)', 'Venue'), F('', 'rue', { focus: true, ico: 'search' }), res, S('height:176px')),
D('display:flex;flex-direction:column;gap:6px', S('font-weight:500;color:var(--ui-text-highlighted)', 'Speakers'), D('display:flex;gap:6px;flex-wrap:wrap;align-items:center;min-height:' + ih + 'px;padding:4px 8px;border:1px solid var(--ui-border-accented)', chipX('Inès Duarte'), chipX('Jonas Pereira'), S('color:var(--ui-text-muted);margin-left:4px', 'Search to add')), S('color:var(--ui-text-muted);font-size:12px', 'An event can have many speakers.'))))
} else {
shell.nav = 'content'; shell.crumbs = ['Content', 'Events']; shell.mTitle = 'Events'; shell.contentOn = 'events'
const chipR = t => S('height:20px;padding:0 6px;display:inline-flex;align-items:center;background:var(--rc-sand);color:var(--rc-on-sand);font-size:12px;font-weight:500;white-space:nowrap', t)
const gc = '48px minmax(0,1.4fr) 110px 200px 200px'
const rr = [[42, 'Lime plaster workshop', '21 Nov 2026', [chipR('Rue Verte hall')], [chipR('Inès Duarte'), chipR('Jonas Pereira'), S('color:var(--ui-text-muted);font-size:12px', '+2')]], [41, 'Heat pumps: what the numbers say', '3 Nov 2026', [S('color:var(--ui-text-muted)', '–')], [chipR('Jonas Pereira')]], [40, 'Open day at the Rue Verte site', '12 Nov 2026', [chipR('Rue Verte yard')], [S('color:var(--ui-text-muted)', '–')]]]
main = Page(pad, Title('Events', 'events · 9 fields', Later('Relation columns: later')), m ? D('background:var(--ui-bg);border:1px solid var(--ui-border)', ...rr.map(r => D('padding:12px 16px;border-top:1px solid var(--ui-border);display:flex;flex-direction:column;gap:6px', S('font-weight:500;font-size:15px', r[1]), D('display:flex;gap:6px;align-items:center', S('font-size:12px;color:var(--ui-text-muted)', 'Venue'), ...r[3]), D('display:flex;gap:6px;align-items:center;flex-wrap:wrap', S('font-size:12px;color:var(--ui-text-muted)', 'Speakers'), ...r[4])))) : D('background:var(--ui-bg);border:1px solid var(--ui-border)', D('display:grid;grid-template-columns:' + gc + ';gap:12px;height:36px;align-items:center;padding:0 12px;background:var(--ui-bg-elevated);color:var(--ui-text-muted);font-weight:500', S('', 'ID'), S('', 'Title'), S('', 'Starts on'), S('', 'Venue'), S('', 'Speakers')), ...rr.map(r => D('display:grid;grid-template-columns:' + gc + ';gap:12px;height:48px;align-items:center;padding:0 12px;border-top:1px solid var(--ui-border)', S(mono + 'font-size:12px;color:var(--ui-text-muted)', String(r[0])), S('font-weight:500;color:var(--ui-text-highlighted);overflow:hidden;text-overflow:ellipsis;white-space:nowrap', r[1]), S('', r[2]), D('display:flex;gap:4px;align-items:center', ...r[3]), D('display:flex;gap:4px;align-items:center', ...r[4])))), S('color:var(--ui-text-muted);font-size:12px;line-height:18px', 'One chip for a single relation. Up to two chips and a "+N" for many. Empty shows a dash.'))
}
}
// 8 permissions (later)
if (v === 'perms') {
shell.nav = 'settings'; shell.crumbs = ['Settings', 'Permissions']; shell.mTitle = 'Permissions'; shell.mLead = 'arrow-left'; shell.sideOpen = true
const ch = k === 'changed'
const rowsC = [['Events', 'events', [1, 1, 1, 1]], ['Recipes', 'recipes', ch ? [1, 1, 1, 0] : [1, 1, 1, 1]], ['Press mentions', 'press-mentions', ch ? [1, 0, 0, 0] : [1, 1, 1, 1]]]
const rowsB = [['Articles', [1, 1, 1, 1]], ['Authors', [1, 1, 1, 0]], ['Sites', [1, 0, 0, 0]], ['Media', [1, 1, 1, 1]], ['Users', [0, 0, 0, 0]]]
const A4 = ['Read', 'Create', 'Update', 'Delete']
const cols = 'minmax(0,1fr) 80px 80px 80px 80px'
const cellP = (on, lock, changed) => D('display:flex;align-items:center;justify-content:center;gap:4px;opacity:' + (lock ? 0.55 : 1), Chk(!!on), changed && S('width:6px;height:6px;background:var(--ui-info)'))
const desk = D('background:var(--ui-bg);border:1px solid var(--ui-border)', D('display:grid;grid-template-columns:' + cols + ';gap:8px;height:36px;align-items:center;padding:0 12px;background:var(--ui-bg-elevated);color:var(--ui-text-muted);font-weight:500', S('', 'Content type'), ...A4.map(a => S('text-align:center', a))),
...rowsC.map(r => D('display:grid;grid-template-columns:' + cols + ';gap:8px;height:44px;align-items:center;padding:0 12px;border-top:1px solid var(--ui-border)', D('display:flex;align-items:center;gap:8px', S('font-weight:500', r[0]), S(mono + 'font-size:12px;color:var(--ui-text-muted)', r[1])), ...r[2].map((x, i) => cellP(x, false, ch && ((r[0] === 'Recipes' && i === 3) || (r[0] === 'Press mentions' && i > 0)))))),
D('display:flex;align-items:center;gap:8px;padding:8px 12px;border-top:1px solid var(--ui-border);background:var(--ui-bg-muted);color:var(--ui-text-toned);font-size:12px', I('lock', 14), 'Built-in types. RenewCMS sets these rules.'),
...rowsB.map(r => D('display:grid;grid-template-columns:' + cols + ';gap:8px;height:44px;align-items:center;padding:0 12px;border-top:1px solid var(--ui-border)', D('display:flex;align-items:center;gap:8px', I('lock', 14, 'color:var(--ui-text-muted)'), S('font-weight:500', r[0]), Bd('Built-in', 'built')), ...r[1].map(x => cellP(x, true)))))
const mob = D('display:flex;flex-direction:column;gap:12px', ...rowsC.map(r => D('background:var(--ui-bg);border:1px solid var(--ui-border);padding:12px 16px;display:flex;flex-direction:column;gap:2px', S('font-weight:600;font-size:15px;color:var(--ui-text-highlighted)', r[0]), ...r[2].map((x, i) => D('display:flex;align-items:center;gap:12px;min-height:44px;border-top:' + (i ? '1px solid var(--ui-border-muted)' : 'none'), Chk(!!x), S('flex:1', A4[i]), ch && ((r[0] === 'Recipes' && i === 3) || (r[0] === 'Press mentions' && i > 0)) && Bd('Changed', 'chg'))))), D('background:var(--ui-bg);border:1px solid var(--ui-border);padding:12px 16px;display:flex;align-items:center;gap:10px;min-height:48px', I('lock', 16, 'color:var(--ui-text-muted)'), S('flex:1', '5 built-in types'), S('color:var(--ui-text-muted);font-size:12px', 'Set by RenewCMS'), I('chevron-right', 14, 'color:var(--ui-text-muted)')))
const foot = D('flex-shrink:0;display:flex;align-items:center;gap:8px;padding:12px ' + (m ? 16 : 24) + 'px;border-top:1px solid var(--ui-border);background:var(--ui-bg)', S('flex:1;font-size:12px;color:' + (ch ? 'var(--ui-warning)' : 'var(--ui-text-muted)'), ch ? '4 changes not saved' : 'No changes'), B('Discard', { dis: !ch }), B('Save permissions', { k: 'primary', dis: !ch }))
main = D('flex:1;min-width:0;min-height:0;display:flex;flex-direction:column', Page(pad, Title('Permissions', 'What each role can do with each content type.', Later()), Alert('info', 'info', 'Today\'s rules are the starting point', 'Owners and admins edit the schema. Any verified user can read, add, edit and delete entries.'), Seg([['owner', 'Owner'], ['admin', 'Admin'], ['user', 'User']], 'user', m ? '100%' : '320px'), m ? mob : desk, D('display:flex;align-items:center;gap:8px;color:var(--ui-text-toned);font-size:12px;line-height:18px;background:var(--ui-bg-elevated);padding:10px 12px', I('lock', 14), S('', 'Schema (create, edit and delete content types): owners and admins only. Set by RenewCMS.'))), foot)
}
// 9 export / import (later)
if (v === 'xport') {
Object.assign(shell, { nav: 'schema', crumbs: ['Schema'], mTitle: 'Schema' })
main = Page(pad, Title('Schema', 'Content types and the fields they are made of.', B('Import', { icon: 'upload' }), B('Export', { icon: 'download' }), Later(), B('New content type', { k: 'primary', icon: 'plus', px: 14 })), typesTable(true))
const rd = (on, t, sub) => D('display:flex;gap:10px;align-items:flex-start;padding:10px 12px;border:1px solid ' + (on ? 'var(--ui-primary)' : 'var(--ui-border-accented)') + ';background:' + (on ? 'var(--rc-sand)' : 'var(--ui-bg)') + ';color:' + (on ? 'var(--rc-on-sand)' : 'var(--ui-text-highlighted)'), S('width:16px;height:16px;margin-top:2px;flex-shrink:0;border:1px solid currentColor;display:flex;align-items:center;justify-content:center', on && S('width:8px;height:8px;background:currentColor')), D('display:flex;flex-direction:column', S('font-weight:500', t), S('font-size:12px;color:' + (on ? 'var(--rc-on-sand)' : 'var(--ui-text-muted)'), sub)))
if (k === 'export') ov.push(Shell({ title: 'Export schema', desc: 'Download the fields of your content types as a file. Entries aren\'t included.', close: true, later: true, cancel: 'Cancel', confirm: 'Download file' }, [D('display:flex;flex-direction:column;gap:8px', rd(true, 'All content types', '3 content types'), rd(false, 'One content type', 'Choose which one')), F('File name', 'renewcms-schema.json', { mono: true, dis: true, help: 'Import this file on another RenewCMS site to create the same content types.' })]))
else {
const ref = k === 'refused'
const rowI = (ic, t, text, flag, tag) => D('display:flex;gap:10px;padding:10px 12px;border:1px solid var(--ui-border);background:' + (flag ? 'var(--rc-warning-soft)' : 'var(--ui-bg)'), S('margin-top:2px;display:flex;color:' + (flag ? 'var(--ui-warning)' : 'var(--ui-text-toned)'), I(ic)), D('flex:1;min-width:0;display:flex;flex-direction:column;gap:2px', D('display:flex;align-items:center;gap:8px;flex-wrap:wrap', S('font-weight:600;color:var(--ui-text-highlighted)', t), tag && Bd(tag, 'chg'), flag && Bd(flag, 'warn', 'triangle-alert')), S('color:var(--ui-text-toned);text-wrap:pretty', text)))
ov.push(Shell({ title: 'Import schema', desc: 'renewcms-schema.json · 3 content types', w: 600, top: 70, close: true, later: true, cancel: 'Cancel', confirm: ref ? 'Try again' : 'Import schema', cdis: false }, [ref ? Alert('error', 'circle-x', 'Nothing was imported', 'Some entries on this site don\'t fit the imported fields. RenewCMS can\'t tell which entries. The flagged change can cause this.') : S('font-weight:600;font-size:15px;color:var(--ui-text-highlighted)', 'Create 1, change 1, no change 1'), D('display:flex;flex-direction:column;gap:8px', rowI('plus', 'Recipes', 'New content type with 4 fields.', null, 'Create'), rowI('pencil', 'Events', 'Add 2 fields, remove Description. Events has 37 entries on this site.', 'Removes data', 'Change'), rowI('equal', 'Press mentions', 'Same as on this site.', null, null)), S('color:var(--ui-text-muted);font-size:12px;line-height:18px', 'Existing entries are checked against the changes when you import. If any entry doesn\'t fit, nothing is imported.')]))
}
}
if (m && v !== 'gallery' && s.drawer) shell.drawer = true
const framed = !bare
return { framed, bare, shell, mob: m, main, ov: D('display:contents', ...ov), bw, bh: bhh }
}
}
</script>
</body>
</html>
+178
View File
@@ -0,0 +1,178 @@
const N = 'available now', L = 'later'
const st = (name, scope, trigger, s, copy, o = {}) => ({ name, scope, trigger, s, copy, ...o })
export const groups = [
{ label: '1 Schema list', title: '1 Schema: list of types', route: '/schema, /schema/:key (built-in)', api: 'GET /v1/content-type', auth: 'Owner or admin', note: 'Sidebar entry "Schema" for owners and admins only. Built-in types are listed with a lock and a Built-in badge, always after the custom ones. They open a read-only view. Sample data: the field counts of built-ins are illustrative.', states: [
st('Populated', N, 'An owner or admin opens /schema.', { v: 'types', k: 'ok' }, 'Schema · Content types and the fields they are made of. · New content type · Name · Key · Fields · Last updated · Built-in types are managed by RenewCMS. You can read their fields, but not change them. · Built-in · 3 content types · 5 built-in'),
st('Loading', N, 'First load or retry. Skeleton rows appear after 150 ms. New content type is disabled.', { v: 'types', k: 'loading' }, '(skeleton) · New content type (disabled)'),
st('Empty: no custom type yet', N, 'GET /v1/content-type returns []. Built-ins are still listed below.', { v: 'types', k: 'empty' }, 'No content types yet · Create a content type to manage your own kind of content, like events or recipes. The built-in types stay as they are. · New content type'),
st('Error', N, '500 or network failure on the list request.', { v: 'types', k: 'error' }, 'Couldn\'t load content types · GET /v1/content-type failed. Check your connection and try again. · Try again'),
st('Forbidden (403)', N, 'A user who is not owner or admin types /schema. There is no sidebar entry, so the page explains instead of redirecting.', { v: 'types', k: 'forbidden' }, 'You don\'t have access to Schema · Only owners and admins can change content types. You can still add and edit entries from the Content menu. · Go to Home'),
st('Built-in type: read-only view', N, 'Click Articles in the list. No edit, no delete, no add field.', { v: 'types', k: 'builtin' }, 'Articles · Built-in · Managed by RenewCMS · Articles is a built-in type. You can read its fields here, but you can\'t edit it, delete it or add fields. · Label · Key · Type · Rules · Entries of built-in types are managed from their own screens, like Articles and Authors.')
] },
{ label: '2 Schema builder', title: '2 Schema builder', route: '/schema/new, /schema/:key', api: 'POST /v1/content-type, GET/PUT /v1/content-type/{key}', auth: 'Owner or admin', note: 'One screen, three regions: type name and key on top, ordered field list on the left, field inspector on the right, collapsible API preview at the bottom. Mobile: the list is the page, the inspector is a 92% sheet, the API preview is a sheet. Field keys and types of saved fields are locked; fields added since the last save can still choose both.', states: [
st('New type', N, '/schema/new. One starter field is added because a type needs at least one.', { v: 'builder', k: 'new' }, 'New content type · Name · For example, Events · Key · events · Used in URLs and the API. Choose it carefully: it can\'t change after you save. · Fields · 1 of 50 · Add field · Field: Title · Label · Key · The name used in the API. Lowercase letters, digits and underscores. · Type · Required · An entry can\'t be saved with this field empty. · Unique values · Default value · Used when an entry is created and this field is left out. · Shortest · Longest · Counted in characters. Entries show a counter. · Save · Discard'),
st('Editing an existing type', N, '/schema/events with 37 entries. Key is locked, saved field keys and types are locked.', { v: 'builder', k: 'edit' }, '37 entries use this content type. Changes are checked against them when you save. · Key (lock) · Used in the API, so it can\'t change. · Can\'t change after saving · Saved'),
st('Locked key: tooltip', N, 'Hover or focus the locked key.', { v: 'builder', k: 'locked' }, 'The key is used in URLs and the API, so it can\'t change after the type is created.'),
st('Unsaved changes', N, 'Two fields added, Capacity changed, Description removed. Rows carry New and Changed badges; removal shows an undo row.', { v: 'builder', k: 'dirty' }, 'Unsaved changes · New · Changed · Description will be removed · Undo · Save · Discard'),
st('Field errors', N, 'Checked as the user types, and again on Save. The row is outlined and shows an alert icon. Save is disabled until all are fixed.', { v: 'builder', k: 'ferr' }, '3 problems to fix · Give the field a label. · Lowest value can\'t be above the highest value. · Choices can\'t be blank. · Two choices are the same.'),
st('Type-level errors', N, 'New type with no name, a one-letter key and no fields.', { v: 'builder', k: 'terr' }, 'Give the content type a name. · Use 2 to 40 lowercase letters, digits or hyphens. · No fields yet · A content type needs at least one field. · 3 problems to fix'),
st('Choice list editor', N, 'A Choice field is selected. Add, remove and reorder; blanks and duplicates are flagged per row.', { v: 'builder', k: 'choices', sheet: true }, 'Choices · 5 of 50 · Add a choice · Add · Add 1 to 50 choices. Each one needs a different name. Removing a choice that entries use will be refused when you save. · Choices can\'t be blank. · Two choices are the same.'),
st('Keyboard reorder', N, 'Focus the grip, press Space. Up and Down move, Space drops, Esc cancels. Move up, Move down and Remove buttons are on the selected row.', { v: 'builder', k: 'kb' }, 'Moving Ends on. Position 2 of 7. Press Up or Down to move, Space to drop, Esc to cancel. (live region, polite)'),
st('API preview open', N, 'The panel at the bottom. Updates as fields change. Copy JSON copies the sample entry.', { v: 'builder', k: 'api' }, 'API preview · Where entries of this type live · A sample entry. Values come from each field\'s type and default. · Updates as you edit. Fields you add or remove here appear after you save. · Copy JSON · Copied'),
st('Saving', N, 'PUT in flight. Inputs dim, Save shows the loader, nothing can be dragged.', { v: 'builder', k: 'saving' }, 'Saving…'),
st('Saved', N, '200. A toast confirms, the badges clear.', { v: 'builder', k: 'saved' }, 'Saved at 11:02 · Content type saved · Events now has 8 fields.'),
st('Save failed', N, '500 or network failure. Nothing was sent as saved; the edits stay.', { v: 'builder', k: 'fail' }, 'Save failed · Couldn\'t save the content type · Something went wrong on our side. Your changes are still here. Try again in a moment. · Try again'),
st('Key already taken', N, '409 content_type_key_taken on POST.', { v: 'builder', k: 'taken' }, 'The key "events" is already used by another content type. Choose a different key.'),
st('Schema incompatible', N, '422 schema_incompatible on PUT. The review dialog (group 3) closes into this state. Changes of the kinds that can cause it are marked.', { v: 'builder', k: 'incompat' }, 'Nothing was changed · Some entries don\'t fit the new fields, so the whole change was refused. RenewCMS can\'t tell which entries. The changes that can cause this are marked. · Review changes · Possible cause'),
st('Offline', N, 'navigator.onLine is false. Edits are kept; Save is disabled.', { v: 'builder', k: 'offline' }, 'You\'re offline. Changes will be saved when you reconnect. · Waiting for connection')
] },
{ label: '3 Review and delete', title: '3 Schema change review and delete type', route: '/schema/:key (dialogs)', api: 'PUT /v1/content-type/{key}, DELETE /v1/content-type/{key}', auth: 'Owner or admin', note: 'The review opens on Save when the type already has entries (37 here). It is informational: the server decides compatibility. Destructive changes (removing a field or a choice, tightening a limit, making a field unique or required) carry a warning flag. Per-change entry counts and a full diff are later.', states: [
st('Review before saving', N, 'Save on a type that has entries.', { v: 'review', k: 'review' }, 'Review changes to Events · Apply them to save the content type. · Add 2 fields, change 1, remove 1 · Events has 37 entries. Each one is checked against the new fields when you apply. · Add Speaker · Text, optional. · Add Room · Choice, required, default "Main hall". Existing entries get the default, so they still fit. · Change Capacity · Highest value goes from 5000 to 2000. · Entries may not fit · Remove Description · Entries stop returning its values. · Removes data · Flagged changes can be refused if existing entries don\'t fit. If that happens, nothing is changed. · Back to editing · Apply changes'),
st('Applying', N, 'PUT in flight. Dialog cannot be dismissed.', { v: 'review', k: 'applying' }, 'Applying…'),
st('Refused (schema_incompatible)', N, '422 schema_incompatible. States that nothing changed and names the kind of change that likely caused it, never an entry.', { v: 'review', k: 'refused' }, 'Nothing was changed · RenewCMS refused the changes because some entries don\'t fit the new fields. It doesn\'t say which entries. · Your content type is as it was · No field was added, changed or removed. · The change that can cause this in your edit · Possible cause · This kind of change is refused when an entry is over the new limit, a new required field has no default, a field becomes unique while entries share a value, or a removed choice is still in use. · Discard changes · Back to editing'),
st('Review with counts and diff', L, 'Per-change entry counts and a full diff need an API that does not exist yet.', { v: 'review', k: 'later' }, 'Affects 0 entries · Affects 37 entries · Affects 3 entries · Affects 31 entries · View full diff · Per-change counts and diff come later', { notNow: true }),
st('Delete type: blocked', N, 'Delete content type on a type with entries. No confirm button.', { v: 'review', k: 'blocked' }, 'You can\'t delete Events yet · A content type can only be deleted when it has no entries. · Events has 37 entries · Delete all of its entries first, then delete the content type. · Close · View entries'),
st('Delete type: confirm', N, 'Delete content type on an empty type.', { v: 'review', k: 'confirm' }, 'Delete Recipes? · Recipes has no entries. Its fields and its API routes will be deleted. This can\'t be undone. · Key: recipes · Cancel · Delete content type'),
st('Delete type: server fallback (409)', N, '409 content_type_has_entries. An entry was added after the page loaded.', { v: 'review', k: 'fallback' }, 'Recipes now has entries · Someone added an entry after this page loaded, so nothing was deleted. Delete the entries first, then try again. · Close · View entries')
] },
{ label: '4 Field types', title: '4 Field-type gallery', route: 'reference board', api: '', auth: 'n/a', note: 'One frame per type: inspector options, the entry form control (default and open states), the list cell with its empty state, the error message for each rule, and the filter widget. Filters are later: filtering on custom fields is not in the API. Mobile drops the inspector column (the builder frames show it as a sheet).', states: ['text', 'richtext', 'number', 'boolean', 'date', 'select'].map((t, i) => st(['Text', 'Rich text', 'Number', 'Yes or no', 'Date', 'Choice'][i], N, 'type: "' + t + '"', { v: 'gallery', k: t }, ({ text: 'Text · Short text, like a title or a name · Shortest · Longest · characters · 74 / 80 · Fill in Title. · Title must be text. · Title needs at least 3 characters. · Title can be up to 80 characters. · Another entry already uses this Title. Enter a different one.', richtext: 'Rich text · Long text with formatting, written in Markdown · Write · Preview · Markdown. Switch to Preview to check the result. · 86 / 5000 · Not available for rich text. (Unique)', number: 'Number · Whole or decimal numbers · Lowest value · Highest value · Enter a number · Between 1 and 5000. · Description must be a number. · Capacity must be at least 1. · Capacity must be at most 5000.', boolean: 'Yes or no · An on or off switch · On by default · Yes or no fields have no limits. · Not available for yes or no fields. (Unique) · Choose yes or no for Online. · Online must be yes or no.', date: 'Date · A calendar day, without a time · Earliest date · Latest date · Pick a date · Pick a date for Starts on. · Starts on must be a date, like 2026-11-21. · Starts on can\'t be before 1 Jan 2026. · Starts on can\'t be after 31 Dec 2027.', select: 'Choice · One option from a list you define · Choices · Choose an option · Choose one of: Talk, Workshop or Meetup. · Another entry already uses this choice for Category.' })[t])) },
{ label: '5 Content and entry list', title: '5 Content navigation and entry list', route: '/content/:key', api: 'GET /v1/content-type/{key}, GET /v1/content-type/{key}/entry', auth: 'Any verified user', note: 'The sidebar gets a "Content" group, one item per custom type (a default icon: types have no icon in the API). With more than 5 types it shows the first 5 and the selected one, then "Show all N"; long names truncate with the full name in a tooltip. On mobile the group is one collapsed row in the drawer. List: ID, up to 6 chosen field columns (default: first 4), Created, Updated, Updated by. Sort: ID, Created, Updated, either direction (default Updated, newest first). Page size 5, 25, 50, 100 (default 25). No filter or search.', states: [
st('Populated', N, '/content/events. 7 entries, one page: no pager, only the count.', { v: 'entries', k: 'ok' }, 'Content · Events · events · 7 fields · New entry · Sort by · Last updated · Columns · Edit content type · ID · Title · Starts on · Ends on · Online · Created · Updated · Updated by · 7 entries'),
st('Paginated, 5 per page', N, '/content/events?size=5. 37 entries.', { v: 'entries', k: 'paged' }, 'Showing 1–5 of 37 · 5 per page · Page 1 of 8 (mobile)'),
st('Columns menu', N, 'The Columns button. Popover on desktop, sheet on mobile. Created and updated always show.', { v: 'entries', k: 'cols' }, 'Columns · 4 of 6 · Choose up to 6 fields to show. 4 selected. · Created and updated dates always show · Reset · Done'),
st('Many types in the sidebar', N, '14 custom types. Long names truncate. Mobile shows the drawer with the group expanded.', { v: 'entries', k: 'ok', many: true }, 'Content · Frequently asked questions and answers (truncated) · Show all 14 · All content types 14 (mobile, collapsed)'),
st('Loading', N, 'First load or retry.', { v: 'entries', k: 'loading' }, '(skeleton)'),
st('Empty for this type', N, 'Total is 0. The hint points to New entry.', { v: 'entries', k: 'empty' }, 'No entries yet · Use New entry to add the first event. Each entry follows the fields of this content type. · New entry'),
st('Error', N, '500 or network failure.', { v: 'entries', k: 'error' }, 'Couldn\'t load entries · GET /v1/content-type/events/entry failed. Check your connection and try again. · Try again'),
st('Forbidden (403)', N, 'The API answers 403. Unverified accounts are redirected to /register/pending before this.', { v: 'entries', k: 'forbidden', role: 'user' }, 'You don\'t have access to Events · Your account can\'t open this content right now. If you think this is a mistake, ask an owner or an admin. · Go to Home'),
st('Type not found', N, '404 content_type_not_found on /content/unknown.', { v: 'entries', k: 'notfound' }, 'Content type not found · It may have been deleted, or the address may be mistyped. · Go to Home')
] },
{ label: '6 Entry editor', title: '6 Entry editor', route: '/content/:key/new, /content/:key/:id', api: 'POST /v1/content-type/{key}/entry, GET/PUT/DELETE /v1/content-type/{key}/entry/{id}', auth: 'Any verified user', note: 'The form is generated from the schema, one control per field in schema order. Required fields carry * and the line "Fields marked * are required." Defaults are pre-filled on create and tagged Default. Saving replaces the whole entry.', states: [
st('New entry', N, '/content/events/new. Online is pre-filled from its default.', { v: 'entry', k: 'new' }, 'New entry · Events · Fields marked * are required. · Default · Each entry needs a different title. · Between 1 and 5000. · Choose an option · Pick a date · Save · Cancel · New entry · Not saved yet'),
st('Editing', N, '/content/events/42. Save is disabled until something changes.', { v: 'entry', k: 'edit' }, 'Lime plaster workshop · Events · Entry 42 · Saved · Delete · Cancel · Save · Created by · Updated by · Inès Duarte · 12 Oct 2026, 09:14 · Marta Alves · 15 Oct 2026, 11:02'),
st('Unsaved changes', N, 'Any edit.', { v: 'entry', k: 'dirty' }, 'Unsaved changes · 32 / 80'),
st('Markdown preview', N, 'The Preview tab of a rich text field.', { v: 'entry', k: 'preview' }, 'Write · Preview'),
st('Saving', N, 'PUT or POST in flight. Form dims.', { v: 'entry', k: 'saving' }, 'Saving…'),
st('Saved', N, '200.', { v: 'entry', k: 'saved' }, 'Saved at 11:02 · Entry saved · "Lime plaster workshop" is up to date.'),
st('Save failed', N, '500 or network failure. Values stay.', { v: 'entry', k: 'fail' }, 'Save failed · Couldn\'t save the entry · Something went wrong on our side. Your changes are still here. Try again in a moment. · Try again'),
st('Required fields empty', N, '422 invalid_entry: title: required, starts_on: required. The first field with an error takes focus.', { v: 'entry', k: 'required' }, 'Fill in Title. · Pick a date for Starts on. · Not saved'),
st('Rule errors', N, '422 invalid_entry for max, type, max and options. One rule per field is shown at a time.', { v: 'entry', k: 'rules' }, 'Title can be up to 80 characters. · 91 / 80 · Ends on must be a date, like 2026-11-21. · Capacity must be at most 5000. · Choose one of: Talk, Workshop or Meetup. · Not saved'),
st('Duplicate unique value (409)', N, '409 invalid_entry: title: unique.', { v: 'entry', k: 'unique' }, 'Not saved · Another entry already uses this title. Change it and save again. · Another entry already uses this Title. Enter a different one.'),
st('Entry not found', N, '404 entry_not_found, for example after a delete elsewhere.', { v: 'entry', k: 'notfound' }, 'Entry not found · It may have been deleted by someone else. · Back to Events'),
st('Schema changed since load', N, '422 invalid_entry: room: required, or unknown_field. The form is read-only until reloaded.', { v: 'entry', k: 'changed' }, 'The fields of Events changed · A field was removed and a new required field, Room, was added after you opened this form. Reload the form to continue. What you typed here can\'t be saved against the old fields. · Reload form'),
st('Delete entry: confirm', N, 'Delete.', { v: 'entry', k: 'delete' }, 'Delete this entry? · "Lime plaster workshop" will be deleted from Events. This can\'t be undone. · Cancel · Delete entry')
] },
{ label: '7 Relations', title: '7 Relation field and picker', route: '/schema/:key, /content/:key/:id', api: 'not built', auth: 'Owner or admin (picker), any verified user (form)', note: 'All later. The model reads as two sentences, with a live preview of both sides. Three shapes: one to one, one to many, many to many.', states: [
st('Relation in the builder', L, 'A seventh type, Relation, in the type gallery.', { v: 'rel', k: 'builder' }, 'Relation · Related content type · How are they connected? · One to one · Each Event has one Venue, and each Venue has one Event. · One to many · Each Event has one Venue. A Venue has many Events. · Many to many · Each Event has many Venues, and each Venue has many Events. · Each Event has one Venue · Each Venue has many Events · shown on Venue as the field "Events"'),
st('Relation in the entry form', L, 'Search and pick; chips for many.', { v: 'rel', k: 'form' }, 'Venue · Speakers · Search to add · An event can have many speakers.'),
st('Relation in the list', L, 'One chip, two chips and +N, or a dash.', { v: 'rel', k: 'list' }, 'One chip for a single relation. Up to two chips and a "+N" for many. Empty shows a dash.')
] },
{ label: '8 Permissions', title: '8 Permissions grid', route: '/settings/permissions', api: 'not built', auth: 'Owner or admin', note: 'All later. Rows are types, columns are actions, one role at a time. Built-in rows are locked. Mobile collapses to one card per type with four checkboxes.', states: [
st('Default: today\'s rules', L, 'Role User selected. Everything on, as today.', { v: 'perms', k: 'default' }, 'Permissions · What each role can do with each content type. · Today\'s rules are the starting point · Owners and admins edit the schema. Any verified user can read, add, edit and delete entries. · Owner · Admin · User · Read · Create · Update · Delete · Built-in types. RenewCMS sets these rules. · Schema (create, edit and delete content types): owners and admins only. Set by RenewCMS. · No changes · Discard · Save permissions'),
st('Changed, not saved', L, 'Two types restricted for the User role.', { v: 'perms', k: 'changed' }, '4 changes not saved · Changed')
] },
{ label: '9 Export and import', title: '9 Schema export and import', route: '/schema (dialogs)', api: 'not built', auth: 'Owner or admin', note: 'All later. Dev-to-production flow: export a file, import it elsewhere, preview, same compatibility review as group 3, explicit confirm.', states: [
st('Export', L, 'Export on /schema.', { v: 'xport', k: 'export' }, 'Export schema · Download the fields of your content types as a file. Entries aren\'t included. · All content types · 3 content types · One content type · Choose which one · File name · renewcms-schema.json · Import this file on another RenewCMS site to create the same content types. · Cancel · Download file'),
st('Import preview', L, 'A file was chosen.', { v: 'xport', k: 'import' }, 'Import schema · renewcms-schema.json · 3 content types · Create 1, change 1, no change 1 · Recipes · New content type with 4 fields. · Events · Add 2 fields, remove Description. Events has 37 entries on this site. · Removes data · Press mentions · Same as on this site. · Existing entries are checked against the changes when you import. If any entry doesn\'t fit, nothing is imported. · Cancel · Import schema'),
st('Import refused', L, 'The server answers schema_incompatible.', { v: 'xport', k: 'refused' }, 'Nothing was imported · Some entries on this site don\'t fit the imported fields. RenewCMS can\'t tell which entries. The flagged change can cause this. · Try again')
] }
]
export const tables = [
{ title: 'Scope: available now or later', tpl: '260px 110px minmax(0,1fr)', cols: ['Feature', 'Status', 'Notes'], rows: [
['1 Schema list, built-in rows, read-only view', 'Available now', 'Built-in list is static client data (see Needs backend)'],
['2 Schema builder, all states', 'Available now', ''],
['Live API preview', 'Available now', 'Built on the client from the field list'],
['Type-level and field-level validation', 'Available now', 'Same rules as the server, shown while typing'],
['3 Review step and Apply', 'Available now', 'Needs the entry total (see Needs backend)'],
['3 Refusal state, delete type, blocked delete', 'Available now', ''],
['3 Per-change entry counts, full diff', 'Later', 'The API does not return them'],
['4 Field-type gallery', 'Available now', 'Filter widgets inside it are Later'],
['5 Content group in the sidebar, entry list', 'Available now', 'No filter or search on custom fields'],
['6 Entry editor, all states', 'Available now', ''],
['7 Relation field and picker', 'Later', ''],
['8 Permissions grid', 'Later', ''],
['9 Schema export and import', 'Later', ''],
['Filters on custom fields', 'Later', ''],
['Publish and draft state for entries', 'Later', 'Not drawn'],
['Public (anonymous) read access', 'Later', 'Not drawn'],
['Activity log entries for types and entries', 'Later', 'Not drawn']] },
{ title: 'Routes', tpl: '190px 280px 200px minmax(0,1fr)', cols: ['Route', 'Screen', 'Auth', 'API'], rows: [
['/schema', 'Schema list', 'Owner or admin. Others get the 403 page', 'GET /v1/content-type'],
['/schema/new', 'Schema builder, new type', 'Owner or admin', 'POST /v1/content-type'],
['/schema/:key', 'Schema builder (custom type) or read-only view (built-in)', 'Owner or admin', 'GET, PUT, DELETE /v1/content-type/{key}'],
['/content/:key', 'Entry list', 'Any verified user', 'GET /v1/content-type/{key}, GET /v1/content-type/{key}/entry'],
['/content/:key/new', 'New entry', 'Any verified user', 'POST /v1/content-type/{key}/entry'],
['/content/:key/:id', 'Entry editor', 'Any verified user', 'GET, PUT, DELETE /v1/content-type/{key}/entry/{id}'],
['/settings/permissions (later)', 'Permissions grid', 'Owner or admin', 'Not built'],
['/content/:key query', 'page, size (5, 25, 50, 100; default 25), sort (id, created_at, updated_at) and dir (asc, desc); default updated_at desc', 'Any verified user', 'Defaults omitted from the URL. Parameter names sort and dir are an assumption']] },
{ title: 'New components and their Nuxt UI mapping', tpl: '210px 110px 330px minmax(0,1fr)', cols: ['Component', 'Status', 'Nuxt UI', 'Why an existing one does not fit'], rows: [
['SchemaTable', 'New', 'UTable; below 640 px a list of UCard', 'Same pattern as SitesTable. Built-in rows add the lock and a Built-in badge'],
['BuiltInBadge', 'New', 'UBadge outline + lock icon', 'Existing badges have no lock; same size as the Linked badge'],
['FieldList', 'New', 'List of UButton rows, useSortable, UBadge', 'No Nuxt UI sortable list. Keyboard: the grip is a button; Space picks up, arrows move, Space drops, Esc cancels. Move up and Move down buttons on the selected row. Same approach as AuthorList'],
['FieldInspector', 'New', 'UForm, UFormField, UInput, UInputNumber, UInputDate, USelect, UTextarea, USwitch', 'Composition only. Controls follow the field type'],
['FieldTypePicker', 'New', 'URadioGroup variant="card" in a grid, icon in the label', 'Existing radio cards fit; only the icon and the lock state are added'],
['KeyField', 'Existing', 'SlugField (UInput + UButton + UBadge)', 'Reused for the type key and field keys. Locked variant already exists'],
['ChoicesEditor', 'New', 'UInput + UButton rows, useSortable', 'UInputTags can\'t reorder or flag a blank or duplicate per row'],
['ApiPreview', 'New', 'UCollapsible + CodeSnippet + UButton', 'CodeSnippet is reused. Sheet on mobile'],
['ChangeReview', 'New', 'UModal (sheet on mobile), UBadge, list rows', 'Dialog pattern unchanged. Rows reuse the UAlert-style row of SuggestionList'],
['SchemaRefusal, DeleteTypeDialog', 'New', 'UModal + UAlert', 'Dialog pattern unchanged. Delete uses color="error"'],
['ContentNavGroup', 'New', 'UNavigationMenu group "Content" (NavGroup)', 'Adds the 5 + selected cap, "Show all N" and the collapsed mobile row'],
['EntryTable', 'New', 'UTable with column visibility', 'Cells per field type (FieldCell). Cards on mobile'],
['ColumnPicker', 'New', 'UPopover + UCheckbox list; bottom sheet on mobile', 'UDropdownMenu closes on each pick and has no cap message'],
['SortSelect', 'New', 'USelect + UButton icon', 'ID, Created and Updated only'],
['FieldControl', 'New', 'UInput, UInputNumber, UInputDate, USelect, USwitch (the single toggle), MarkdownField', 'One switch per field type, generated from the schema'],
['MarkdownField', 'New', 'UTextarea + UTabs (Write, Preview) + toolbar of UButton', 'The article editor is a full document editor. This is a compact one'],
['FieldCell', 'New', 'text, UBadge outline (choice), icon + text (yes or no)', 'Renders one value per type, with the empty dash'],
['EntryForm', 'New', 'UForm generated from the schema', 'Provenance footer, schema-changed alert'],
['RelationPicker (later)', 'New', 'URadioGroup card + USelect', 'Sentence preview is text'],
['RelationField (later)', 'New', 'UInputMenu multiple', 'Chips and search'],
['PermissionsGrid (later)', 'New', 'UTable + UCheckbox; UCard list on mobile', ''],
['SchemaImportDialog (later)', 'New', 'UModal + UFileUpload', '']] },
{ title: 'Errors to copy', tpl: '300px 70px minmax(0,1fr)', cols: ['Error', 'HTTP', 'Copy and place'], rows: [
['content_type_not_found', '404', 'Page: "Content type not found · It may have been deleted, or the address may be mistyped."'],
['entry_not_found', '404', 'Page: "Entry not found · It may have been deleted by someone else."'],
['content_type_key_taken', '409', 'Under the key: "The key "events" is already used by another content type. Choose a different key."'],
['content_type_has_entries', '409', 'Delete dialog: "Recipes now has entries · Someone added an entry after this page loaded, so nothing was deleted. Delete the entries first, then try again."'],
['invalid_content_type_key', '400', 'Under the key: "Use 2 to 40 lowercase letters, digits or hyphens."'],
['invalid_field', '400', 'On the marked field, per rule (label, key, limits, default, choices). If the client missed one: "Check the fields marked in the list."'],
['schema_incompatible', '422', 'Refusal dialog: "Nothing was changed · RenewCMS refused the changes because some entries don\'t fit the new fields. It doesn\'t say which entries."'],
['invalid_entry: key: required', '422', '"Fill in Title." (date: "Pick a date for Starts on.", choice: "Choose an option for Category.")'],
['invalid_entry: key: type', '422', '"Title must be text." / "must be a number." / "must be yes or no." / "must be a date, like 2026-11-21."'],
['invalid_entry: key: min, max', '422', 'Text: "needs at least N characters", "can be up to N characters". Number: "must be at least N", "must be at most N". Date: "can\'t be before D", "can\'t be after D"'],
['invalid_entry: key: options', '422', '"Choose one of: Talk, Workshop or Meetup."'],
['invalid_entry: key: unique', '409', '"Another entry already uses this Title. Enter a different one." plus the alert "Not saved"'],
['invalid_entry: key: unknown_field', '422', 'Alert "The fields of Events changed", button Reload form'],
['401', '401', 'Existing: redirect to /login?redirect=…&reason=expired'],
['403', '403', 'Unverified: redirect to /register/pending. Wrong role on /schema: "You don\'t have access to Schema"'],
['400, 500', '', 'Existing table. Saves: "Couldn\'t save the … Something went wrong on our side. Your changes are still here. Try again in a moment."']] },
{ title: 'Needs backend', tpl: '40px minmax(0,1fr)', cols: ['#', 'What the design assumes'], rows: [
['1', 'Total number of entries of a type (X-Total-Count or a body field, as on Articles). Used for pagination, "37 entries use this content type" and the blocked delete.'],
['2', 'Names of the sort and direction parameters on the entry list (drawn as sort and dir).'],
['3', 'Built-in types and their fields. GET /v1/content-type returns custom types only, so the read-only views use static client data, or a new read-only endpoint.'],
['4', 'created_by and updated_by are user ids. Any verified user needs their display names, but the user list is not open to all roles. Needs a name in the entry response or a light lookup.'],
['5', 'A per-type icon does not exist. The sidebar uses one default icon.'],
['6', 'The exact alphabet of the type key ("lowercase slug"). Drawn as letters, digits and hyphens.'],
['7', 'Locked field keys and types of saved fields are a client rule: a PUT with a changed key would remove one field and add another. The server does not reject it.'],
['8', 'No signal that the schema changed while a form was open. The design relies on 422 invalid_entry (required, unknown_field) on save.'],
['9', 'default of false versus no default for a yes or no field: needs null for "no default".'],
['10', 'Later: per-change entry counts and diff, relations, permissions, export and import, filters on custom fields, publish and draft, public read, activity log.']] },
{ title: 'Decisions to confirm', tpl: '40px minmax(0,1fr)', cols: ['#', 'Decision'], rows: [
['1', 'Field keys and types lock per field once saved. Fields added since the last save can still change both.'],
['2', 'The review opens only when the type has entries. A type without entries saves directly.'],
['3', 'A new type starts with one field (Title), because a type needs at least one field.'],
['4', 'Yes or no is the label for the boolean type, Choice for select, Rich text for richtext.'],
['5', 'Required fields carry * and the line "Fields marked * are required." Optional fields carry nothing, unlike the "(optional)" tag used in settings forms, because most fields are optional here.'],
['6', 'The Schema item sits after Users in the sidebar. The Content group sits under the main items.'],
['7', 'The list shows 4 field columns by default and at most 6.']] },
{ title: 'Accessibility', tpl: '220px minmax(0,1fr)', cols: ['Topic', 'Rule'], rows: [
['Reorder', 'The grip is a button with aria-label "Move Ends on". Space picks up, Up and Down move, Space drops, Esc cancels, with a polite live region ("Moving Ends on. Position 2 of 7."). Move up, Move down and Remove buttons exist on the selected row and in the mobile sheet.'],
['Focus order', 'Name, key, Save, Discard, field list (one tab stop, arrows move between rows), inspector top to bottom, API preview. Opening the inspector sheet on mobile moves focus to its title; closing returns it to the row.'],
['Focus', '2 px --ui-primary, offset 2 px, as everywhere.'],
['Labels and errors', 'Every control has a visible label. Error text is tied to its input with aria-describedby and aria-invalid. Rows with errors also show an icon, not only a red border.'],
['Type picker', 'A radio group. The locked state sets aria-disabled and the line "Can\'t change after saving" is read with the group.'],
['Counters', 'Character counters are polite live regions on pause, not on every key.'],
['Contrast', 'Tokens already computed in foundations.md. Muted text is never placed on sand; selected tiles use --rc-on-sand for their description.'],
['Touch', 'Controls are 44 px on mobile. The inspector, columns and API preview are bottom sheets.']] }
]
+25
View File
@@ -54,6 +54,19 @@ Glossary pass 2, changes made: activity log lines "Removed N expired invites" an
| 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." |
| 404 content_type_not_found | Page: "Content type not found · It may have been deleted, or the address may be mistyped." |
| 404 entry_not_found | Page: "Entry not found · It may have been deleted by someone else." |
| 409 content_type_key_taken | Under the key: "The key "events" is already used by another content type. Choose a different key." |
| 409 content_type_has_entries | Delete dialog: "Recipes now has entries · Someone added an entry after this page loaded, so nothing was deleted. Delete the entries first, then try again." |
| 400 invalid_content_type_key | Under the key: "Use 2 to 40 lowercase letters, digits or hyphens." |
| 400 invalid_field | On the marked field, per rule (label, key, limits, default, choices). If the client missed one: "Check the fields marked in the list." |
| 409 schema_incompatible | Refusal dialog: "Nothing was changed · RenewCMS refused the changes because some entries don't fit the new fields. It doesn't say which entries." |
| 422 invalid_entry: key: required | "Fill in Title." (date: "Pick a date for Starts on.", choice: "Choose an option for Category.") |
| 422 invalid_entry: key: type | "Title must be text." / "must be a number." / "must be yes or no." / "must be a date, like 2026-11-21." |
| 422 invalid_entry: key: min, max | Text: "needs at least N characters", "can be up to N characters". Number: "must be at least N", "must be at most N". Date: "can't be before D", "can't be after D" |
| 422 invalid_entry: key: options | "Choose one of: Talk, Workshop or Meetup." |
| 409 invalid_entry: key: unique | "Another entry already uses this Title. Enter a different one." plus the alert "Not saved" |
| 422 invalid_entry: key: unknown_field | Alert "The fields of Events changed", button Reload form |
| 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
@@ -79,3 +92,15 @@ 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.
## Custom content types
Groups on `RenewCMS Screens Schema.dc.html`: 1 Schema list (6), 2 Schema builder (16), 3 Review and delete (7), 4 Field types (6), 5 Content and entry list (9), 6 Entry editor (13), 7 Relations (3), 8 Permissions (2), 9 Export and import (3). 65 states, 56 available now and 9 later. Each has a 1440 and a 390 frame; light and dark follow the theme switch. Nothing is clock-sensitive. Tag per state: "Available now" or "Later". Copy per state: screens/schema.md, content.md, entry.md, schema-later.md.
Roles: owners and admins see Schema and edit types. Any verified user sees the Content group and reads and writes entries. A user who is not owner or admin and opens /schema gets "You don't have access to Schema".
Keys: a type key is 2 to 40 lowercase letters, digits and hyphens (chosen at creation, never changes). A field key is lowercase letters, digits and underscores, starts with a letter, up to 40 (editable until its field is first saved). The two inputs show their own rule.
Schema changes with entries: Save opens the review ("Add 2 fields, change 1, remove 1"); Apply sends the PUT; schema_incompatible shows "Nothing was changed" and names the kind of change that likely caused it, never an entry. A type with entries cannot be deleted ("You can't delete Events yet").
Entry rules, 422 except unique (409): required, type, min, max, options, unique, unknown_field. Messages are per type and drawn in the field-type gallery (group "Field types").
+355
View File
@@ -0,0 +1,355 @@
Feature: Owners and admins define custom content types, and users manage entries of those types through a generic /v1 API
As a site owner or admin
I want to define content types made of ordered scalar fields, and then create entries of those types
So that I can store structured content beyond articles, with the schema enforced by the server
Background:
Given internal/domain/contenttype defines the entity ContentType with ID uint32, Key, Name,
Fields []Field, CreatedAt and UpdatedAt, with snake_case json tags
And Field is a value object, ordered by its position in ContentType.Fields, with Key, Label,
Type, Required, Unique, Default, Min, Max and Options
And the field types are "text", "richtext", "number", "boolean", "date" and "select"
And a content type key matches the domain slug rule and has 2 to 40 characters
And a field key matches ^[a-z][a-z0-9_]{0,39}$, is unique within its type, and a type has 1 to 50 fields
And internal/domain/contenttype defines the sentinels ErrContentTypeNotFound, ErrKeyTaken,
ErrInvalidKey, ErrInvalidField, ErrHasEntries and ErrSchemaIncompatible
And internal/domain/contenttype defines the interface Repository with Create, GetByKey, List,
Update and Delete
And internal/domain/entry defines the entity Entry with ID uint32, ContentTypeID, Data
(a JSON object), CreatedBy, UpdatedBy, CreatedAt and UpdatedAt
And internal/domain/entry defines the sentinels ErrEntryNotFound, ErrInvalidEntry and
ErrUniqueViolation, and the interface Repository with Create, Get, ListPage, Update, Delete,
DeleteByContentType, CountByContentType and FindByFieldValue(contentTypeID, fieldKey, value, excludeID)
And schema validation of a field list and of an entry's data lives in the domain/use cases,
never in handlers, and handler request structs still use validate tags
And the use cases CreateContentType, ListContentTypes, GetContentType, UpdateContentType,
DeleteContentType, CreateEntry, GetEntry, ListEntries, UpdateEntry and DeleteEntry depend only
on the two domain repositories and an injected clock
And persistence stores content types in one table with the fields as a JSON text column, and
entries in one generic table with the data as a JSON text column, so no DDL runs at runtime
and the SQL is portable across SQLite, MySQL/MariaDB and PostgreSQL
And both GORM models are added to the AutoMigrate list and wired only in api/dependecyInjection.go
And the built-in articles, authors, sites, media and users are not part of this engine
And the routes are mounted under /v1/content-type in a router with jwtauth.Verifier, apiKeyAuth,
AuditContext, RequireSignedIn, jwtauth.Authenticator, RequireCurrentToken and
RequireVerifiedUser, and POST /v1/content-type, PUT /v1/content-type/{key} and
DELETE /v1/content-type/{key} additionally sit behind RequireOwnerOrAdmin
And a content type response has exactly the keys id, key, name, icon, fields, created_at, updated_at
And a field response has exactly the keys key, label, type, required, unique, default, min, max,
options, with null for an unset default, min and max and [] for no options
And an entry response has exactly the keys id, content_type, data, created_by, updated_by,
created_at, updated_at, where content_type is the type's key
And errors are plain text from http.Error, and the new apperr strings are
content_type_not_found, content_type_key_taken, content_type_has_entries,
invalid_content_type_key, invalid_field, schema_incompatible, entry_not_found and invalid_entry
And users: owner id 1 "marta" (verified), admin id 2 "dev" (verified), unverified id 4 "quinn"
And the sample type "recipe" has the fields, in order:
| key | type | required | unique | default | min | max | options |
| title | text | true | true | | 3 | 80 | |
| servings | number | false | false | 4 | 1 | 50 | |
| vegetarian | boolean | false | false | false | | | |
| published_on | date | false | false | | | | |
| difficulty | select | true | false | | | | easy, medium, hard |
| notes | richtext | false | false | | | 500 | |
Scenario: Creating a content type
Given a valid jwt cookie for admin 2
When the client sends POST /v1/content-type with body
{"key": "recipe", "name": "Recipe", "fields": [<the sample fields>]}
Then the response status is 201
And the body has exactly the keys id, key, name, icon, fields, created_at, updated_at
And key is "recipe" and the fields come back in the order sent
And each field has exactly the keys key, label, type, required, unique, default, min, max, options
Scenario Outline: Creating a content type with an invalid body is refused and stores nothing
Given a valid jwt cookie for admin 2
When the client sends POST /v1/content-type with <body>
Then the response status is <status>
And the response body is <message>
And no content type exists in the repository
Examples:
| body | status | message |
| body not-json | 400 | apperr.BodyErrorMessage |
| body {} | 400 | text containing 'Key' and 'required' |
| {"key": "Recipe!", "name": "R", "fields": [<one text field>]} | 400 | invalid_content_type_key |
| {"key": "r", "name": "R", "fields": [<one text field>]} | 400 | invalid_content_type_key |
| {"key": "recipe", "name": "", "fields": [<one text field>]} | 400 | text containing 'Name' and 'required' |
| {"key": "recipe", "name": "R", "fields": []} | 422 | invalid_field |
| {"key": "recipe", "name": "R", "fields": [<51 fields>]} | 422 | invalid_field |
| a field key "Title" or "1st" or "a-b" | 422 | invalid_field |
| two fields with the key "title" | 422 | invalid_field |
| a field type "integer" | 422 | invalid_field |
| a select field with no options, an empty option, or a duplicated option | 422 | invalid_field |
| options on a non-select field | 422 | invalid_field |
| min or max on a boolean or select field | 422 | invalid_field |
| min greater than max | 422 | invalid_field |
| a negative or fractional min or max on a text or richtext field | 422 | invalid_field |
| a non-date min or max on a date field | 422 | invalid_field |
| unique true on a richtext or boolean field | 422 | invalid_field |
| a default of the wrong type, outside min/max, or not in the options | 422 | invalid_field |
| a default on a unique field | 422 | invalid_field |
Scenario: A content type key can't be reused
Given the content type "recipe" exists
When admin 2 sends POST /v1/content-type with the key "recipe"
Then the response status is 409
And the response body is content_type_key_taken
And only one content type exists
Scenario Outline: Writing content types needs a verified owner or admin
Given <caller>
When the client sends POST /v1/content-type with a valid body
Then the response status is <status>
And the response body is <message>
And no content type exists in the repository
Examples:
| caller | status | message |
| no credentials | 401 | the existing Authenticator response |
| a jwt cookie for user 4 | 403 | apperr.VerificationRequiredErrorMessage |
| a stale token_version cookie | 401 | the existing Authenticator response |
Scenario: An API key acts as its creator on the content type routes
Given an active key created by admin 2
When the client sends POST /v1/content-type with that key and no cookie and a valid body
Then the response status is 201
Scenario: Listing and reading content types
Given the content types "recipe" and "event" exist
And a valid jwt cookie for any verified user
When the client sends GET /v1/content-type
Then the response status is 200
And the body is a JSON array of both content types, ordered by name
When the client sends GET /v1/content-type/recipe
Then the response status is 200 and the body is the "recipe" content type
Scenario Outline: Reading a content type that doesn't exist or with a bad key
Given a valid jwt cookie for admin 2
When the client sends <method> /v1/content-type/<key> <body>
Then the response status is <status>
And the response body is <message>
Examples:
| method | key | body | status | message |
| GET | nope | | 404 | content_type_not_found |
| PUT | nope | and a valid schema body | 404 | content_type_not_found |
| DELETE | nope | | 404 | content_type_not_found |
| GET | Bad_Key | | 404 | content_type_not_found |
Scenario: Updating a content type before it has entries
Given the content type "recipe" exists with no entries
When admin 2 sends PUT /v1/content-type/recipe with a new name, a removed field, a reordered
list and a changed field type
Then the response status is 200
And the body shows the new name, the new field order and the new field type
And the key is still "recipe"
Scenario: The key of a content type can't be changed
Given the content type "recipe" exists
When admin 2 sends PUT /v1/content-type/recipe with body key "dish"
Then the response status is 200
And the key is still "recipe"
Scenario Outline: Updating a content type that has entries
Given the content type "recipe" has an entry {"title": "Pad thai", "difficulty": "easy"}
When admin 2 sends PUT /v1/content-type/recipe with <change>
Then the response status is <status>
And the response body is <message>
And the stored schema is <outcome>
Examples:
| change | status | message | outcome |
| a field's type changed from text to number | 422 | invalid_field | unchanged |
| a new required field without a default | 409 | schema_incompatible | unchanged |
| a new required field with a default | 200 | | updated |
| a new optional field | 200 | | updated |
| the field "notes" removed | 200 | | updated |
| the option "easy" removed from difficulty | 409 | schema_incompatible | unchanged |
| the option "hard" removed from difficulty | 200 | | updated |
| title max lowered below the stored title's length | 409 | schema_incompatible | unchanged |
| label, order or name changed | 200 | | updated |
Scenario: Making a field unique is refused when stored values collide
Given the type "recipe" has two entries with the title "Pad thai" and the title is not unique
When admin 2 sends PUT /v1/content-type/recipe making title unique
Then the response status is 409 with schema_incompatible and the schema is unchanged
Scenario: Values of a removed field are no longer returned
Given an entry with notes "Soak overnight" and a schema update that removes "notes"
When a user sends GET on that entry
Then data has no "notes" key
When the entry is saved again through PUT
Then the stored document has no "notes" key
Scenario: Deleting a content type
Given the content type "event" exists with no entries
When admin 2 sends DELETE /v1/content-type/event
Then the response status is 204 and the body is empty
And GET /v1/content-type/event returns 404 with content_type_not_found
Scenario: A content type with entries can't be deleted
Given the content type "recipe" has one entry
When admin 2 sends DELETE /v1/content-type/recipe
Then the response status is 409
And the response body is content_type_has_entries
And the type and its entry still exist
Scenario: Creating an entry applies defaults
Given the content type "recipe" exists and a valid jwt cookie for admin 2
When the client sends POST /v1/content-type/recipe/entry with body
{"data": {"title": "Pad thai", "difficulty": "easy"}}
Then the response status is 201
And the body has exactly the keys id, content_type, data, created_by, updated_by, created_at, updated_at
And content_type is "recipe", created_by and updated_by are 2
And data is {"title": "Pad thai", "difficulty": "easy", "servings": 4, "vegetarian": false}
And data has no "published_on" and no "notes" key
Scenario: An explicit value overrides the default and an explicit null is kept
Given the content type "recipe" exists
When the client creates an entry with {"title": "Soup", "difficulty": "easy", "servings": 2, "published_on": null}
Then data servings is 2 and published_on is null and no default is applied to published_on
Scenario Outline: Creating an entry that breaks the schema is refused and stores nothing
Given the content type "recipe" exists and a valid jwt cookie
When the client sends POST /v1/content-type/recipe/entry with <body>
Then the response status is <status>
And the response body is <message>
And no entry exists
Examples:
| body | status | message |
| body not-json | 400 | apperr.BodyErrorMessage |
| {} | 400 | apperr.BodyErrorMessage |
| {"data": "x"} | 400 | apperr.BodyErrorMessage |
| {"data": {"difficulty": "easy"}} | 422 | invalid_entry: title: required |
| {"data": {"title": null, "difficulty": "easy"}} | 422 | invalid_entry: title: required |
| {"data": {"title": 5, "difficulty": "easy"}} | 422 | invalid_entry: title: type |
| {"data": {"title": "ab", "difficulty": "easy"}} | 422 | invalid_entry: title: min |
| {"data": {"title": "<81 runes>", "difficulty": "easy"}} | 422 | invalid_entry: title: max |
| {"data": {"title": "Soup", "difficulty": "extreme"}} | 422 | invalid_entry: difficulty: options |
| {"data": {"title": "Soup", "difficulty": "easy", "servings": 0}} | 422 | invalid_entry: servings: min |
| {"data": {"title": "Soup", "difficulty": "easy", "servings": 51}} | 422 | invalid_entry: servings: max |
| {"data": {"title": "Soup", "difficulty": "easy", "servings": "4"}} | 422 | invalid_entry: servings: type |
| {"data": {"title": "Soup", "difficulty": "easy", "vegetarian": "yes"}} | 422 | invalid_entry: vegetarian: type |
| {"data": {"title": "Soup", "difficulty": "easy", "published_on": "2026-02-30"}} | 422 | invalid_entry: published_on: type |
| {"data": {"title": "Soup", "difficulty": "easy", "published_on": "2026-02-01T10:00:00Z"}} | 422 | invalid_entry: published_on: type |
| {"data": {"title": "Soup", "difficulty": "easy", "notes": "<501 runes>"}} | 422 | invalid_entry: notes: max |
| {"data": {"title": "Soup", "difficulty": "easy", "colour": "red"}} | 422 | invalid_entry: colour: unknown_field |
Scenario: Boundary values are accepted
Given the content type "recipe" exists
When entries are created with a title of exactly 3 runes, exactly 80 runes, servings 1 and servings 50
Then each response status is 201
Scenario: Unique fields reject duplicates and ignore the entry itself
Given the content type "recipe" has an entry 7 with the title "Pad thai"
When the client sends POST /v1/content-type/recipe/entry with the title "Pad thai"
Then the response status is 409
And the response body is "invalid_entry: title: unique"
When the client sends PUT /v1/content-type/recipe/entry/7 with the same title "Pad thai" and a new servings
Then the response status is 200
Scenario: Unique values are scoped to their content type and ignore nulls
Given a content type "dish" with a unique text field "title" and an entry titled "Pad thai"
And the content type "recipe" has an entry titled "Pad thai"
Then both entries exist
And two entries of a type with an optional unique field both leaving it absent are accepted
Scenario: Getting an entry
Given the entry 7 of type "recipe"
When the client sends GET /v1/content-type/recipe/entry/7
Then the response status is 200 and the body is the entry
When the client sends GET /v1/content-type/dish/entry/7
Then the response status is 404 and the body is entry_not_found
Scenario Outline: Entry routes with a bad id or a missing resource
Given a valid jwt cookie
When the client sends <method> <path> <body>
Then the response status is <status>
And the response body is <message>
Examples:
| method | path | body | status | message |
| GET | /v1/content-type/recipe/entry/abc | | 400 | apperr.IdUint32ErrorMessage |
| GET | /v1/content-type/recipe/entry/-1 | | 400 | apperr.IdUint32ErrorMessage |
| GET | /v1/content-type/recipe/entry/4294967296 | | 400 | apperr.IdUint32ErrorMessage |
| GET | /v1/content-type/recipe/entry/999 | | 404 | entry_not_found |
| PUT | /v1/content-type/recipe/entry/999 | and a valid data body | 404 | entry_not_found |
| DELETE | /v1/content-type/recipe/entry/999 | | 404 | entry_not_found |
| GET | /v1/content-type/nope/entry/1 | | 404 | content_type_not_found |
| POST | /v1/content-type/nope/entry | and a valid data body | 404 | content_type_not_found |
| GET | /v1/content-type/nope/entry | | 404 | content_type_not_found |
Scenario: Replacing an entry validates the whole document and keeps provenance
Given the entry 7 of type "recipe" created by admin 2, and a valid jwt cookie for owner 1
When owner 1 sends PUT /v1/content-type/recipe/entry/7 with {"data": {"title": "Green curry", "difficulty": "medium"}}
Then the response status is 200
And data is exactly {"title": "Green curry", "difficulty": "medium"} with no default applied
And created_by is 2 and updated_by is 1 and updated_at is later than created_at
When owner 1 sends PUT with {"data": {"difficulty": "medium"}}
Then the response status is 422 with invalid_entry: title: required and the entry is unchanged
Scenario: Deleting an entry
Given the entry 7 of type "recipe"
When the client sends DELETE /v1/content-type/recipe/entry/7
Then the response status is 204 and the body is empty
And GET on entry 7 returns 404 with entry_not_found
Scenario Outline: Listing entries is paginated and sortable
Given 30 entries of type "recipe", and entries of type "dish" that must not appear
When the client sends GET /v1/content-type/recipe/entry<query>
Then the response status is <status>
And <result>
Examples:
| query | status | result |
| | 200 | items has 25 entries, total 30, page 1, size 25, ordered updated_at desc |
| ?page=2 | 200 | items has 5 entries, total 30, page 2, size 25 |
| ?size=5&page=2 | 200 | items has 5 entries, page 2, size 5 |
| ?sort=id:asc | 200 | items ordered by id ascending |
| ?sort=created_at:desc | 200 | items ordered by created_at descending |
| ?page=99 | 200 | items is [] and total is 30 |
| ?page=0 | 400 | apperr.BodyErrorMessage |
| ?size=7 | 400 | apperr.BodyErrorMessage |
| ?sort=data:asc | 400 | apperr.BodyErrorMessage |
| ?page=abc | 400 | apperr.BodyErrorMessage |
Scenario: An empty content type lists no entries
Given the content type "event" with no entries
When the client sends GET /v1/content-type/event/entry
Then the body is {"items": [], "total": 0, "page": 1, "size": 25} and items is a JSON array, not null
Scenario Outline: Entry routes accept any verified user and API keys, and refuse everyone else
Given the content type "recipe" exists
When <caller> sends POST /v1/content-type/recipe/entry with a valid body
Then the response status is <status>
Examples:
| caller | status |
| an admin cookie | 201 |
| an owner cookie | 201 |
| an active API key of admin 2 | 201 |
| no credentials | 401 |
| a cookie for unverified 4 | 403 |
| a stale token_version cookie | 401 |
Scenario: Built-in resources are not reachable through the generic engine
Given a valid jwt cookie for admin 2
When the client creates a content type with the key "article" and sends GET /v1/content-type/article/entry
Then the routes behave as for any custom type and GET /v1/article is unchanged
And no article, author, site, media or user is read or written by the engine
Scenario: Use case: validating an entry against a schema returns domain sentinels
Given a fake contenttype.Repository holding "recipe" and a fake entry.Repository
When CreateEntry is called with data breaking each rule in the table above
Then errors.Is(err, entry.ErrInvalidEntry) is true for each, and the repository received no Create
And a duplicate unique value returns an error satisfying errors.Is(err, entry.ErrUniqueViolation)
Scenario: Use case: schema updates re-validate stored entries
Given a fake entry.Repository holding entries and a fake contenttype.Repository
When UpdateContentType is called with a schema that an existing entry violates
Then it returns contenttype.ErrSchemaIncompatible and the repository Update is not called
And a type change returns contenttype.ErrInvalidField
And DeleteContentType with entries returns contenttype.ErrHasEntries and nothing is deleted
+100
View File
@@ -0,0 +1,100 @@
# QA procedure: custom content types (backend core)
Package: `test` (black-box). No live server, no real SQLite file, no real SMTP.
## Setup shared by every case
1. Call `validator.InitValidator()` once per test.
2. Add in-memory fakes with unique type names across the package: `mockContentTypeRepo`
(implements `contenttype.Repository`, `failNext("Update")` style switch) and `mockEntryRepo` (implements `entry.Repository`, with
`CountByContentType`; `FindByFieldValue` compares decoded
JSON values in Go; ordering, paging and per-type scoping implemented like the real contract; an
`createCalls` counter). Reuse `mockUserRepo`, `stubHasher` and the API key fakes.
3. Build the handler stack from a `*api.UseCases` container holding fakes and mount
`api.InitBackendRoutes(container, settings)` on a test server (unused use cases stay nil). If a nil
use case breaks a constructor, fall back to a fresh `chi.NewRouter()` mirroring the new
content type router: `jwtauth.Verifier`, key middleware, `RequireSignedIn`, `jwtauth.Authenticator`,
`RequireCurrentToken`, `RequireVerifiedUser`, with `RequireOwnerOrAdmin` on POST/PUT/DELETE
`/content-type`. Token: `jwtauth.New("HS256", []byte("test-secret"), nil)`.
4. Inject a fake clock (`now func() time.Time`) into the use cases so `updated_at` > `created_at`.
5. Seed users: owner 1 "marta", admin 2 "dev" (verified), unverified 4 "quinn". Helpers: `cookieFor(userId,
tokenVersion)`, `bearer(raw)`; create the API key through `POST /v1/api-key`.
6. Helper `sampleRecipe()` builds the "recipe" request body from the feature's table.
## Content type create and validation
7. Admin 2 `POST /v1/content-type` with the recipe -> `201`; key set is exactly `id`, `key`, `name`, `icon`,
`fields`, `created_at`, `updated_at`; each field has exactly `key`, `label`, `type`, `required`,
`unique`, `default`, `min`, `max`, `options`; order preserved; `default`/`min`/`max` are JSON `null`
and `options` is `[]` when unset.
8. Invalid-body table (feature table): each case asserts status, exact body (or contains for
validator text), and that `mockContentTypeRepo` is empty. Cover not-json, `{}`, bad key (`Recipe!`,
1 char, 41 chars), empty name, 0 fields, 51 fields, bad/duplicate/overlong field keys, unknown type,
every min/max/options/unique/default rule violation.
9. Duplicate key -> `409` `content_type_key_taken`, one type stored.
10. Access table: no credentials `401`, user 4 `403` `apperr.VerificationRequiredErrorMessage`, stale
token_version `401`, API key of admin 2 `201`. Failures leave the repository empty.
## Content type read, update, delete
11. List returns an array ordered by name; `GET /{key}` returns the type; unknown or malformed key -> `404`
`content_type_not_found`; same for PUT and DELETE.
12. Update with no entries: name, order, removal and type change accepted (`200`); body key in the PUT is
ignored and the key stays.
13. Update with entries (table): type change `422 invalid_field`; new required without default `409
schema_incompatible`; new required with default `200`; new optional `200`; remove field `200`; remove
an option in use `409`; remove an unused option `200`; lower max below a stored value `409`; label,
order, name `200`. On every `409`/`422`, assert the stored schema is byte-identical to before
(`failNext` not used, compare the fake's stored type).
14. Make a field unique while two stored entries collide -> `409 schema_incompatible`, unchanged.
15. Removed field values are not returned on GET, and are absent from the stored document after the next
PUT of that entry.
16. Delete without entries -> `204` empty body, then `404`. Delete with entries -> `409
content_type_has_entries`, type and entries intact.
17. Repository failure on Update/Delete -> `500` "Internal server error", state unchanged.
## Entries
18. Create with defaults: response key set exactly `id`, `content_type`, `data`, `created_by`,
`updated_by`, `created_at`, `updated_at`; `data` equals `{"title","difficulty","servings":4,
"vegetarian":false}`; no `published_on`/`notes` key; `created_by` = `updated_by` = 2.
19. Explicit value beats default; explicit `null` is kept and no default is applied to it.
20. Invalid-data table (feature table, include 400s: not-json, `{}`, non-object `data`): assert status,
exact body, and `createCalls == 0`. Include the date cases `2026-02-30` and a datetime string, a
string number `"4"`, and an unknown field `colour`.
21. Boundaries: title of exactly 3 and 80 runes (use a multibyte string to pin rune counting), servings 1
and 50, notes 500 runes -> `201`; one beyond each -> `422`.
22. Unique: second entry with the same title -> `409` body `invalid_entry: title: unique`; PUT on the
same entry with its own title -> `200`; same title in another type -> `201`; two entries both
omitting an optional unique field -> `201`.
23. GET: entry of another type's key -> `404` `entry_not_found`; unknown type -> `404`
`content_type_not_found`; ids `abc`, `-1`, `4294967296` -> `400` `apperr.IdUint32ErrorMessage`.
24. PUT replaces data wholesale: no defaults re-applied; `created_by` unchanged, `updated_by` = caller,
`updated_at` > `created_at`; invalid replacement -> `422` and the stored entry unchanged.
25. DELETE -> `204`, empty body, then `404`; unknown id `404 entry_not_found`.
26. List: seed 30 recipes and some dishes; default page (25 items, total 30, page 1, size 25,
`updated_at:desc`), `?page=2`, `?size=5&page=2`, `?sort=id:asc`, `?sort=created_at:desc`, `?page=99`
(`items: []`, total 30). Bad `page=0`, `size=7`, `sort=data:asc`, `page=abc` -> `400`
`apperr.BodyErrorMessage`. Empty type -> `items` is `[]` (assert JSON `[]`, not `null`).
27. Access table on entry routes: admin, owner, API key -> `201`; none `401`; user 4 `403`; stale `401`.
A non-admin verified caller can read and write entries but not content types (only if a
non-owner/non-admin role exists in the fake; otherwise skip and note it).
28. Isolation: creating a type keyed `article` does not affect `GET /v1/article`; no built-in repository
fake is called by any case in this file.
## Use case level (no HTTP)
29. `CreateEntry`/`UpdateEntry` against `mockContentTypeRepo` + `mockEntryRepo`: each rule breach ->
`errors.Is(err, entry.ErrInvalidEntry)` and no write; duplicate -> `entry.ErrUniqueViolation`.
30. `UpdateContentType`: incompatible stored entry -> `contenttype.ErrSchemaIncompatible` and no `Update`
call; type change -> `ErrInvalidField`; `DeleteContentType` with entries ->
`ErrHasEntries`; unknown key -> `ErrContentTypeNotFound`; taken key -> `ErrKeyTaken`.
31. Schema validator unit table: every row of the "invalid body" table asserted on the domain function
directly with `errors.Is(err, contenttype.ErrInvalidField)`.
## Manual verification (not exercised by the Go tests)
- Real SQLite, then MySQL/MariaDB and PostgreSQL via the existing driver tasks: start `task dev:api`,
confirm `AutoMigrate` creates the content type and entry tables with the JSON documents in text
columns and no table gets created or altered when a new content type is defined.
- Create a type, restart the server and confirm types and entries persist; create 1,000 entries and
confirm list paging and the unique check stay responsive (the unique check is a portable lookup, not a
DB index).
- Fire two concurrent POSTs with the same unique value and record the outcome (known limitation: the
check is not transactional).
- With curl and an API key, create a type and an entry from a non-browser client and confirm a browser
origin in `CORS_ALLOWED_ORIGINS` can use PUT and DELETE (preflight allows them).
@@ -0,0 +1,235 @@
Feature: Content types carry an optional icon, built-in types are readable, and verified users can resolve user display names
As an owner, admin or verified user working in the SPA
I want an icon per content type, a read-only view of the built-in types and the display names of entry authors
So that the sidebar, the Schema screen and the entry screens can be drawn without leaking account data
Background:
Given the existing content type contract of custom_content_types.feature is unchanged except
that a content type response now has exactly the keys id, key, name, icon, fields, created_at,
updated_at
And a content type icon is null or a string matching ^[a-z][a-z0-9-]{0,39}$ and it is never
checked against a list of known icons
And internal/domain/contenttype defines the sentinel ErrInvalidIcon and the apperr string is
invalid_icon
And the icon is stored in a nullable column added by AutoMigrate, so existing rows read as null,
and the fields column stays a JSON text column
And an empty icon "" is stored as null
And a PUT replaces the icon like it replaces the name and the fields, so an absent icon clears it
And internal/domain/builtintype defines the static catalogue of the built-in types article,
author, site, media and user, in this order, each with a name and a list of fields shaped like
a content type field (key, label, type, required, unique, default, min, max, options)
And the catalogue uses no repository and no database, and the use cases ListBuiltinTypes and
GetBuiltinType depend only on that package
And the routes GET /v1/builtin-type and GET /v1/builtin-type/{key} are mounted in a router with
jwtauth.Verifier, apiKeyAuth, AuditContext, RequireSignedIn, jwtauth.Authenticator,
RequireCurrentToken, RequireVerifiedUser and RequireOwnerOrAdmin
And a built-in type response has exactly the keys key, name, fields
And the new apperr string is builtin_type_not_found
And the route GET /v1/user/lookup is mounted on the existing user router behind the verified
user chain with no role requirement
And a lookup item has exactly the keys id and display_name
And users: owner id 1 "marta" with display name "Marta Alves", admin id 2 "dev" with no
display name, verified id 3 "sam" with display name "Sam Roy", unverified id 4 "quinn"
And only the roles owner and admin exist, so every verified user passes RequireOwnerOrAdmin
And errors are plain text from http.Error
Scenario: Creating a content type with an icon
Given a valid jwt cookie for admin 2
When the client sends POST /v1/content-type with the recipe body and "icon": "chef-hat"
Then the response status is 201
And the body has exactly the keys id, key, name, icon, fields, created_at, updated_at
And icon is "chef-hat"
And GET /v1/content-type/recipe and GET /v1/content-type both show icon "chef-hat"
Scenario Outline: A content type without an icon has a null icon
Given a valid jwt cookie for admin 2
When the client creates "recipe" with <icon>
Then the response status is 201 and icon is null in the response, in GET /v1/content-type/recipe and in the list
Examples:
| icon |
| no icon key |
| "icon": null |
| "icon": "" |
Scenario: A content type stored before this slice still works
Given the content type "recipe" was stored with no icon value
When a verified user sends GET /v1/content-type and GET /v1/content-type/recipe
Then the response status is 200 and icon is null and all other keys are unchanged
Scenario Outline: An invalid icon is refused and stores nothing
Given a valid jwt cookie for admin 2
When the client sends POST /v1/content-type with a valid body and "icon": <icon>
Then the response status is 400
And the response body is invalid_icon
And no content type exists in the repository
Examples:
| icon |
| "Chef-Hat" |
| "1star" |
| "-star" |
| "chef hat" |
| "chef_hat" |
| "<41 characters>" |
| 5 |
Scenario: Boundary icons are accepted
Given a valid jwt cookie for admin 2
When the client creates types with the icons "a" and a 40 character icon "a" followed by 39 "b"
Then each response status is 201
Scenario Outline: Updating the icon of a content type
Given the content type "recipe" exists with the icon "chef-hat" and has an entry
When admin 2 sends PUT /v1/content-type/recipe with the same fields and <icon>
Then the response status is <status>
And <outcome>
Examples:
| icon | status | outcome |
| "icon": "utensils" | 200 | icon is "utensils" |
| no icon key | 200 | icon is null |
| "icon": null | 200 | icon is null |
| "icon": "Bad Icon" | 400 | the body is invalid_icon and the icon is still "chef-hat" |
Scenario: The icon does not affect entries
Given the content type "recipe" has an entry and admin 2 changes only the icon
Then the response status is 200 and the entry data and its updated_at are unchanged
Scenario: Listing the built-in types
Given a valid jwt cookie for owner 1
When the client sends GET /v1/builtin-type
Then the response status is 200
And the body is a JSON array of 5 items with the keys article, author, site, media, user in this order
And each item has exactly the keys key, name, fields
And the names are "Articles", "Authors", "Sites", "Media" and "Users"
And every field has exactly the keys key, label, type, required, unique, default, min, max, options
And every field type is one of text, richtext, number, boolean, date, select
Scenario Outline: The built-in field lists match the real API
Given a valid jwt cookie for admin 2
When the client sends GET /v1/builtin-type/<key>
Then the response status is 200
And the field keys, in order, are <fields>
And no field key is one of id, created_at, updated_at, password, password_reset_code, verification_code, token_version
Examples:
| key | fields |
| article | title, body, slug, excerpt, seo_title, seo_description, is_online, canonical_url, noindex |
| author | name, slug, bio, website |
| site | name, key, base_url, default_robots, locale, is_default, site_name, title_template, default_description |
| media | filename, size, width, height, content_type |
| user | username, display_name, email, role |
Scenario Outline: Selected built-in field rules
Given a valid jwt cookie for admin 2
When the client sends GET /v1/builtin-type/<key>
Then the field <field> has type <type>, required <required>, min <min>, max <max> and options <options>
Examples:
| key | field | type | required | min | max | options |
| article | title | text | true | 3 | 200 | [] |
| article | body | richtext | false | null | null | [] |
| article | excerpt | text | false | null | 300 | [] |
| article | is_online | boolean | false | null | null | [] |
| site | default_robots | select | false | null | null | index, noindex |
| site | site_name | text | false | null | 100 | [] |
| site | title_template | text | false | null | 200 | [] |
| site | default_description | text | false | null | 320 | [] |
| user | role | select | true | null | null | owner, admin |
| user | email | text | true | null | null | [] |
Scenario: Reading one built-in type does not collide with a custom type of the same key
Given the custom content type "builtin" exists, and a custom content type "article" exists
And a valid jwt cookie for admin 2
When the client sends GET /v1/content-type/builtin and GET /v1/content-type/article
Then each response is the custom content type
When the client sends GET /v1/builtin-type/article
Then the response is the built-in article type
And GET /v1/content-type never lists a built-in type
Scenario Outline: The built-in routes are read-only and restricted
Given <caller>
When the client sends <method> <path>
Then the response status is <status>
And the response body is <message>
Examples:
| caller | method | path | status | message |
| owner 1 cookie | GET | /v1/builtin-type | 200 | |
| admin 2 cookie | GET | /v1/builtin-type/user | 200 | |
| an active API key of admin 2 | GET | /v1/builtin-type | 200 | |
| a cookie for unverified 4 | GET | /v1/builtin-type | 403 | apperr.VerificationRequiredErrorMessage |
| no credentials | GET | /v1/builtin-type | 401 | the existing Authenticator response |
| a stale token_version cookie | GET | /v1/builtin-type | 401 | the existing Authenticator response |
| admin 2 cookie | GET | /v1/builtin-type/nope | 404 | builtin_type_not_found |
| admin 2 cookie | GET | /v1/builtin-type/Article | 404 | builtin_type_not_found |
| admin 2 cookie | POST | /v1/builtin-type | 405 | empty |
| admin 2 cookie | PUT | /v1/builtin-type/article | 405 | empty |
| admin 2 cookie | DELETE | /v1/builtin-type/article | 405 | empty |
Scenario: Reading the built-in types never touches data
Given fake repositories for content types, entries, articles, authors, sites, media and users
When the client sends GET /v1/builtin-type and GET /v1/builtin-type/site
Then no repository method is called
Scenario: Any verified user resolves display names
Given a valid jwt cookie for verified user 3
When the client sends GET /v1/user/lookup?ids=1,2,3
Then the response status is 200
And the body is a JSON array of 3 items ordered by id
And each item has exactly the keys id and display_name
And the display names are "Marta Alves", "dev" (the username, because the display name is empty) and "Sam Roy"
And the body contains no email, role, username or status
Scenario Outline: Lookup edge cases
Given a valid jwt cookie for verified user 3
When the client sends GET /v1/user/lookup<query>
Then the response status is <status>
And the response body is <message>
Examples:
| query | status | message |
| ?ids=2,2,2 | 200 | an array with one item for id 2 |
| ?ids=1,999 | 200 | an array with only id 1 |
| ?ids=999 | 200 | [] |
| ?ids=4 | 200 | an array with the item for id 4 |
| (no query) | 400 | apperr.BodyErrorMessage |
| ?ids= | 400 | apperr.BodyErrorMessage |
| ?ids=abc | 400 | apperr.BodyErrorMessage |
| ?ids=1,-2 | 400 | apperr.BodyErrorMessage |
| ?ids=1,4294967296 | 400 | apperr.BodyErrorMessage |
| ?ids=1,,2 | 400 | apperr.BodyErrorMessage |
| 101 distinct ids | 400 | apperr.BodyErrorMessage |
| exactly 100 ids | 200 | an array of the existing users |
Scenario Outline: Lookup needs a verified signed-in user or an API key
Given <caller>
When the client sends GET /v1/user/lookup?ids=1
Then the response status is <status>
Examples:
| caller | status |
| a cookie for verified user 3 | 200 |
| an active API key of admin 2 | 200 |
| no credentials | 401 |
| a cookie for unverified 4 | 403 |
| a stale token_version cookie | 401 |
Scenario: Existing user and entry responses are unchanged
Given a valid jwt cookie for verified user 3
When the client sends GET /v1/user/ and GET /v1/content-type/recipe/entry
Then the responses keep their existing shapes, and created_by and updated_by stay numeric ids
Scenario: Use case: the icon rule returns a domain sentinel
Given a fake contenttype.Repository
When CreateContentType and UpdateContentType are called with each invalid icon of the table above
Then errors.Is(err, contenttype.ErrInvalidIcon) is true and the repository received no Create or Update
Scenario: Use case: the catalogue and the lookup
Given the builtintype package and a fake user.Repository
When ListBuiltinTypes and GetBuiltinType("nope") are called
Then the list has 5 types and the unknown key returns builtintype.ErrNotFound
When LookupUserNames is called with ids 1, 2, 999
Then it returns the display name for 1, the username for 2, and nothing for 999
@@ -0,0 +1,91 @@
# QA procedure: custom content types support (icon, built-in read model, user lookup)
Package: `test` (black-box). No live server, no real SQLite file, no real SMTP.
## Setup shared by every case
1. Call `validator.InitValidator()` once per test.
2. Reuse the existing fakes `mockContentTypeRepo`, `mockEntryRepo`, `mockUserRepo`, `stubHasher` and the API key
fakes from the custom content types tests. Extend `mockUserRepo` with the batch lookup by ids (unknown ids
skipped). Add a counting wrapper (`countingRepos`) that records any call on the article, author, site,
media, user, content type and entry fakes, with a unique type name across the package.
3. Build the `*api.UseCases` container with fakes and mount `api.InitBackendRoutes(container, settings)` on a
test server. If a nil use case breaks a constructor, fall back to a fresh `chi.NewRouter()` mirroring
`NewContentTypeRouter`, a new `NewBuiltinTypeRouter` (same chain plus `RequireOwnerOrAdmin`) and the user
router, with `jwtauth.New("HS256", []byte("test-secret"), nil)`.
4. Inject a fake clock into the use cases.
5. Seed users: owner 1 "marta" (display name "Marta Alves"), admin 2 "dev" (empty display name), verified
id 3 "sam" ("Sam Roy"), unverified 4 "quinn". Only the roles owner and admin exist, so no verified user is
rejected by `RequireOwnerOrAdmin`. Helpers: `cookieFor(userId, tokenVersion)`, `bearer(raw)`; the API key
through `POST /v1/api-key`.
6. Reuse `sampleRecipe()`; add `withIcon(body, value)` that sets, omits or nulls the icon key.
## Icon
7. Create with `"icon": "chef-hat"` -> 201; key set is exactly `id`, `key`, `name`, `icon`, `fields`, `created_at`,
`updated_at`; the icon is also present in `GET /{key}` and in the list. Update the existing pair's
"exactly the keys" wording and its QA step 7 accordingly.
8. Create with the key absent, `null` and `""` -> 201 and `icon` is JSON `null` in all three reads (assert the
raw JSON `null`, not a missing key and not `""`).
9. Legacy row: seed `mockContentTypeRepo` with a type that has no icon set; GET list and GET one -> 200, `icon`
null, other keys unchanged.
10. Invalid icons (`Chef-Hat`, `1star`, `-star`, `chef hat`, `chef_hat`, 41 characters, JSON number `5`) ->
400 `invalid_icon`, repository empty. 1 and 40 character icons -> 201.
11. PUT on a type that has an entry: new icon -> 200; absent -> 200 and null; `null` -> 200 and null; invalid ->
400 `invalid_icon` and the stored icon is unchanged. The stored entry and its `updated_at` are unchanged in
every case.
12. Use case level: `CreateContentType` / `UpdateContentType` with each invalid icon ->
`errors.Is(err, contenttype.ErrInvalidIcon)`, no `Create`/`Update` call on the fake. Domain table test of the
icon rule on the function directly.
13. Persistence mapper round trip (unit, no GORM): icon nil and non-nil survive the model/domain conversion in
both directions. The repository `Update` select list must include the icon (verified in the manual section
against the real DB).
## Built-in types
14. Owner `GET /v1/builtin-type` -> 200, array of 5, keys `article`, `author`, `site`, `media`, `user` in order,
names `Articles`, `Authors`, `Sites`, `Media`, `Users`; each item has exactly `key`, `name`, `fields`; each
field has exactly the nine field keys; every type is one of the six engine types.
15. Field-key table (feature table): per type, the ordered field keys; assert none of the forbidden keys
(`id`, `created_at`, `updated_at`, `password`, `password_reset_code`, `verification_code`, `token_version`)
appears in any type.
16. Rules table (feature table): spot-check type, required, min, max and options for the listed fields, with
`default`/`min`/`max` as JSON `null` and `options` as `[]` when unset. Rule values come from the request
structs; where a rule is not stated there (author bio max, media filename), leave min/max null.
17. Cross-check against the real contracts so the catalogue can't drift: for each built-in type, the JSON object
keys of the domain struct (via `json.Marshal` of the entity: `article.Article`, `author.Author`, `site.Site`,
`image.Image`, `user.User`) must contain every catalogue field key, using the json tags. Fail the test if a
catalogue key does not exist in the entity JSON.
18. `GET /v1/builtin-type/{key}` for each key -> 200 with the same item as in the list; `nope` and `Article` ->
404 `builtin_type_not_found`.
19. Collision: seed custom types `builtin` and `article`; `GET /v1/content-type/builtin` and `/article` return the
custom types; `GET /v1/content-type` lists only the custom ones; `GET /v1/builtin-type/article` returns the
built-in one.
20. Access table: owner 200, admin 200, API key of admin 200, user 4 403 `apperr.VerificationRequiredErrorMessage`,
none 401, stale 401. POST/PUT/DELETE on `/v1/builtin-type` and `/v1/builtin-type/article` -> 405 for admin.
(A verified non-owner non-admin 403 cannot be tested: no such role exists.)
21. Isolation: with the counting wrapper, calling the list and `GET /site` leaves every repository call count at
zero.
22. Use case level: `ListBuiltinTypes` returns 5 types; `GetBuiltinType("nope")` returns `builtintype.ErrNotFound`.
## User lookup
23. As verified user 3, `GET /v1/user/lookup?ids=1,2,3` -> 200; array ordered by id; each item has exactly `id`
and `display_name`; names `Marta Alves`, `dev`, `Sam Roy`; raw body contains none of `email`, `role`,
`username`, `status`, `password`.
24. Edge table (feature table): duplicates collapse, unknown ids are omitted, all-unknown -> `[]` (assert JSON
`[]` not `null`), unverified id 4 still resolves, missing/empty/non-numeric/negative/overflow/`1,,2`/101 ids
-> 400 `apperr.BodyErrorMessage`, exactly 100 ids -> 200.
25. Access table: verified user 3 200, API key of admin 2 200, none 401, user 4 403, stale token_version 401.
26. Regression: `GET /v1/user/` and entry responses are unchanged (same keys as before, `created_by`/`updated_by`
numeric).
27. Use case level: `LookupUserNames` with a fake `user.Repository` returns display name, falls back to the
username when it is empty, omits unknown ids, and makes a single batch call on the fake (no per-id lookups).
## Manual verification (not exercised by the Go tests)
- Start `task dev:api` on an existing database that already has content types: confirm AutoMigrate adds the
nullable icon column, old types read `icon: null`, and nothing else changes. Repeat on MySQL/MariaDB and
PostgreSQL via the existing driver tasks.
- Change an icon through PUT against the real SQLite file and reload: confirms the repository `Update` select
list includes the icon (the mapper test cannot).
- Compare `GET /v1/builtin-type/<key>` field rules with the real `POST`/`PATCH` validation of each resource once
(for example create a site with a 101 character `site_name`, expect a 400) to confirm that the stated max
values are honest.
- Request `GET /v1/user/lookup` in a browser session as a non-admin and confirm no email or role appears in the
network response.
@@ -0,0 +1,141 @@
package builtintype
import (
"RenewCMS/internal/domain/article"
"RenewCMS/internal/domain/contenttype"
"RenewCMS/internal/domain/user"
"errors"
)
var ErrNotFound = errors.New("built-in type not found")
const (
KeyArticle = "article"
KeyAuthor = "author"
KeySite = "site"
KeyMedia = "media"
KeyUser = "user"
)
type Type struct {
Key string `json:"key"`
Name string `json:"name"`
Fields []contenttype.Field `json:"fields"`
}
func Catalogue() []Type {
return []Type{
{Key: KeyArticle, Name: "Articles", Fields: articleFields()},
{Key: KeyAuthor, Name: "Authors", Fields: authorFields()},
{Key: KeySite, Name: "Sites", Fields: siteFields()},
{Key: KeyMedia, Name: "Media", Fields: mediaFields()},
{Key: KeyUser, Name: "Users", Fields: userFields()},
}
}
func Find(key string) (Type, error) {
for _, candidate := range Catalogue() {
if candidate.Key == key {
return candidate, nil
}
}
return Type{}, ErrNotFound
}
func field(key string, label string, fieldType contenttype.FieldType) contenttype.Field {
return contenttype.Field{Key: key, Label: label, Type: fieldType, Options: []string{}}
}
func (b builder) required() builder {
b.Required = true
return b
}
func (b builder) min(bound int) builder {
b.Min = bound
return b
}
func (b builder) max(bound int) builder {
b.Max = bound
return b
}
func (b builder) options(options ...string) builder {
b.Options = options
return b
}
type builder contenttype.Field
func text(key string, label string) builder {
return builder(field(key, label, contenttype.TypeText))
}
func of(key string, label string, fieldType contenttype.FieldType) builder {
return builder(field(key, label, fieldType))
}
func build(builders ...builder) []contenttype.Field {
fields := make([]contenttype.Field, 0, len(builders))
for _, b := range builders {
fields = append(fields, contenttype.Field(b))
}
return fields
}
func articleFields() []contenttype.Field {
return build(
text("title", "Title").required().min(article.MinTitleRunes).max(article.MaxTitleRunes),
of("body", "Body", contenttype.TypeRichText),
text("slug", "Slug"),
text("excerpt", "Excerpt").max(300),
text("seo_title", "SEO title").max(120),
text("seo_description", "SEO description").max(320),
of("is_online", "Online", contenttype.TypeBoolean),
text("canonical_url", "Canonical URL").max(article.MaxCanonicalURLRunes),
of("noindex", "No index", contenttype.TypeBoolean),
)
}
func authorFields() []contenttype.Field {
return build(
text("name", "Name").required(),
text("slug", "Slug"),
text("bio", "Bio"),
text("website", "Website"),
)
}
func siteFields() []contenttype.Field {
return build(
text("name", "Name").required(),
text("key", "Key").required(),
text("base_url", "Base URL").required(),
of("default_robots", "Default robots", contenttype.TypeSelect).options("index", "noindex"),
text("locale", "Locale"),
of("is_default", "Default site", contenttype.TypeBoolean),
text("site_name", "Site name").max(100),
text("title_template", "Title template").max(200),
text("default_description", "Default description").max(320),
)
}
func mediaFields() []contenttype.Field {
return build(
text("filename", "Filename"),
of("size", "Size", contenttype.TypeNumber),
of("width", "Width", contenttype.TypeNumber),
of("height", "Height", contenttype.TypeNumber),
text("content_type", "Content type"),
)
}
func userFields() []contenttype.Field {
return build(
text("username", "Username").required(),
text("display_name", "Display name"),
text("email", "Email").required(),
of("role", "Role", contenttype.TypeSelect).required().options(string(user.RoleOwner), string(user.RoleAdmin)),
)
}
@@ -0,0 +1,66 @@
package contenttype
import (
"errors"
"time"
)
var (
ErrContentTypeNotFound = errors.New("content type not found")
ErrKeyTaken = errors.New("a content type with that key already exists")
ErrInvalidName = errors.New("invalid content type name")
ErrInvalidKey = errors.New("invalid content type key")
ErrInvalidIcon = errors.New("invalid content type icon")
ErrInvalidField = errors.New("invalid field")
ErrHasEntries = errors.New("the content type still has entries")
ErrSchemaIncompatible = errors.New("the schema is incompatible with the stored entries")
)
type FieldType string
const (
TypeText FieldType = "text"
TypeRichText FieldType = "richtext"
TypeNumber FieldType = "number"
TypeBoolean FieldType = "boolean"
TypeDate FieldType = "date"
TypeSelect FieldType = "select"
)
const (
RuleType = "type"
RuleMin = "min"
RuleMax = "max"
RuleOptions = "options"
)
const (
MinKeyRunes = 2
MaxKeyRunes = 40
MaxNameRunes = 100
MinFields = 1
MaxFields = 50
DateLayout = "2006-01-02"
)
type Field struct {
Key string `json:"key"`
Label string `json:"label"`
Type FieldType `json:"type"`
Required bool `json:"required"`
Unique bool `json:"unique"`
Default any `json:"default"`
Min any `json:"min"`
Max any `json:"max"`
Options []string `json:"options"`
}
type ContentType struct {
ID uint32 `json:"id"`
Key string `json:"key"`
Name string `json:"name"`
Icon *string `json:"icon"`
Fields []Field `json:"fields"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
@@ -0,0 +1,9 @@
package contenttype
type Repository interface {
Create(contentType ContentType) (ContentType, error)
GetByKey(key string) (ContentType, error)
List() ([]ContentType, error)
Update(contentType ContentType) (ContentType, error)
Delete(id uint32) error
}
+80
View File
@@ -0,0 +1,80 @@
package contenttype
import (
"math"
"time"
"unicode/utf8"
)
type kind struct {
accepts func(value any) bool
measure func(value any) (float64, bool)
bound func(bound any) (float64, bool)
unique bool
}
var kinds = map[FieldType]kind{
TypeText: {accepts: isString, measure: runeCount, bound: wholeLength, unique: true},
TypeRichText: {accepts: isString, measure: runeCount, bound: wholeLength},
TypeNumber: {accepts: isNumber, measure: asNumber, bound: asNumber, unique: true},
TypeBoolean: {accepts: isBoolean},
TypeDate: {accepts: isDate, measure: dateDays, bound: dateDays, unique: true},
TypeSelect: {accepts: isString, unique: true},
}
func isString(value any) bool {
_, ok := value.(string)
return ok
}
func isBoolean(value any) bool {
_, ok := value.(bool)
return ok
}
func isNumber(value any) bool {
_, ok := asNumber(value)
return ok
}
func isDate(value any) bool {
_, ok := dateDays(value)
return ok
}
func runeCount(value any) (float64, bool) {
text, ok := value.(string)
return float64(utf8.RuneCountInString(text)), ok
}
func wholeLength(bound any) (float64, bool) {
number, ok := asNumber(bound)
return number, ok && number >= 0 && number == math.Trunc(number)
}
func asNumber(value any) (float64, bool) {
var number float64
switch typed := value.(type) {
case float64:
number = typed
case int:
number = float64(typed)
case int64:
number = float64(typed)
default:
return 0, false
}
return number, !math.IsNaN(number) && !math.IsInf(number, 0)
}
func dateDays(value any) (float64, bool) {
text, ok := value.(string)
if !ok {
return 0, false
}
parsed, err := time.Parse(DateLayout, text)
if err != nil || parsed.Format(DateLayout) != text {
return 0, false
}
return float64(parsed.Unix()), true
}
+113
View File
@@ -0,0 +1,113 @@
package contenttype
import (
"RenewCMS/internal/domain/slug"
"regexp"
"strings"
"unicode/utf8"
)
var iconPattern = regexp.MustCompile(`^[a-z][a-z0-9-]{0,39}$`)
var fieldKeyPattern = regexp.MustCompile(`^[a-z][a-z0-9_]{0,39}$`)
func ValidateKey(key string) error {
length := utf8.RuneCountInString(key)
if length < MinKeyRunes || length > MaxKeyRunes || !slug.IsValid(key) {
return ErrInvalidKey
}
return nil
}
func ValidateName(name string) error {
if strings.TrimSpace(name) == "" || utf8.RuneCountInString(name) > MaxNameRunes {
return ErrInvalidName
}
return nil
}
func ValidateIcon(icon *string) (*string, error) {
if icon == nil || *icon == "" {
return nil, nil
}
if !iconPattern.MatchString(*icon) {
return nil, ErrInvalidIcon
}
return icon, nil
}
func ValidateFields(fields []Field) ([]Field, error) {
if len(fields) < MinFields || len(fields) > MaxFields {
return nil, ErrInvalidField
}
seen := make(map[string]bool, len(fields))
normalized := make([]Field, 0, len(fields))
for _, field := range fields {
if seen[field.Key] || !field.validSchema() {
return nil, ErrInvalidField
}
seen[field.Key] = true
if field.Options == nil {
field.Options = []string{}
}
normalized = append(normalized, field)
}
return normalized, nil
}
func (f Field) validSchema() bool {
fieldKind, known := kinds[f.Type]
if !known || !fieldKeyPattern.MatchString(f.Key) {
return false
}
if f.Unique && !fieldKind.unique {
return false
}
return f.validOptions() && f.validBounds(fieldKind) && f.validDefault()
}
func (f Field) validOptions() bool {
if f.Type != TypeSelect {
return len(f.Options) == 0
}
if len(f.Options) == 0 {
return false
}
seen := make(map[string]bool, len(f.Options))
for _, option := range f.Options {
if option == "" || seen[option] {
return false
}
seen[option] = true
}
return true
}
func (f Field) validBounds(fieldKind kind) bool {
if f.Min == nil && f.Max == nil {
return true
}
if fieldKind.bound == nil {
return false
}
lower, lowerOk := f.optionalBound(fieldKind, f.Min)
upper, upperOk := f.optionalBound(fieldKind, f.Max)
if !lowerOk || !upperOk {
return false
}
return f.Min == nil || f.Max == nil || lower <= upper
}
func (f Field) optionalBound(fieldKind kind, bound any) (float64, bool) {
if bound == nil {
return 0, true
}
return fieldKind.bound(bound)
}
func (f Field) validDefault() bool {
if f.Default == nil {
return true
}
return !f.Unique && f.Violation(f.Default) == ""
}
+41
View File
@@ -0,0 +1,41 @@
package contenttype
import "slices"
func (f Field) Violation(value any) string {
fieldKind, known := kinds[f.Type]
if !known || !fieldKind.accepts(value) {
return RuleType
}
if rule := f.boundViolation(fieldKind, value); rule != "" {
return rule
}
if len(f.Options) > 0 {
text, _ := value.(string)
if !slices.Contains(f.Options, text) {
return RuleOptions
}
}
return ""
}
func (f Field) boundViolation(fieldKind kind, value any) string {
if fieldKind.measure == nil {
return ""
}
measured, _ := fieldKind.measure(value)
if lower, set := f.measuredBound(fieldKind, f.Min); set && measured < lower {
return RuleMin
}
if upper, set := f.measuredBound(fieldKind, f.Max); set && measured > upper {
return RuleMax
}
return ""
}
func (f Field) measuredBound(fieldKind kind, bound any) (float64, bool) {
if bound == nil {
return 0, false
}
return fieldKind.bound(bound)
}
+90
View File
@@ -0,0 +1,90 @@
package entry
import (
"RenewCMS/internal/domain/contenttype"
"reflect"
"sort"
)
func SameValue(left any, right any) bool {
return reflect.DeepEqual(left, right)
}
type UniqueValue struct {
Key string
Value any
}
func ApplyDefaults(fields []contenttype.Field, data map[string]any) map[string]any {
filled := make(map[string]any, len(data))
for key, value := range data {
filled[key] = value
}
for _, field := range fields {
if _, present := filled[field.Key]; !present && field.Default != nil {
filled[field.Key] = field.Default
}
}
return filled
}
func Project(fields []contenttype.Field, data map[string]any) map[string]any {
projected := make(map[string]any, len(data))
for _, field := range fields {
if value, present := data[field.Key]; present {
projected[field.Key] = value
}
}
return projected
}
func Validate(fields []contenttype.Field, data map[string]any) error {
for _, field := range fields {
if err := validateField(field, data); err != nil {
return err
}
}
return firstUnknownField(fields, data)
}
func validateField(field contenttype.Field, data map[string]any) error {
value := data[field.Key]
if value == nil {
if field.Required {
return invalidField(field.Key, RuleRequired)
}
return nil
}
if rule := field.Violation(value); rule != "" {
return invalidField(field.Key, rule)
}
return nil
}
func firstUnknownField(fields []contenttype.Field, data map[string]any) error {
known := make(map[string]bool, len(fields))
for _, field := range fields {
known[field.Key] = true
}
var unknown []string
for key := range data {
if !known[key] {
unknown = append(unknown, key)
}
}
if len(unknown) == 0 {
return nil
}
sort.Strings(unknown)
return invalidField(unknown[0], RuleUnknownField)
}
func UniqueValues(fields []contenttype.Field, data map[string]any) []UniqueValue {
var values []UniqueValue
for _, field := range fields {
if value := data[field.Key]; field.Unique && value != nil {
values = append(values, UniqueValue{Key: field.Key, Value: value})
}
}
return values
}
+64
View File
@@ -0,0 +1,64 @@
package entry
import (
"errors"
"time"
)
var (
ErrEntryNotFound = errors.New("entry not found")
ErrInvalidEntry = errors.New("invalid entry")
ErrUniqueViolation = errors.New("a unique value is already used")
ErrInvalidSort = errors.New("invalid sort")
ErrInvalidPage = errors.New("invalid page")
)
const (
MaxPage = 1000000
MaxPageSize = 100
)
func ValidatePage(page int, size int) error {
if page > MaxPage || size > MaxPageSize {
return ErrInvalidPage
}
return nil
}
const (
RuleRequired = "required"
RuleUnknownField = "unknown_field"
RuleUnique = "unique"
)
type Entry struct {
ID uint32 `json:"id"`
ContentTypeID uint32 `json:"content_type_id"`
Data map[string]any `json:"data"`
CreatedBy uint32 `json:"created_by"`
UpdatedBy uint32 `json:"updated_by"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
type FieldError struct {
Key string
Rule string
Cause error
}
func (e FieldError) Error() string {
return e.Key + ": " + e.Rule
}
func (e FieldError) Unwrap() error {
return e.Cause
}
func invalidField(key string, rule string) error {
return FieldError{Key: key, Rule: rule, Cause: ErrInvalidEntry}
}
func UniqueViolation(key string) error {
return FieldError{Key: key, Rule: RuleUnique, Cause: ErrUniqueViolation}
}
@@ -0,0 +1,71 @@
package entry
import "strings"
type SortField string
type SortDirection string
const (
SortByID SortField = "id"
SortByCreatedAt SortField = "created_at"
SortByUpdatedAt SortField = "updated_at"
SortAsc SortDirection = "asc"
SortDesc SortDirection = "desc"
)
type Sort struct {
Field SortField
Direction SortDirection
}
func (s Sort) Valid() bool {
switch s.Field {
case SortByID, SortByCreatedAt, SortByUpdatedAt:
default:
return false
}
return s.Direction == SortAsc || s.Direction == SortDesc
}
func (s Sort) String() string {
return string(s.Field) + ":" + string(s.Direction)
}
func ParseSort(value string) (Sort, error) {
field, direction, found := strings.Cut(value, ":")
parsed := Sort{Field: SortField(field), Direction: SortDirection(direction)}
if !found || !parsed.Valid() {
return Sort{}, ErrInvalidSort
}
return parsed, nil
}
func DefaultSort() Sort {
return Sort{Field: SortByUpdatedAt, Direction: SortDesc}
}
type Filters struct {
ContentTypeID uint32
Page int
Size int
Sort Sort
Unpaged bool
}
type PageResult struct {
Items []Entry
Total int
}
type Repository interface {
Create(entry Entry) (Entry, error)
Get(contentTypeID uint32, id uint32) (Entry, error)
ListPage(filters Filters) (PageResult, error)
Update(entry Entry) (Entry, error)
Delete(contentTypeID uint32, id uint32) error
DeleteByContentType(contentTypeID uint32) error
CountByContentType(contentTypeID uint32) (int, error)
FindByFieldValue(contentTypeID uint32, fieldKey string, value any, excludeID uint32) ([]Entry, error)
}
+11
View File
@@ -2,6 +2,7 @@ package user
import (
"errors"
"strings"
"time"
)
@@ -15,8 +16,11 @@ var ErrInvalidPasswordResetCode = errors.New("invalid password reset code")
var ErrPasswordResetCodeExpired = errors.New("password reset code expired")
var ErrInvalidDisplayName = errors.New("invalid display name")
var ErrUsernameTaken = errors.New("username taken")
var ErrInvalidLookup = errors.New("invalid user lookup")
var ErrVerificationEmailNotSent = errors.New("verification email not sent")
const MaxLookupIDs = 100
type Role string
const (
@@ -40,3 +44,10 @@ type User struct {
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
func (u User) NameOrUsername() string {
if trimmed := strings.TrimSpace(u.DisplayName); trimmed != "" {
return trimmed
}
return u.Username
}
@@ -7,6 +7,7 @@ type Repository interface {
GetByUsername(username string) (User, error)
GetByEmail(email string) (User, error)
GetAll() []User
FindByIDs(ids []uint32) ([]User, error)
Create(user User) (User, error)
Delete(id uint32) error
UpdateVerificationStatus(userId uint32, isVerified bool) (User, error)
@@ -7,7 +7,7 @@ import (
)
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{})
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{}, &models.ContentType{}, &models.Entry{})
if err != nil {
return err
}
@@ -0,0 +1,39 @@
package mappers
import (
"RenewCMS/internal/domain/contenttype"
"RenewCMS/internal/infrastructure/persistence/models"
"encoding/json"
)
func ContentTypeToDomain(m models.ContentType) (contenttype.ContentType, error) {
var fields []contenttype.Field
if err := json.Unmarshal([]byte(m.Fields), &fields); err != nil {
return contenttype.ContentType{}, err
}
return contenttype.ContentType{
ID: m.ID,
Key: m.Key,
Name: m.Name,
Icon: m.Icon,
Fields: fields,
CreatedAt: m.CreatedAt,
UpdatedAt: m.UpdatedAt,
}, nil
}
func ContentTypeToModel(c contenttype.ContentType) (models.ContentType, error) {
fields, err := json.Marshal(c.Fields)
if err != nil {
return models.ContentType{}, err
}
return models.ContentType{
ID: c.ID,
Key: c.Key,
Name: c.Name,
Icon: c.Icon,
Fields: string(fields),
CreatedAt: c.CreatedAt,
UpdatedAt: c.UpdatedAt,
}, nil
}
@@ -0,0 +1,39 @@
package mappers
import (
"RenewCMS/internal/domain/entry"
"RenewCMS/internal/infrastructure/persistence/models"
"encoding/json"
)
func EntryToDomain(m models.Entry) (entry.Entry, error) {
data := map[string]any{}
if err := json.Unmarshal([]byte(m.Data), &data); err != nil {
return entry.Entry{}, err
}
return entry.Entry{
ID: m.ID,
ContentTypeID: m.ContentTypeID,
Data: data,
CreatedBy: m.CreatedBy,
UpdatedBy: m.UpdatedBy,
CreatedAt: m.CreatedAt,
UpdatedAt: m.UpdatedAt,
}, nil
}
func EntryToModel(e entry.Entry) (models.Entry, error) {
data, err := json.Marshal(e.Data)
if err != nil {
return models.Entry{}, err
}
return models.Entry{
ID: e.ID,
ContentTypeID: e.ContentTypeID,
Data: string(data),
CreatedBy: e.CreatedBy,
UpdatedBy: e.UpdatedBy,
CreatedAt: e.CreatedAt,
UpdatedAt: e.UpdatedAt,
}, nil
}
@@ -0,0 +1,13 @@
package models
import "time"
type ContentType struct {
ID uint32 `gorm:"primaryKey;autoIncrement"`
Key string `gorm:"column:type_key;size:40;not null;uniqueIndex"`
Name string `gorm:"size:100;not null"`
Icon *string `gorm:"size:40"`
Fields string `gorm:"type:text;not null"`
CreatedAt time.Time `gorm:"autoCreateTime"`
UpdatedAt time.Time `gorm:"autoUpdateTime"`
}
@@ -0,0 +1,13 @@
package models
import "time"
type Entry struct {
ID uint32 `gorm:"primaryKey;autoIncrement"`
ContentTypeID uint32 `gorm:"not null;index"`
Data string `gorm:"type:text;not null"`
CreatedBy uint32 `gorm:"not null"`
UpdatedBy uint32 `gorm:"not null"`
CreatedAt time.Time `gorm:"autoCreateTime"`
UpdatedAt time.Time `gorm:"autoUpdateTime"`
}
@@ -0,0 +1,98 @@
package persistence
import (
domain "RenewCMS/internal/domain/contenttype"
"RenewCMS/internal/infrastructure/persistence/mappers"
entity "RenewCMS/internal/infrastructure/persistence/models"
"errors"
"strings"
"gorm.io/gorm"
)
var _ domain.Repository = &ContentTypeRepository{}
type ContentTypeRepository struct {
db *gorm.DB
}
func NewContentTypeRepository(db *gorm.DB) *ContentTypeRepository {
return &ContentTypeRepository{db}
}
func (c *ContentTypeRepository) Create(contentType domain.ContentType) (domain.ContentType, error) {
model, err := mappers.ContentTypeToModel(contentType)
if err != nil {
return domain.ContentType{}, err
}
if err := c.db.Create(&model).Error; err != nil {
return domain.ContentType{}, mapKeyTakenErr(err)
}
return mappers.ContentTypeToDomain(model)
}
func (c *ContentTypeRepository) GetByKey(key string) (domain.ContentType, error) {
var model entity.ContentType
if err := c.db.Where("type_key = ?", key).First(&model).Error; err != nil {
return domain.ContentType{}, mapNotFoundErr(err, domain.ErrContentTypeNotFound)
}
return mappers.ContentTypeToDomain(model)
}
func (c *ContentTypeRepository) List() ([]domain.ContentType, error) {
var found []entity.ContentType
if err := c.db.Order("LOWER(name) ASC, id ASC").Find(&found).Error; err != nil {
return nil, err
}
contentTypes := make([]domain.ContentType, 0, len(found))
for _, model := range found {
contentType, err := mappers.ContentTypeToDomain(model)
if err != nil {
return nil, err
}
contentTypes = append(contentTypes, contentType)
}
return contentTypes, nil
}
func (c *ContentTypeRepository) Update(contentType domain.ContentType) (domain.ContentType, error) {
model, err := mappers.ContentTypeToModel(contentType)
if err != nil {
return domain.ContentType{}, err
}
result := c.db.Model(&entity.ContentType{}).Where("id = ?", model.ID).Select("Name", "Icon", "Fields", "UpdatedAt").Updates(&model)
if err := deleteOrNotFound(result, domain.ErrContentTypeNotFound); err != nil {
return domain.ContentType{}, mapKeyTakenErr(err)
}
return contentType, nil
}
func (c *ContentTypeRepository) Delete(id uint32) error {
return deleteOrNotFound(c.db.Delete(&entity.ContentType{}, id), domain.ErrContentTypeNotFound)
}
var uniqueViolationMarkers = []string{
"unique constraint failed",
"duplicate entry",
"duplicate key value violates unique constraint",
}
func isUniqueViolation(err error) bool {
if errors.Is(err, gorm.ErrDuplicatedKey) {
return true
}
message := strings.ToLower(err.Error())
for _, marker := range uniqueViolationMarkers {
if strings.Contains(message, marker) {
return true
}
}
return false
}
func mapKeyTakenErr(err error) error {
if isUniqueViolation(err) {
return domain.ErrKeyTaken
}
return err
}
@@ -0,0 +1,152 @@
package persistence
import (
domain "RenewCMS/internal/domain/entry"
"RenewCMS/internal/infrastructure/persistence/mappers"
entity "RenewCMS/internal/infrastructure/persistence/models"
"gorm.io/gorm"
)
var _ domain.Repository = &EntryRepository{}
type EntryRepository struct {
db *gorm.DB
}
func NewEntryRepository(db *gorm.DB) *EntryRepository {
return &EntryRepository{db}
}
var entrySortColumns = map[domain.SortField]string{
domain.SortByID: "id",
domain.SortByCreatedAt: "created_at",
domain.SortByUpdatedAt: "updated_at",
}
var entrySortDirections = map[domain.SortDirection]string{
domain.SortAsc: "ASC",
domain.SortDesc: "DESC",
}
func EntryOrderClause(sort domain.Sort) (string, error) {
column, columnKnown := entrySortColumns[sort.Field]
direction, directionKnown := entrySortDirections[sort.Direction]
if !columnKnown || !directionKnown || !sort.Valid() {
return "", domain.ErrInvalidSort
}
if sort.Field == domain.SortByID {
return column + " " + direction, nil
}
return column + " " + direction + ", id DESC", nil
}
func (e *EntryRepository) Create(record domain.Entry) (domain.Entry, error) {
model, err := mappers.EntryToModel(record)
if err != nil {
return domain.Entry{}, err
}
if err := e.db.Create(&model).Error; err != nil {
return domain.Entry{}, err
}
return mappers.EntryToDomain(model)
}
func (e *EntryRepository) Get(contentTypeID uint32, id uint32) (domain.Entry, error) {
var model entity.Entry
if err := e.db.Where("content_type_id = ? AND id = ?", contentTypeID, id).First(&model).Error; err != nil {
return domain.Entry{}, mapNotFoundErr(err, domain.ErrEntryNotFound)
}
return mappers.EntryToDomain(model)
}
func (e *EntryRepository) ListPage(filters domain.Filters) (domain.PageResult, error) {
order, err := EntryOrderClause(filters.Sort)
if err != nil {
return domain.PageResult{}, err
}
if err := domain.ValidatePage(filters.Page, filters.Size); err != nil {
return domain.PageResult{}, err
}
filters.Page = max(filters.Page, 1)
filters.Size = max(filters.Size, 0)
scoped := func() *gorm.DB {
return e.db.Model(&entity.Entry{}).Where("content_type_id = ?", filters.ContentTypeID)
}
var total int64
if err := scoped().Count(&total).Error; err != nil {
return domain.PageResult{}, err
}
ordered := scoped().Order(order)
if !filters.Unpaged {
ordered = ordered.Limit(filters.Size).Offset((filters.Page - 1) * filters.Size)
}
var models []entity.Entry
if err := ordered.Find(&models).Error; err != nil {
return domain.PageResult{}, err
}
items, err := entriesToDomain(models)
if err != nil {
return domain.PageResult{}, err
}
return domain.PageResult{Items: items, Total: int(total)}, nil
}
func (e *EntryRepository) Update(record domain.Entry) (domain.Entry, error) {
model, err := mappers.EntryToModel(record)
if err != nil {
return domain.Entry{}, err
}
result := e.db.Model(&entity.Entry{}).Where("id = ?", model.ID).Select("Data", "UpdatedBy", "UpdatedAt").Updates(&model)
if err := deleteOrNotFound(result, domain.ErrEntryNotFound); err != nil {
return domain.Entry{}, err
}
return record, nil
}
func (e *EntryRepository) Delete(contentTypeID uint32, id uint32) error {
result := e.db.Where("content_type_id = ? AND id = ?", contentTypeID, id).Delete(&entity.Entry{})
return deleteOrNotFound(result, domain.ErrEntryNotFound)
}
func (e *EntryRepository) DeleteByContentType(contentTypeID uint32) error {
return e.db.Where("content_type_id = ?", contentTypeID).Delete(&entity.Entry{}).Error
}
func (e *EntryRepository) CountByContentType(contentTypeID uint32) (int, error) {
var total int64
if err := e.db.Model(&entity.Entry{}).Where("content_type_id = ?", contentTypeID).Count(&total).Error; err != nil {
return 0, err
}
return int(total), nil
}
func (e *EntryRepository) FindByFieldValue(contentTypeID uint32, fieldKey string, value any, excludeID uint32) ([]domain.Entry, error) {
var models []entity.Entry
if err := e.db.Where("content_type_id = ? AND id <> ?", contentTypeID, excludeID).Find(&models).Error; err != nil {
return nil, err
}
candidates, err := entriesToDomain(models)
if err != nil {
return nil, err
}
matching := []domain.Entry{}
for _, candidate := range candidates {
if domain.SameValue(candidate.Data[fieldKey], value) {
matching = append(matching, candidate)
}
}
return matching, nil
}
func entriesToDomain(models []entity.Entry) ([]domain.Entry, error) {
items := make([]domain.Entry, 0, len(models))
for _, model := range models {
item, err := mappers.EntryToDomain(model)
if err != nil {
return nil, err
}
items = append(items, item)
}
return items, nil
}
@@ -62,6 +62,18 @@ func (u *UserRepository) GetAll() []domainUser.User {
return domainUsers
}
func (u *UserRepository) FindByIDs(ids []uint32) ([]domainUser.User, error) {
var users []entity.User
if err := u.db.Select("id", "username", "display_name").Where("id IN ?", ids).Find(&users).Error; err != nil {
return nil, err
}
found := make([]domainUser.User, 0, len(users))
for _, localUser := range users {
found = append(found, mappers.UserToDomain(localUser))
}
return found, nil
}
func (u *UserRepository) GetByUsername(username string) (domainUser.User, error) {
var localUser entity.User
err := u.db.Model(&entity.User{}).Where("username = ?", username).First(&localUser).Error
@@ -0,0 +1,63 @@
package useCases
import (
"RenewCMS/internal/domain/contenttype"
"errors"
"time"
)
type CreateContentTypeUseCase struct {
contentTypes contenttype.Repository
now func() time.Time
}
type CreateContentTypeCommand struct {
Key string
Name string
Icon *string
Fields []contenttype.Field
}
func NewCreateContentTypeUseCase(contentTypes contenttype.Repository, now func() time.Time) *CreateContentTypeUseCase {
return &CreateContentTypeUseCase{contentTypes, now}
}
func (u *CreateContentTypeUseCase) Create(command CreateContentTypeCommand) (contenttype.ContentType, error) {
if err := contenttype.ValidateKey(command.Key); err != nil {
return contenttype.ContentType{}, err
}
if err := contenttype.ValidateName(command.Name); err != nil {
return contenttype.ContentType{}, err
}
icon, err := contenttype.ValidateIcon(command.Icon)
if err != nil {
return contenttype.ContentType{}, err
}
fields, err := contenttype.ValidateFields(command.Fields)
if err != nil {
return contenttype.ContentType{}, err
}
if err := u.ensureKeyFree(command.Key); err != nil {
return contenttype.ContentType{}, err
}
created := u.now()
return u.contentTypes.Create(contenttype.ContentType{
Key: command.Key,
Name: command.Name,
Icon: icon,
Fields: fields,
CreatedAt: created,
UpdatedAt: created,
})
}
func (u *CreateContentTypeUseCase) ensureKeyFree(key string) error {
_, err := u.contentTypes.GetByKey(key)
if errors.Is(err, contenttype.ErrContentTypeNotFound) {
return nil
}
if err != nil {
return err
}
return contenttype.ErrKeyTaken
}
@@ -0,0 +1,50 @@
package useCases
import (
"RenewCMS/internal/domain/contenttype"
"RenewCMS/internal/domain/entry"
"time"
)
type CreateEntryUseCase struct {
contentTypes contenttype.Repository
entries entry.Repository
now func() time.Time
}
type CreateEntryCommand struct {
ContentTypeKey string
Data map[string]any
UserID uint32
}
func NewCreateEntryUseCase(contentTypes contenttype.Repository, entries entry.Repository, now func() time.Time) *CreateEntryUseCase {
return &CreateEntryUseCase{contentTypes, entries, now}
}
func (u *CreateEntryUseCase) Create(command CreateEntryCommand) (TypedEntry, error) {
owner, err := u.contentTypes.GetByKey(command.ContentTypeKey)
if err != nil {
return TypedEntry{}, err
}
data := entry.ApplyDefaults(owner.Fields, command.Data)
if err := entry.Validate(owner.Fields, data); err != nil {
return TypedEntry{}, err
}
if err := ensureUnique(u.entries, owner, data, 0); err != nil {
return TypedEntry{}, err
}
created := u.now()
stored, err := u.entries.Create(entry.Entry{
ContentTypeID: owner.ID,
Data: data,
CreatedBy: command.UserID,
UpdatedBy: command.UserID,
CreatedAt: created,
UpdatedAt: created,
})
if err != nil {
return TypedEntry{}, err
}
return typedEntry(owner, stored), nil
}
@@ -0,0 +1,30 @@
package useCases
import (
"RenewCMS/internal/domain/contenttype"
"RenewCMS/internal/domain/entry"
)
type DeleteContentTypeUseCase struct {
contentTypes contenttype.Repository
entries entry.Repository
}
func NewDeleteContentTypeUseCase(contentTypes contenttype.Repository, entries entry.Repository) *DeleteContentTypeUseCase {
return &DeleteContentTypeUseCase{contentTypes, entries}
}
func (u *DeleteContentTypeUseCase) Delete(key string) error {
target, err := u.contentTypes.GetByKey(key)
if err != nil {
return err
}
count, err := u.entries.CountByContentType(target.ID)
if err != nil {
return err
}
if count > 0 {
return contenttype.ErrHasEntries
}
return u.contentTypes.Delete(target.ID)
}
@@ -0,0 +1,23 @@
package useCases
import (
"RenewCMS/internal/domain/contenttype"
"RenewCMS/internal/domain/entry"
)
type DeleteEntryUseCase struct {
contentTypes contenttype.Repository
entries entry.Repository
}
func NewDeleteEntryUseCase(contentTypes contenttype.Repository, entries entry.Repository) *DeleteEntryUseCase {
return &DeleteEntryUseCase{contentTypes, entries}
}
func (u *DeleteEntryUseCase) Delete(contentTypeKey string, id uint32) error {
owner, err := u.contentTypes.GetByKey(contentTypeKey)
if err != nil {
return err
}
return u.entries.Delete(owner.ID, id)
}
@@ -0,0 +1,13 @@
package useCases
import "RenewCMS/internal/domain/builtintype"
type GetBuiltinTypeUseCase struct{}
func NewGetBuiltinTypeUseCase() *GetBuiltinTypeUseCase {
return &GetBuiltinTypeUseCase{}
}
func (u *GetBuiltinTypeUseCase) Get(key string) (builtintype.Type, error) {
return builtintype.Find(key)
}
@@ -0,0 +1,15 @@
package useCases
import "RenewCMS/internal/domain/contenttype"
type GetContentTypeUseCase struct {
contentTypes contenttype.Repository
}
func NewGetContentTypeUseCase(contentTypes contenttype.Repository) *GetContentTypeUseCase {
return &GetContentTypeUseCase{contentTypes}
}
func (u *GetContentTypeUseCase) Get(key string) (contenttype.ContentType, error) {
return u.contentTypes.GetByKey(key)
}
@@ -0,0 +1,27 @@
package useCases
import (
"RenewCMS/internal/domain/contenttype"
"RenewCMS/internal/domain/entry"
)
type GetEntryUseCase struct {
contentTypes contenttype.Repository
entries entry.Repository
}
func NewGetEntryUseCase(contentTypes contenttype.Repository, entries entry.Repository) *GetEntryUseCase {
return &GetEntryUseCase{contentTypes, entries}
}
func (u *GetEntryUseCase) Get(contentTypeKey string, id uint32) (TypedEntry, error) {
owner, err := u.contentTypes.GetByKey(contentTypeKey)
if err != nil {
return TypedEntry{}, err
}
found, err := u.entries.Get(owner.ID, id)
if err != nil {
return TypedEntry{}, err
}
return typedEntry(owner, found), nil
}
@@ -5,7 +5,6 @@ import (
"RenewCMS/internal/domain/user"
"errors"
"sort"
"strings"
"time"
)
@@ -62,7 +61,7 @@ func (l *ListAPIKeysUseCase) creatorNamesFor(requester user.User, keys []apikey.
if requester.Role != user.RoleOwner {
return names, nil
}
names[requester.ID] = displayNameOrUsername(requester)
names[requester.ID] = requester.NameOrUsername()
for _, key := range keys {
if _, resolved := names[key.UserID]; resolved {
continue
@@ -75,18 +74,11 @@ func (l *ListAPIKeysUseCase) creatorNamesFor(requester user.User, keys []apikey.
if err != nil {
return nil, err
}
names[key.UserID] = displayNameOrUsername(creator)
names[key.UserID] = creator.NameOrUsername()
}
return names, nil
}
func displayNameOrUsername(account user.User) string {
if trimmed := strings.TrimSpace(account.DisplayName); trimmed != "" {
return trimmed
}
return account.Username
}
func (l *ListAPIKeysUseCase) keysVisibleTo(requester user.User) ([]apikey.APIKey, error) {
if requester.Role == user.RoleOwner {
return l.apiKeyRepository.ListAll()
@@ -0,0 +1,13 @@
package useCases
import "RenewCMS/internal/domain/builtintype"
type ListBuiltinTypesUseCase struct{}
func NewListBuiltinTypesUseCase() *ListBuiltinTypesUseCase {
return &ListBuiltinTypesUseCase{}
}
func (u *ListBuiltinTypesUseCase) List() []builtintype.Type {
return builtintype.Catalogue()
}
@@ -0,0 +1,22 @@
package useCases
import "RenewCMS/internal/domain/contenttype"
type ListContentTypesUseCase struct {
contentTypes contenttype.Repository
}
func NewListContentTypesUseCase(contentTypes contenttype.Repository) *ListContentTypesUseCase {
return &ListContentTypesUseCase{contentTypes}
}
func (u *ListContentTypesUseCase) List() ([]contenttype.ContentType, error) {
found, err := u.contentTypes.List()
if err != nil {
return nil, err
}
if found == nil {
return []contenttype.ContentType{}, nil
}
return found, nil
}
@@ -0,0 +1,51 @@
package useCases
import (
"RenewCMS/internal/domain/contenttype"
"RenewCMS/internal/domain/entry"
)
type ListEntriesUseCase struct {
contentTypes contenttype.Repository
entries entry.Repository
}
type ListEntriesCommand struct {
ContentTypeKey string
Page int
Size int
Sort entry.Sort
}
type EntryPage struct {
Items []TypedEntry
Total int
Page int
Size int
}
func NewListEntriesUseCase(contentTypes contenttype.Repository, entries entry.Repository) *ListEntriesUseCase {
return &ListEntriesUseCase{contentTypes, entries}
}
func (u *ListEntriesUseCase) ListPage(command ListEntriesCommand) (EntryPage, error) {
if err := entry.ValidatePage(command.Page, command.Size); err != nil {
return EntryPage{}, err
}
if !command.Sort.Valid() {
return EntryPage{}, entry.ErrInvalidSort
}
owner, err := u.contentTypes.GetByKey(command.ContentTypeKey)
if err != nil {
return EntryPage{}, err
}
found, err := u.entries.ListPage(entry.Filters{ContentTypeID: owner.ID, Page: command.Page, Size: command.Size, Sort: command.Sort})
if err != nil {
return EntryPage{}, err
}
items := make([]TypedEntry, 0, len(found.Items))
for _, record := range found.Items {
items = append(items, typedEntry(owner, record))
}
return EntryPage{Items: items, Total: found.Total, Page: command.Page, Size: command.Size}, nil
}
@@ -0,0 +1,48 @@
package useCases
import (
"RenewCMS/internal/domain/user"
"sort"
)
type LookupUserNamesUseCase struct {
users user.Repository
}
type UserName struct {
ID uint32
DisplayName string
}
func NewLookupUserNamesUseCase(users user.Repository) *LookupUserNamesUseCase {
return &LookupUserNamesUseCase{users}
}
func (u *LookupUserNamesUseCase) Lookup(ids []uint32) ([]UserName, error) {
distinct := distinctIDs(ids)
if len(distinct) == 0 || len(distinct) > user.MaxLookupIDs {
return nil, user.ErrInvalidLookup
}
found, err := u.users.FindByIDs(distinct)
if err != nil {
return nil, err
}
sort.Slice(found, func(i, j int) bool { return found[i].ID < found[j].ID })
names := make([]UserName, 0, len(found))
for _, record := range found {
names = append(names, UserName{ID: record.ID, DisplayName: record.NameOrUsername()})
}
return names, nil
}
func distinctIDs(ids []uint32) []uint32 {
seen := make(map[uint32]bool, len(ids))
distinct := make([]uint32, 0, len(ids))
for _, id := range ids {
if !seen[id] {
seen[id] = true
distinct = append(distinct, id)
}
}
return distinct
}
@@ -0,0 +1,106 @@
package useCases
import (
"RenewCMS/internal/domain/contenttype"
"RenewCMS/internal/domain/entry"
"time"
)
type UpdateContentTypeUseCase struct {
contentTypes contenttype.Repository
entries entry.Repository
now func() time.Time
}
type UpdateContentTypeCommand struct {
Key string
Name string
Icon *string
Fields []contenttype.Field
}
func NewUpdateContentTypeUseCase(contentTypes contenttype.Repository, entries entry.Repository, now func() time.Time) *UpdateContentTypeUseCase {
return &UpdateContentTypeUseCase{contentTypes, entries, now}
}
func (u *UpdateContentTypeUseCase) Update(command UpdateContentTypeCommand) (contenttype.ContentType, error) {
current, err := u.contentTypes.GetByKey(command.Key)
if err != nil {
return contenttype.ContentType{}, err
}
if err := contenttype.ValidateName(command.Name); err != nil {
return contenttype.ContentType{}, err
}
icon, err := contenttype.ValidateIcon(command.Icon)
if err != nil {
return contenttype.ContentType{}, err
}
fields, err := contenttype.ValidateFields(command.Fields)
if err != nil {
return contenttype.ContentType{}, err
}
stored, err := u.storedEntries(current.ID)
if err != nil {
return contenttype.ContentType{}, err
}
if len(stored) > 0 {
if err := checkCompatibility(current.Fields, fields, stored); err != nil {
return contenttype.ContentType{}, err
}
}
current.Name = command.Name
current.Icon = icon
current.Fields = fields
current.UpdatedAt = u.now()
return u.contentTypes.Update(current)
}
func (u *UpdateContentTypeUseCase) storedEntries(contentTypeID uint32) ([]entry.Entry, error) {
found, err := u.entries.ListPage(entry.Filters{ContentTypeID: contentTypeID, Unpaged: true, Sort: entry.DefaultSort()})
if err != nil {
return nil, err
}
return found.Items, nil
}
func checkCompatibility(previous []contenttype.Field, next []contenttype.Field, stored []entry.Entry) error {
if fieldTypeChanged(previous, next) {
return contenttype.ErrInvalidField
}
seen := make(map[string][]any)
for _, record := range stored {
data := entry.ApplyDefaults(next, entry.Project(next, record.Data))
if entry.Validate(next, data) != nil {
return contenttype.ErrSchemaIncompatible
}
if collides(seen, entry.UniqueValues(next, data)) {
return contenttype.ErrSchemaIncompatible
}
}
return nil
}
func fieldTypeChanged(previous []contenttype.Field, next []contenttype.Field) bool {
types := make(map[string]contenttype.FieldType, len(previous))
for _, field := range previous {
types[field.Key] = field.Type
}
for _, field := range next {
if before, existed := types[field.Key]; existed && before != field.Type {
return true
}
}
return false
}
func collides(seen map[string][]any, values []entry.UniqueValue) bool {
for _, candidate := range values {
for _, earlier := range seen[candidate.Key] {
if entry.SameValue(earlier, candidate.Value) {
return true
}
}
seen[candidate.Key] = append(seen[candidate.Key], candidate.Value)
}
return false
}
@@ -0,0 +1,49 @@
package useCases
import (
"RenewCMS/internal/domain/contenttype"
"RenewCMS/internal/domain/entry"
"time"
)
type UpdateEntryUseCase struct {
contentTypes contenttype.Repository
entries entry.Repository
now func() time.Time
}
type UpdateEntryCommand struct {
ContentTypeKey string
ID uint32
Data map[string]any
UserID uint32
}
func NewUpdateEntryUseCase(contentTypes contenttype.Repository, entries entry.Repository, now func() time.Time) *UpdateEntryUseCase {
return &UpdateEntryUseCase{contentTypes, entries, now}
}
func (u *UpdateEntryUseCase) Update(command UpdateEntryCommand) (TypedEntry, error) {
owner, err := u.contentTypes.GetByKey(command.ContentTypeKey)
if err != nil {
return TypedEntry{}, err
}
current, err := u.entries.Get(owner.ID, command.ID)
if err != nil {
return TypedEntry{}, err
}
if err := entry.Validate(owner.Fields, command.Data); err != nil {
return TypedEntry{}, err
}
if err := ensureUnique(u.entries, owner, command.Data, current.ID); err != nil {
return TypedEntry{}, err
}
current.Data = command.Data
current.UpdatedBy = command.UserID
current.UpdatedAt = u.now()
stored, err := u.entries.Update(current)
if err != nil {
return TypedEntry{}, err
}
return typedEntry(owner, stored), nil
}
@@ -0,0 +1,29 @@
package useCases
import (
"RenewCMS/internal/domain/contenttype"
"RenewCMS/internal/domain/entry"
)
type TypedEntry struct {
entry.Entry
ContentTypeKey string
}
func typedEntry(owner contenttype.ContentType, record entry.Entry) TypedEntry {
record.Data = entry.Project(owner.Fields, record.Data)
return TypedEntry{Entry: record, ContentTypeKey: owner.Key}
}
func ensureUnique(entries entry.Repository, owner contenttype.ContentType, data map[string]any, excludeID uint32) error {
for _, candidate := range entry.UniqueValues(owner.Fields, data) {
taken, err := entries.FindByFieldValue(owner.ID, candidate.Key, candidate.Value, excludeID)
if err != nil {
return err
}
if len(taken) > 0 {
return entry.UniqueViolation(candidate.Key)
}
}
return nil
}
+117
View File
@@ -0,0 +1,117 @@
package test
import (
articleHandler "RenewCMS/api/handlers/article"
siteHandler "RenewCMS/api/handlers/site"
userHandler "RenewCMS/api/handlers/user"
"RenewCMS/internal/domain/builtintype"
"RenewCMS/internal/domain/contenttype"
"reflect"
"sort"
"strconv"
"strings"
"testing"
)
type driftTagRules struct {
required bool
min any
max any
options []string
}
func driftParseTag(tag string) driftTagRules {
rules := driftTagRules{}
for _, part := range strings.Split(tag, ",") {
switch {
case part == "required":
rules.required = true
case strings.HasPrefix(part, "min="):
value, _ := strconv.Atoi(strings.TrimPrefix(part, "min="))
rules.min = value
case strings.HasPrefix(part, "max="):
value, _ := strconv.Atoi(strings.TrimPrefix(part, "max="))
rules.max = value
case strings.HasPrefix(part, "oneof="):
rules.options = strings.Fields(strings.TrimPrefix(part, "oneof="))
}
}
return rules
}
func driftTagFor(t *testing.T, structType reflect.Type, jsonKey string) (string, bool) {
t.Helper()
for i := 0; i < structType.NumField(); i++ {
field := structType.Field(i)
if strings.Split(field.Tag.Get("json"), ",")[0] == jsonKey {
return field.Tag.Get("validate"), true
}
}
return "", false
}
func driftSorted(values []string) []string {
out := append([]string{}, values...)
sort.Strings(out)
return out
}
type driftBinding struct {
typeKey string
request any
fields []string
checkRequired bool
}
func TestBuiltinCatalogueMatchesRequestTags(t *testing.T) {
bindings := []driftBinding{
{builtintype.KeyArticle, articleHandler.PostArticle{}, []string{"title"}, true},
{builtintype.KeyArticle, articleHandler.UpdateArticleBody{}, []string{"excerpt", "seo_title", "seo_description", "canonical_url"}, false},
{builtintype.KeyArticle, articleHandler.CheckArticleSEOBody{}, []string{"excerpt", "seo_title", "seo_description", "canonical_url"}, false},
{builtintype.KeySite, siteHandler.PostSite{}, []string{"name", "key", "base_url", "default_robots", "site_name", "title_template", "default_description"}, true},
{builtintype.KeySite, siteHandler.PatchSite{}, []string{"default_robots", "site_name", "title_template", "default_description"}, false},
{builtintype.KeyUser, userHandler.CreateInviteRequest{}, []string{"email"}, true},
}
covered := map[string]bool{}
for _, binding := range bindings {
builtin, err := builtintype.Find(binding.typeKey)
if err != nil {
t.Fatalf("catalogue type %s: %v", binding.typeKey, err)
}
byKey := map[string]contenttype.Field{}
for _, f := range builtin.Fields {
byKey[f.Key] = f
}
structType := reflect.TypeOf(binding.request)
for _, key := range binding.fields {
catalogueField, ok := byKey[key]
if !ok {
t.Errorf("%s.%s missing from catalogue", binding.typeKey, key)
continue
}
tag, found := driftTagFor(t, structType, key)
if !found {
t.Errorf("%s has no json field %s", structType.Name(), key)
continue
}
rules := driftParseTag(tag)
covered[binding.typeKey+"."+key] = true
label := binding.typeKey + "." + key + " vs " + structType.Name()
if binding.checkRequired && rules.required != catalogueField.Required {
t.Errorf("%s: required catalogue=%v tag=%v", label, catalogueField.Required, rules.required)
}
if !reflect.DeepEqual(rules.min, catalogueField.Min) {
t.Errorf("%s: min catalogue=%v tag=%v", label, catalogueField.Min, rules.min)
}
if !reflect.DeepEqual(rules.max, catalogueField.Max) {
t.Errorf("%s: max catalogue=%v tag=%v", label, catalogueField.Max, rules.max)
}
if !reflect.DeepEqual(driftSorted(rules.options), driftSorted(catalogueField.Options)) {
t.Errorf("%s: options catalogue=%v tag=%v", label, catalogueField.Options, rules.options)
}
}
}
if len(covered) != 13 {
t.Errorf("covered catalogue fields = %d, want 13", len(covered))
}
}
@@ -0,0 +1,684 @@
package test
import (
"RenewCMS/api"
"RenewCMS/api/pkg/apperr"
validator "RenewCMS/api/pkg/validator"
"RenewCMS/internal/domain/article"
"RenewCMS/internal/domain/author"
"RenewCMS/internal/domain/builtintype"
"RenewCMS/internal/domain/contenttype"
"RenewCMS/internal/domain/entry"
"RenewCMS/internal/domain/image"
"RenewCMS/internal/domain/site"
"RenewCMS/internal/domain/user"
"RenewCMS/internal/infrastructure/config"
"RenewCMS/internal/infrastructure/hashing"
"RenewCMS/internal/infrastructure/persistence/mappers"
"RenewCMS/internal/infrastructure/useCases"
"encoding/json"
"errors"
"fmt"
"net/http"
"net/http/httptest"
"reflect"
"strconv"
"strings"
"testing"
"time"
"github.com/go-chi/chi/v5"
"github.com/go-chi/jwtauth/v5"
)
const supportRecipeKey = "recipe"
var supportContentTypeKeys = []string{"created_at", "fields", "icon", "id", "key", "name", "updated_at"}
var supportFieldKeys = []string{"default", "key", "label", "max", "min", "options", "required", "type", "unique"}
func newSupportEnv(t *testing.T) *contentTypeEnv {
t.Helper()
env := newContentTypeEnv(t)
env.users.users[ctOwnerId] = user.User{ID: ctOwnerId, Username: "marta", DisplayName: "Marta Alves", IsVerified: true, Role: user.RoleOwner}
env.users.users[ctMemberId] = user.User{ID: ctMemberId, Username: "sam", DisplayName: "Sam Roy", IsVerified: true, Role: user.RoleAdmin}
return env
}
func recipeWithIcon(icon any, present bool) string {
body := map[string]any{"key": supportRecipeKey, "name": "Recipe", "fields": recipeFields()}
if present {
body["icon"] = icon
}
encoded, _ := json.Marshal(body)
return string(encoded)
}
func recipeUpdate(icon any, present bool) string {
body := map[string]any{"name": "Recipe", "fields": recipeFields()}
if present {
body["icon"] = icon
}
encoded, _ := json.Marshal(body)
return string(encoded)
}
func rawJSONValue(t *testing.T, rec *httptest.ResponseRecorder, key string) string {
t.Helper()
var decoded map[string]json.RawMessage
if err := json.Unmarshal(rec.Body.Bytes(), &decoded); err != nil {
t.Fatalf("failed to decode %q: %v", rec.Body.String(), err)
}
raw, present := decoded[key]
if !present {
t.Fatalf("key %q missing in %q", key, rec.Body.String())
}
return string(raw)
}
func decodeContentArray(t *testing.T, rec *httptest.ResponseRecorder) []map[string]any {
t.Helper()
var decoded []map[string]any
if err := json.Unmarshal(rec.Body.Bytes(), &decoded); err != nil {
t.Fatalf("failed to decode %q: %v", rec.Body.String(), err)
}
return decoded
}
func expectIconEverywhere(t *testing.T, env *contentTypeEnv, want string) {
t.Helper()
one := env.admin(t, http.MethodGet, "/v1/content-type/"+supportRecipeKey, "")
if got := rawJSONValue(t, one, "icon"); got != want {
t.Errorf("GET one: expected icon %s, got %s", want, got)
}
list := env.admin(t, http.MethodGet, "/v1/content-type", "")
var items []map[string]json.RawMessage
if err := json.Unmarshal(list.Body.Bytes(), &items); err != nil || len(items) != 1 {
t.Fatalf("unexpected list %q: %v", list.Body.String(), err)
}
if got := string(items[0]["icon"]); got != want {
t.Errorf("GET list: expected icon %s, got %s", want, got)
}
}
func TestContentTypeIconHTTP(t *testing.T) {
t.Run("Creating a content type with an icon", func(t *testing.T) {
env := newSupportEnv(t)
rec := env.admin(t, http.MethodPost, "/v1/content-type", recipeWithIcon("chef-hat", true))
expectStatusAndBody(t, rec, http.StatusCreated, "")
if got := objectKeys(decodeContentObject(t, rec)); !reflect.DeepEqual(got, supportContentTypeKeys) {
t.Errorf("expected keys %v, got %v", supportContentTypeKeys, got)
}
if got := rawJSONValue(t, rec, "icon"); got != `"chef-hat"` {
t.Errorf("expected chef-hat, got %s", got)
}
expectIconEverywhere(t, env, `"chef-hat"`)
})
t.Run("A content type without an icon has a null icon", func(t *testing.T) {
cases := map[string]string{
"no icon key": recipeWithIcon(nil, false),
`"icon": null`: recipeWithIcon(nil, true),
`"icon": ""`: recipeWithIcon("", true),
}
for name, body := range cases {
t.Run(name, func(t *testing.T) {
env := newSupportEnv(t)
rec := env.admin(t, http.MethodPost, "/v1/content-type", body)
expectStatusAndBody(t, rec, http.StatusCreated, "")
if got := rawJSONValue(t, rec, "icon"); got != "null" {
t.Errorf("expected null, got %s", got)
}
expectIconEverywhere(t, env, "null")
})
}
})
t.Run("A content type stored before this slice still works", func(t *testing.T) {
env := newSupportEnv(t)
env.types.types[1] = contenttype.ContentType{ID: 1, Key: supportRecipeKey, Name: "Recipe", Fields: []contenttype.Field{{Key: "title", Label: "Title", Type: contenttype.TypeText}}}
rec := env.as(t, ctMemberId, http.MethodGet, "/v1/content-type/"+supportRecipeKey, "")
expectStatusAndBody(t, rec, http.StatusOK, "")
if got := rawJSONValue(t, rec, "icon"); got != "null" {
t.Errorf("expected null, got %s", got)
}
if got := objectKeys(decodeContentObject(t, rec)); !reflect.DeepEqual(got, supportContentTypeKeys) {
t.Errorf("unexpected keys %v", got)
}
expectIconEverywhere(t, env, "null")
})
t.Run("An invalid icon is refused and stores nothing", func(t *testing.T) {
invalid := []any{"Chef-Hat", "1star", "-star", "chef hat", "chef_hat", strings.Repeat("a", 41), 5}
for _, icon := range invalid {
t.Run(fmt.Sprint(icon), func(t *testing.T) {
env := newSupportEnv(t)
rec := env.admin(t, http.MethodPost, "/v1/content-type", recipeWithIcon(icon, true))
expectStatusAndBody(t, rec, http.StatusBadRequest, apperr.InvalidIconErrorMessage)
if len(env.types.types) != 0 {
t.Errorf("expected nothing stored, got %d", len(env.types.types))
}
})
}
})
t.Run("Boundary icons are accepted", func(t *testing.T) {
env := newSupportEnv(t)
for index, icon := range []string{"a", "a" + strings.Repeat("b", 39)} {
body := map[string]any{"key": "recipe" + strconv.Itoa(index), "name": "Recipe", "icon": icon, "fields": recipeFields()}
encoded, _ := json.Marshal(body)
expectStatusAndBody(t, env.admin(t, http.MethodPost, "/v1/content-type", string(encoded)), http.StatusCreated, "")
}
})
t.Run("Updating the icon of a content type", func(t *testing.T) {
cases := []struct {
name string
body string
status int
message string
icon string
}{
{"utensils", recipeUpdate("utensils", true), http.StatusOK, "", `"utensils"`},
{"no icon key", recipeUpdate(nil, false), http.StatusOK, "", "null"},
{"null", recipeUpdate(nil, true), http.StatusOK, "", "null"},
{"bad icon", recipeUpdate("Bad Icon", true), http.StatusBadRequest, apperr.InvalidIconErrorMessage, `"chef-hat"`},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
env := newSupportEnv(t)
expectStatusAndBody(t, env.admin(t, http.MethodPost, "/v1/content-type", recipeWithIcon("chef-hat", true)), http.StatusCreated, "")
rec := env.admin(t, http.MethodPut, "/v1/content-type/"+supportRecipeKey, tc.body)
expectStatusAndBody(t, rec, tc.status, tc.message)
expectIconEverywhere(t, env, tc.icon)
})
}
})
t.Run("The icon does not affect entries", func(t *testing.T) {
env := newSupportEnv(t)
expectStatusAndBody(t, env.admin(t, http.MethodPost, "/v1/content-type", recipeWithIcon("chef-hat", true)), http.StatusCreated, "")
created := env.createEntry(t, supportRecipeKey, ctAdminId, `{"title": "Soup", "difficulty": "easy"}`)
expectStatusAndBody(t, created, http.StatusCreated, "")
before := env.entries.entries[1]
expectStatusAndBody(t, env.admin(t, http.MethodPut, "/v1/content-type/"+supportRecipeKey, recipeUpdate("utensils", true)), http.StatusOK, "")
if after := env.entries.entries[1]; !reflect.DeepEqual(before, after) {
t.Errorf("entry changed: %v -> %v", before, after)
}
})
}
func TestContentTypeIconUseCase(t *testing.T) {
invalid := []string{"Chef-Hat", "1star", "-star", "chef hat", "chef_hat", strings.Repeat("a", 41)}
now := func() time.Time { return time.Date(2026, time.October, 5, 9, 0, 0, 0, time.UTC) }
fields := []contenttype.Field{{Key: "title", Label: "Title", Type: contenttype.TypeText}}
for _, icon := range invalid {
t.Run("use case rejects "+icon, func(t *testing.T) {
repo := newMockContentTypeRepo()
repo.types[1] = contenttype.ContentType{ID: 1, Key: "dish", Name: "Dish", Fields: fields}
bad := icon
_, err := useCases.NewCreateContentTypeUseCase(repo, now).Create(useCases.CreateContentTypeCommand{Key: "recipe", Name: "Recipe", Icon: &bad, Fields: fields})
if !errors.Is(err, contenttype.ErrInvalidIcon) || repo.createCalls != 0 {
t.Errorf("create: err %v, calls %d", err, repo.createCalls)
}
_, err = useCases.NewUpdateContentTypeUseCase(repo, newMockEntryRepo(), now).Update(useCases.UpdateContentTypeCommand{Key: "dish", Name: "Dish", Icon: &bad, Fields: fields})
if !errors.Is(err, contenttype.ErrInvalidIcon) || repo.updateCalls != 0 {
t.Errorf("update: err %v, calls %d", err, repo.updateCalls)
}
})
}
t.Run("domain rule", func(t *testing.T) {
empty, valid := "", "chef-hat"
if got, err := contenttype.ValidateIcon(&empty); got != nil || err != nil {
t.Errorf("empty icon should become nil, got %v %v", got, err)
}
if got, err := contenttype.ValidateIcon(&valid); err != nil || *got != valid {
t.Errorf("valid icon refused: %v", err)
}
if got, err := contenttype.ValidateIcon(nil); got != nil || err != nil {
t.Errorf("nil icon should stay nil, got %v %v", got, err)
}
})
}
func checkBuiltinItem(t *testing.T, item map[string]any) {
t.Helper()
if got := objectKeys(item); !reflect.DeepEqual(got, []string{"fields", "key", "name"}) {
t.Fatalf("unexpected item keys %v", got)
}
engineTypes := map[string]bool{"text": true, "richtext": true, "number": true, "boolean": true, "date": true, "select": true}
for _, raw := range item["fields"].([]any) {
field := raw.(map[string]any)
if got := objectKeys(field); !reflect.DeepEqual(got, supportFieldKeys) {
t.Errorf("unexpected field keys %v", got)
}
if !engineTypes[field["type"].(string)] {
t.Errorf("unknown field type %v", field["type"])
}
}
}
func builtinFieldKeys(item map[string]any) []string {
keys := []string{}
for _, raw := range item["fields"].([]any) {
keys = append(keys, raw.(map[string]any)["key"].(string))
}
return keys
}
func TestBuiltinTypeHTTP(t *testing.T) {
t.Run("Listing the built-in types", func(t *testing.T) {
env := newSupportEnv(t)
rec := env.as(t, ctOwnerId, http.MethodGet, "/v1/builtin-type", "")
expectStatusAndBody(t, rec, http.StatusOK, "")
items := decodeContentArray(t, rec)
keys, names := []string{}, []string{}
for _, item := range items {
checkBuiltinItem(t, item)
keys = append(keys, item["key"].(string))
names = append(names, item["name"].(string))
}
if !reflect.DeepEqual(keys, []string{"article", "author", "site", "media", "user"}) {
t.Errorf("unexpected keys %v", keys)
}
if !reflect.DeepEqual(names, []string{"Articles", "Authors", "Sites", "Media", "Users"}) {
t.Errorf("unexpected names %v", names)
}
})
t.Run("The built-in field lists match the real API", func(t *testing.T) {
env := newSupportEnv(t)
want := map[string]string{
"article": "title, body, slug, excerpt, seo_title, seo_description, is_online, canonical_url, noindex",
"author": "name, slug, bio, website",
"site": "name, key, base_url, default_robots, locale, is_default, site_name, title_template, default_description",
"media": "filename, size, width, height, content_type",
"user": "username, display_name, email, role",
}
forbidden := []string{"id", "created_at", "updated_at", "password", "password_reset_code", "verification_code", "token_version"}
for key, fields := range want {
t.Run(key, func(t *testing.T) {
rec := env.admin(t, http.MethodGet, "/v1/builtin-type/"+key, "")
expectStatusAndBody(t, rec, http.StatusOK, "")
got := builtinFieldKeys(decodeContentObject(t, rec))
if strings.Join(got, ", ") != fields {
t.Errorf("expected %s, got %v", fields, got)
}
for _, name := range got {
for _, bad := range forbidden {
if name == bad {
t.Errorf("forbidden field %s", name)
}
}
}
})
}
})
t.Run("Selected built-in field rules", func(t *testing.T) {
env := newSupportEnv(t)
cases := []struct {
key, field, fieldType string
required bool
min, max any
options []any
}{
{"article", "title", "text", true, float64(3), float64(200), []any{}},
{"article", "body", "richtext", false, nil, nil, []any{}},
{"article", "excerpt", "text", false, nil, float64(300), []any{}},
{"article", "is_online", "boolean", false, nil, nil, []any{}},
{"site", "default_robots", "select", false, nil, nil, []any{"index", "noindex"}},
{"site", "site_name", "text", false, nil, float64(100), []any{}},
{"site", "title_template", "text", false, nil, float64(200), []any{}},
{"site", "default_description", "text", false, nil, float64(320), []any{}},
{"user", "role", "select", true, nil, nil, []any{"owner", "admin"}},
{"user", "email", "text", true, nil, nil, []any{}},
}
for _, tc := range cases {
t.Run(tc.key+"."+tc.field, func(t *testing.T) {
item := decodeContentObject(t, env.admin(t, http.MethodGet, "/v1/builtin-type/"+tc.key, ""))
for _, raw := range item["fields"].([]any) {
field := raw.(map[string]any)
if field["key"] != tc.field {
continue
}
if field["type"] != tc.fieldType || field["required"] != tc.required || field["min"] != tc.min || field["max"] != tc.max || !reflect.DeepEqual(field["options"], tc.options) {
t.Errorf("unexpected field %v", field)
}
return
}
t.Errorf("field %s missing", tc.field)
})
}
})
t.Run("Reading one built-in type does not collide with a custom type of the same key", func(t *testing.T) {
env := newSupportEnv(t)
env.createType(t, "builtin", dishFields())
env.createType(t, "article", dishFields())
for _, key := range []string{"builtin", "article"} {
rec := env.admin(t, http.MethodGet, "/v1/content-type/"+key, "")
expectStatusAndBody(t, rec, http.StatusOK, "")
if got := objectKeys(decodeContentObject(t, rec)); !reflect.DeepEqual(got, supportContentTypeKeys) {
t.Errorf("%s is not the custom type: %v", key, got)
}
}
item := decodeContentObject(t, env.admin(t, http.MethodGet, "/v1/builtin-type/article", ""))
if item["name"] != "Articles" {
t.Errorf("expected the built-in article, got %v", item["name"])
}
listed := decodeContentArray(t, env.admin(t, http.MethodGet, "/v1/content-type", ""))
if len(listed) != 2 {
t.Errorf("expected 2 custom types, got %d", len(listed))
}
})
t.Run("The built-in routes are read-only and restricted", func(t *testing.T) {
env := newSupportEnv(t)
stale := func(req *http.Request) {
_, tokenString, _ := env.token.Encode(map[string]any{"user_id": uint32(ctStaleId), "token_version": 0})
req.AddCookie(&http.Cookie{Name: "jwt", Value: tokenString})
}
apiKey := env.issueKey(ctAdminId)
cases := []struct {
name, method, path string
mutate func(*http.Request)
status int
message string
}{
{"owner 1 cookie", http.MethodGet, "/v1/builtin-type", env.asUser(t, ctOwnerId), 200, ""},
{"admin 2 cookie", http.MethodGet, "/v1/builtin-type/user", env.asUser(t, ctAdminId), 200, ""},
{"an active API key of admin 2", http.MethodGet, "/v1/builtin-type", func(req *http.Request) { req.Header.Set("Authorization", "Bearer "+apiKey) }, 200, ""},
{"a cookie for unverified 4", http.MethodGet, "/v1/builtin-type", env.asUser(t, ctUnverifiedId), 403, apperr.VerificationRequiredErrorMessage},
{"no credentials", http.MethodGet, "/v1/builtin-type", nil, 401, ""},
{"a stale token_version cookie", http.MethodGet, "/v1/builtin-type", stale, 401, ""},
{"unknown key", http.MethodGet, "/v1/builtin-type/nope", env.asUser(t, ctAdminId), 404, apperr.BuiltinTypeNotFoundErrorMessage},
{"uppercase key", http.MethodGet, "/v1/builtin-type/Article", env.asUser(t, ctAdminId), 404, apperr.BuiltinTypeNotFoundErrorMessage},
{"POST", http.MethodPost, "/v1/builtin-type", env.asUser(t, ctAdminId), 405, ""},
{"PUT", http.MethodPut, "/v1/builtin-type/article", env.asUser(t, ctAdminId), 405, ""},
{"DELETE", http.MethodDelete, "/v1/builtin-type/article", env.asUser(t, ctAdminId), 405, ""},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
rec := env.request(t, tc.method, tc.path, "", tc.mutate)
expectStatusAndBody(t, rec, tc.status, tc.message)
if tc.status == http.StatusMethodNotAllowed && rec.Body.Len() != 0 {
t.Errorf("expected empty body, got %q", rec.Body.String())
}
})
}
})
t.Run("Reading the built-in types never touches data", func(t *testing.T) {
validator.InitValidator()
users := newMockUserRepo()
users.users[ctAdminId] = user.User{ID: ctAdminId, Username: "dev", IsVerified: true, Role: user.RoleAdmin}
token := jwtauth.New("HS256", []byte("test-secret"), nil)
now := func() time.Time { return time.Now() }
generator := hashing.NewSHA256KeyGenerator()
container := &api.UseCases{
Token: token,
GetUserUseCase: useCases.NewGetUserUseCase(users),
AuthenticateAPIKeyUseCase: useCases.NewAuthenticateAPIKeyUseCase(newMockAPIKeyRepo(), generator, users, now),
ListBuiltinTypesUseCase: useCases.NewListBuiltinTypesUseCase(),
GetBuiltinTypeUseCase: useCases.NewGetBuiltinTypeUseCase(),
CreateContentTypeUseCase: useCases.NewCreateContentTypeUseCase(panickingContentTypeRepo{}, now),
CreateEntryUseCase: useCases.NewCreateEntryUseCase(panickingContentTypeRepo{}, panickingEntryRepo{}, now),
}
router := chi.NewRouter()
router.Mount("/v1", api.InitBackendRoutes(container, config.Settings{}))
_, tokenString, _ := token.Encode(map[string]any{"user_id": uint32(ctAdminId), "token_version": 0})
for _, path := range []string{"/v1/builtin-type", "/v1/builtin-type/site"} {
req := httptest.NewRequest(http.MethodGet, path, nil)
req.AddCookie(&http.Cookie{Name: "jwt", Value: tokenString})
rec := httptest.NewRecorder()
router.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Errorf("%s: status %d", path, rec.Code)
}
}
})
}
type panickingContentTypeRepo struct{ contenttype.Repository }
type panickingEntryRepo struct{ entry.Repository }
func TestBuiltinTypeCatalogueMatchesEntities(t *testing.T) {
entities := map[string]any{
builtintype.KeyArticle: article.Article{},
builtintype.KeyAuthor: author.Author{},
builtintype.KeySite: site.Site{},
builtintype.KeyMedia: image.Image{},
builtintype.KeyUser: user.User{},
}
for key, entity := range entities {
t.Run(key, func(t *testing.T) {
encoded, err := json.Marshal(entity)
if err != nil {
t.Fatal(err)
}
var object map[string]any
_ = json.Unmarshal(encoded, &object)
found, err := builtintype.Find(key)
if err != nil {
t.Fatal(err)
}
for _, field := range found.Fields {
if _, exists := object[field.Key]; !exists {
t.Errorf("catalogue field %s.%s does not exist in the entity JSON", key, field.Key)
}
}
})
}
}
func TestBuiltinTypeUseCases(t *testing.T) {
if got := useCases.NewListBuiltinTypesUseCase().List(); len(got) != 5 {
t.Errorf("expected 5 types, got %d", len(got))
}
if _, err := useCases.NewGetBuiltinTypeUseCase().Get("nope"); !errors.Is(err, builtintype.ErrNotFound) {
t.Errorf("expected ErrNotFound, got %v", err)
}
found, err := useCases.NewGetBuiltinTypeUseCase().Get("site")
if err != nil || found.Name != "Sites" {
t.Errorf("unexpected %v %v", found, err)
}
}
func lookupQuery(ids ...int) string {
parts := make([]string, 0, len(ids))
for _, id := range ids {
parts = append(parts, strconv.Itoa(id))
}
return "?ids=" + strings.Join(parts, ",")
}
func TestUserLookupHTTP(t *testing.T) {
t.Run("Any verified user resolves display names", func(t *testing.T) {
env := newSupportEnv(t)
rec := env.as(t, ctMemberId, http.MethodGet, "/v1/user/lookup?ids=1,2,3", "")
expectStatusAndBody(t, rec, http.StatusOK, "")
items := decodeContentArray(t, rec)
wantNames := []string{"Marta Alves", "dev", "Sam Roy"}
if len(items) != 3 {
t.Fatalf("expected 3 items, got %v", items)
}
for index, item := range items {
if got := objectKeys(item); !reflect.DeepEqual(got, []string{"display_name", "id"}) {
t.Errorf("unexpected keys %v", got)
}
if item["id"] != float64(index+1) || item["display_name"] != wantNames[index] {
t.Errorf("unexpected item %v", item)
}
}
for _, leaked := range []string{"email", "role", "username", "status", "password"} {
if strings.Contains(rec.Body.String(), leaked) {
t.Errorf("body leaks %s", leaked)
}
}
})
t.Run("Lookup edge cases", func(t *testing.T) {
env := newSupportEnv(t)
var hundred, overflow []int
for id := 1; id <= 100; id++ {
hundred = append(hundred, id)
}
overflow = append(hundred, 101)
cases := []struct {
name, query string
status int
body string
count int
}{
{"duplicates", "?ids=2,2,2", 200, "", 1},
{"one unknown", "?ids=1,999", 200, "", 1},
{"all unknown", "?ids=999", 200, "[]", 0},
{"unverified user", "?ids=4", 200, "", 1},
{"no query", "", 400, apperr.BodyErrorMessage, 0},
{"empty", "?ids=", 400, apperr.BodyErrorMessage, 0},
{"letters", "?ids=abc", 400, apperr.BodyErrorMessage, 0},
{"negative", "?ids=1,-2", 400, apperr.BodyErrorMessage, 0},
{"overflow", "?ids=1,4294967296", 400, apperr.BodyErrorMessage, 0},
{"empty element", "?ids=1,,2", 400, apperr.BodyErrorMessage, 0},
{"101 distinct ids", lookupQuery(overflow...), 400, apperr.BodyErrorMessage, 0},
{"exactly 100 ids", lookupQuery(hundred...), 200, "", 5},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
rec := env.as(t, ctMemberId, http.MethodGet, "/v1/user/lookup"+tc.query, "")
expectStatusAndBody(t, rec, tc.status, tc.body)
if tc.status == http.StatusOK {
if got := len(decodeContentArray(t, rec)); got != tc.count {
t.Errorf("expected %d items, got %d", tc.count, got)
}
}
})
}
})
t.Run("Repository failure is a 500, not a 400", func(t *testing.T) {
env := newSupportEnv(t)
env.users.fail.failNext("FindByIDs")
rec := env.as(t, ctMemberId, http.MethodGet, "/v1/user/lookup?ids=1", "")
expectStatusAndBody(t, rec, http.StatusInternalServerError, "Internal server error")
})
t.Run("More than the maximum raw parts is rejected", func(t *testing.T) {
env := newSupportEnv(t)
rec := env.as(t, ctMemberId, http.MethodGet, "/v1/user/lookup?ids="+strings.Repeat("1,", 100)+"1", "")
expectStatusAndBody(t, rec, http.StatusBadRequest, apperr.BodyErrorMessage)
})
t.Run("Lookup needs a verified signed-in user or an API key", func(t *testing.T) {
env := newSupportEnv(t)
apiKey := env.issueKey(ctAdminId)
stale := func(req *http.Request) {
_, tokenString, _ := env.token.Encode(map[string]any{"user_id": uint32(ctStaleId), "token_version": 0})
req.AddCookie(&http.Cookie{Name: "jwt", Value: tokenString})
}
cases := []struct {
name string
mutate func(*http.Request)
status int
}{
{"verified user 3", env.asUser(t, ctMemberId), 200},
{"API key", func(req *http.Request) { req.Header.Set("Authorization", "Bearer "+apiKey) }, 200},
{"no credentials", nil, 401},
{"unverified 4", env.asUser(t, ctUnverifiedId), 403},
{"stale token", stale, 401},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
rec := env.request(t, http.MethodGet, "/v1/user/lookup?ids=1", "", tc.mutate)
if rec.Code != tc.status {
t.Errorf("expected %d, got %d (%s)", tc.status, rec.Code, rec.Body.String())
}
})
}
})
t.Run("Existing user and entry responses are unchanged", func(t *testing.T) {
env := newSupportEnv(t)
env.createType(t, supportRecipeKey, recipeFields())
expectStatusAndBody(t, env.createEntry(t, supportRecipeKey, ctMemberId, `{"title": "Soup", "difficulty": "easy"}`), http.StatusCreated, "")
rec := env.as(t, ctMemberId, http.MethodGet, "/v1/user/", "")
expectStatusAndBody(t, rec, http.StatusOK, "")
list := env.as(t, ctMemberId, http.MethodGet, "/v1/content-type/"+supportRecipeKey+"/entry", "")
expectStatusAndBody(t, list, http.StatusOK, "")
var page struct {
Items []map[string]any `json:"items"`
}
if err := json.Unmarshal(list.Body.Bytes(), &page); err != nil || len(page.Items) != 1 {
t.Fatalf("unexpected page %q: %v", list.Body.String(), err)
}
if page.Items[0]["created_by"] != float64(ctMemberId) || page.Items[0]["updated_by"] != float64(ctMemberId) {
t.Errorf("created_by and updated_by should stay numeric ids: %v", page.Items[0])
}
})
}
func TestLookupUserNamesUseCase(t *testing.T) {
users := newMockUserRepo()
users.users[1] = user.User{ID: 1, Username: "marta", DisplayName: "Marta Alves"}
users.users[2] = user.User{ID: 2, Username: "dev"}
lookup := useCases.NewLookupUserNamesUseCase(users)
t.Run("display name, username fallback, unknown omitted, one batch call", func(t *testing.T) {
names, err := lookup.Lookup([]uint32{2, 999, 1, 1})
if err != nil {
t.Fatal(err)
}
want := []useCases.UserName{{ID: 1, DisplayName: "Marta Alves"}, {ID: 2, DisplayName: "dev"}}
if !reflect.DeepEqual(names, want) {
t.Errorf("expected %v, got %v", want, names)
}
if users.findByIDsCalls != 1 {
t.Errorf("expected a single batch call, got %d", users.findByIDsCalls)
}
})
t.Run("exactly the maximum number of ids is accepted", func(t *testing.T) {
atLimit := make([]uint32, 0, user.MaxLookupIDs)
for id := uint32(1); id <= user.MaxLookupIDs; id++ {
atLimit = append(atLimit, id)
}
if _, err := lookup.Lookup(atLimit); err != nil {
t.Errorf("expected no error at the limit, got %v", err)
}
})
t.Run("no ids or too many ids", func(t *testing.T) {
if _, err := lookup.Lookup(nil); !errors.Is(err, user.ErrInvalidLookup) {
t.Errorf("expected ErrInvalidLookup, got %v", err)
}
tooMany := make([]uint32, 0, 101)
for id := uint32(1); id <= 101; id++ {
tooMany = append(tooMany, id)
}
if _, err := lookup.Lookup(tooMany); !errors.Is(err, user.ErrInvalidLookup) {
t.Errorf("expected ErrInvalidLookup, got %v", err)
}
})
}
func TestContentTypeIconMapperRoundTrip(t *testing.T) {
icon := "chef-hat"
for name, stored := range map[string]*string{"nil": nil, "set": &icon} {
t.Run(name, func(t *testing.T) {
model, err := mappers.ContentTypeToModel(contenttype.ContentType{Key: "recipe", Icon: stored, Fields: []contenttype.Field{}})
if err != nil {
t.Fatal(err)
}
back, err := mappers.ContentTypeToDomain(model)
if err != nil {
t.Fatal(err)
}
if !reflect.DeepEqual(back.Icon, stored) {
t.Errorf("expected %v, got %v", stored, back.Icon)
}
})
}
}
+383
View File
@@ -0,0 +1,383 @@
package test
import (
"RenewCMS/api"
validator "RenewCMS/api/pkg/validator"
"RenewCMS/internal/domain/apikey"
"RenewCMS/internal/domain/contenttype"
"RenewCMS/internal/domain/entry"
"RenewCMS/internal/domain/user"
"RenewCMS/internal/infrastructure/config"
"RenewCMS/internal/infrastructure/hashing"
"RenewCMS/internal/infrastructure/useCases"
"encoding/json"
"net/http"
"net/http/httptest"
"reflect"
"sort"
"strings"
"testing"
"time"
"github.com/go-chi/chi/v5"
"github.com/go-chi/jwtauth/v5"
)
const (
ctOwnerId = 1
ctAdminId = 2
ctMemberId = 3
ctUnverifiedId = 4
ctStaleId = 5
)
type mockContentTypeRepo struct {
types map[uint32]contenttype.ContentType
nextID uint32
createCalls int
updateCalls int
deleteCalls int
fail failSwitch
}
var _ contenttype.Repository = &mockContentTypeRepo{}
func newMockContentTypeRepo() *mockContentTypeRepo {
return &mockContentTypeRepo{types: map[uint32]contenttype.ContentType{}}
}
func (m *mockContentTypeRepo) Create(contentType contenttype.ContentType) (contenttype.ContentType, error) {
if err := m.fail.trigger("Create"); err != nil {
return contenttype.ContentType{}, err
}
m.createCalls++
m.nextID++
contentType.ID = m.nextID
m.types[contentType.ID] = contentType
return contentType, nil
}
func (m *mockContentTypeRepo) GetByKey(key string) (contenttype.ContentType, error) {
if err := m.fail.trigger("GetByKey"); err != nil {
return contenttype.ContentType{}, err
}
for _, stored := range m.types {
if stored.Key == key {
return stored, nil
}
}
return contenttype.ContentType{}, contenttype.ErrContentTypeNotFound
}
func (m *mockContentTypeRepo) List() ([]contenttype.ContentType, error) {
if err := m.fail.trigger("List"); err != nil {
return nil, err
}
listed := []contenttype.ContentType{}
for _, stored := range m.types {
listed = append(listed, stored)
}
sort.Slice(listed, func(i, j int) bool { return listed[i].Name < listed[j].Name })
return listed, nil
}
func (m *mockContentTypeRepo) Update(contentType contenttype.ContentType) (contenttype.ContentType, error) {
if err := m.fail.trigger("Update"); err != nil {
return contenttype.ContentType{}, err
}
m.updateCalls++
m.types[contentType.ID] = contentType
return contentType, nil
}
func (m *mockContentTypeRepo) Delete(id uint32) error {
if err := m.fail.trigger("Delete"); err != nil {
return err
}
m.deleteCalls++
delete(m.types, id)
return nil
}
type mockEntryRepo struct {
entries map[uint32]entry.Entry
nextID uint32
createCalls int
updateCalls int
}
var _ entry.Repository = &mockEntryRepo{}
func newMockEntryRepo() *mockEntryRepo {
return &mockEntryRepo{entries: map[uint32]entry.Entry{}}
}
func (m *mockEntryRepo) Create(record entry.Entry) (entry.Entry, error) {
m.createCalls++
m.nextID++
record.ID = m.nextID
m.entries[record.ID] = record
return record, nil
}
func (m *mockEntryRepo) Get(contentTypeID uint32, id uint32) (entry.Entry, error) {
if stored, found := m.entries[id]; found && stored.ContentTypeID == contentTypeID {
return stored, nil
}
return entry.Entry{}, entry.ErrEntryNotFound
}
func (m *mockEntryRepo) ListPage(filters entry.Filters) (entry.PageResult, error) {
matching := []entry.Entry{}
for _, stored := range m.entries {
if stored.ContentTypeID == filters.ContentTypeID {
matching = append(matching, stored)
}
}
sortEntries(matching, filters.Sort)
page := entry.PageResult{Items: []entry.Entry{}, Total: len(matching)}
if filters.Unpaged {
page.Items = matching
return page, nil
}
start := min((filters.Page-1)*filters.Size, len(matching))
end := min(start+filters.Size, len(matching))
page.Items = matching[start:end]
return page, nil
}
func sortEntries(items []entry.Entry, order entry.Sort) {
if order.Field == "" {
order = entry.DefaultSort()
}
key := func(item entry.Entry) int64 {
switch order.Field {
case entry.SortByID:
return int64(item.ID)
case entry.SortByCreatedAt:
return item.CreatedAt.UnixNano()
}
return item.UpdatedAt.UnixNano()
}
sort.SliceStable(items, func(i, j int) bool {
if order.Direction == entry.SortAsc {
return key(items[i]) < key(items[j])
}
return key(items[i]) > key(items[j])
})
}
func (m *mockEntryRepo) Update(record entry.Entry) (entry.Entry, error) {
m.updateCalls++
m.entries[record.ID] = record
return record, nil
}
func (m *mockEntryRepo) Delete(contentTypeID uint32, id uint32) error {
if _, err := m.Get(contentTypeID, id); err != nil {
return err
}
delete(m.entries, id)
return nil
}
func (m *mockEntryRepo) DeleteByContentType(contentTypeID uint32) error {
for id, stored := range m.entries {
if stored.ContentTypeID == contentTypeID {
delete(m.entries, id)
}
}
return nil
}
func (m *mockEntryRepo) CountByContentType(contentTypeID uint32) (int, error) {
count := 0
for _, stored := range m.entries {
if stored.ContentTypeID == contentTypeID {
count++
}
}
return count, nil
}
func (m *mockEntryRepo) FindByFieldValue(contentTypeID uint32, fieldKey string, value any, excludeID uint32) ([]entry.Entry, error) {
found := []entry.Entry{}
for _, stored := range m.entries {
if stored.ContentTypeID == contentTypeID && stored.ID != excludeID && reflect.DeepEqual(stored.Data[fieldKey], value) {
found = append(found, stored)
}
}
return found, nil
}
type contentTypeEnv struct {
types *mockContentTypeRepo
entries *mockEntryRepo
users *mockUserRepo
keys *mockAPIKeyRepo
generator *hashing.SHA256KeyGenerator
token *jwtauth.JWTAuth
clock time.Time
router http.Handler
}
func newContentTypeEnv(t *testing.T) *contentTypeEnv {
t.Helper()
validator.InitValidator()
entries := newMockEntryRepo()
env := &contentTypeEnv{
types: newMockContentTypeRepo(),
entries: entries,
users: newMockUserRepo(),
keys: newMockAPIKeyRepo(),
generator: hashing.NewSHA256KeyGenerator(),
token: jwtauth.New("HS256", []byte("test-secret"), nil),
clock: time.Date(2026, time.October, 5, 9, 0, 0, 0, time.UTC),
}
env.users.users[ctOwnerId] = user.User{ID: ctOwnerId, Username: "marta", IsVerified: true, Role: user.RoleOwner}
env.users.users[ctAdminId] = user.User{ID: ctAdminId, Username: "dev", IsVerified: true, Role: user.RoleAdmin}
env.users.users[ctMemberId] = user.User{ID: ctMemberId, Username: "pat", IsVerified: true}
env.users.users[ctUnverifiedId] = user.User{ID: ctUnverifiedId, Username: "quinn", IsVerified: false, Role: user.RoleAdmin}
env.users.users[ctStaleId] = user.User{ID: ctStaleId, Username: "stale", IsVerified: true, Role: user.RoleAdmin, TokenVersion: 1}
now := func() time.Time { return env.clock }
container := &api.UseCases{
Token: env.token,
GetUserUseCase: useCases.NewGetUserUseCase(env.users),
AuthenticateAPIKeyUseCase: useCases.NewAuthenticateAPIKeyUseCase(env.keys, env.generator, env.users, now),
CreateContentTypeUseCase: useCases.NewCreateContentTypeUseCase(env.types, now),
ListContentTypesUseCase: useCases.NewListContentTypesUseCase(env.types),
GetContentTypeUseCase: useCases.NewGetContentTypeUseCase(env.types),
UpdateContentTypeUseCase: useCases.NewUpdateContentTypeUseCase(env.types, env.entries, now),
DeleteContentTypeUseCase: useCases.NewDeleteContentTypeUseCase(env.types, env.entries),
ListUsersAndInvitesUseCase: useCases.NewListUsersAndInvitesUseCase(env.users, newInviteFakeRepo()),
ListBuiltinTypesUseCase: useCases.NewListBuiltinTypesUseCase(),
GetBuiltinTypeUseCase: useCases.NewGetBuiltinTypeUseCase(),
LookupUserNamesUseCase: useCases.NewLookupUserNamesUseCase(env.users),
CreateEntryUseCase: useCases.NewCreateEntryUseCase(env.types, env.entries, now),
GetEntryUseCase: useCases.NewGetEntryUseCase(env.types, env.entries),
ListEntriesUseCase: useCases.NewListEntriesUseCase(env.types, env.entries),
UpdateEntryUseCase: useCases.NewUpdateEntryUseCase(env.types, env.entries, now),
DeleteEntryUseCase: useCases.NewDeleteEntryUseCase(env.types, env.entries),
}
router := chi.NewRouter()
router.Mount("/v1", api.InitBackendRoutes(container, config.Settings{}))
env.router = router
return env
}
func (e *contentTypeEnv) request(t *testing.T, method string, path string, body string, mutate func(*http.Request)) *httptest.ResponseRecorder {
t.Helper()
req := httptest.NewRequest(method, path, strings.NewReader(body))
if body != "" {
req.Header.Set("Content-Type", "application/json")
}
if mutate != nil {
mutate(req)
}
rec := httptest.NewRecorder()
e.router.ServeHTTP(rec, req)
return rec
}
func (e *contentTypeEnv) asUser(t *testing.T, userId uint32) func(*http.Request) {
t.Helper()
return func(req *http.Request) {
if userId == 0 {
return
}
_, tokenString, err := e.token.Encode(map[string]any{"user_id": userId, "token_version": 0})
if err != nil {
t.Fatalf("failed to encode jwt: %v", err)
}
req.AddCookie(&http.Cookie{Name: "jwt", Value: tokenString})
}
}
func (e *contentTypeEnv) as(t *testing.T, userId uint32, method string, path string, body string) *httptest.ResponseRecorder {
t.Helper()
return e.request(t, method, path, body, e.asUser(t, userId))
}
func (e *contentTypeEnv) issueKey(userId uint32) string {
raw, prefix, hashed := e.generator.Generate()
_, _ = e.keys.Create(apikey.APIKey{UserID: userId, Name: "ci", Prefix: prefix, HashedKey: hashed, CreatedAt: e.clock})
return raw
}
func (e *contentTypeEnv) admin(t *testing.T, method string, path string, body string) *httptest.ResponseRecorder {
t.Helper()
return e.as(t, ctAdminId, method, path, body)
}
func (e *contentTypeEnv) createType(t *testing.T, key string, fields []map[string]any) {
t.Helper()
rec := e.admin(t, http.MethodPost, "/v1/content-type", typeBody(key, strings.ToUpper(key[:1])+key[1:], fields))
if rec.Code != http.StatusCreated {
t.Fatalf("create type %s: %d %s", key, rec.Code, rec.Body.String())
}
}
func (e *contentTypeEnv) createEntry(t *testing.T, key string, userId uint32, data string) *httptest.ResponseRecorder {
t.Helper()
e.clock = e.clock.Add(time.Minute)
return e.as(t, userId, http.MethodPost, "/v1/content-type/"+key+"/entry", `{"data": `+data+`}`)
}
func typeBody(key string, name string, fields []map[string]any) string {
encoded, _ := json.Marshal(map[string]any{"key": key, "name": name, "fields": fields})
return string(encoded)
}
func recipeFields() []map[string]any {
return []map[string]any{
{"key": "title", "label": "Title", "type": "text", "required": true, "unique": true, "min": 3, "max": 80},
{"key": "servings", "label": "Servings", "type": "number", "default": 4, "min": 1, "max": 50},
{"key": "vegetarian", "label": "Vegetarian", "type": "boolean", "default": false},
{"key": "published_on", "label": "Published on", "type": "date"},
{"key": "difficulty", "label": "Difficulty", "type": "select", "required": true, "options": []string{"easy", "medium", "hard"}},
{"key": "notes", "label": "Notes", "type": "richtext", "max": 500},
}
}
func dishFields() []map[string]any {
return []map[string]any{
{"key": "title", "label": "Title", "type": "text", "unique": true},
{"key": "slug", "label": "Slug", "type": "text", "unique": true},
}
}
func textField(overrides map[string]any) map[string]any {
field := map[string]any{"key": "title", "label": "Title", "type": "text"}
for key, value := range overrides {
field[key] = value
}
return field
}
func decodeContentObject(t *testing.T, rec *httptest.ResponseRecorder) map[string]any {
t.Helper()
var decoded map[string]any
if err := json.Unmarshal(rec.Body.Bytes(), &decoded); err != nil {
t.Fatalf("failed to decode %q: %v", rec.Body.String(), err)
}
return decoded
}
func objectKeys(object map[string]any) []string {
keys := make([]string, 0, len(object))
for key := range object {
keys = append(keys, key)
}
sort.Strings(keys)
return keys
}
func expectStatusAndBody(t *testing.T, rec *httptest.ResponseRecorder, status int, body string) {
t.Helper()
if rec.Code != status {
t.Fatalf("expected status %d, got %d, body %q", status, rec.Code, rec.Body.String())
}
if body != "" && strings.TrimSpace(rec.Body.String()) != body {
t.Errorf("expected body %q, got %q", body, rec.Body.String())
}
}
+668
View File
@@ -0,0 +1,668 @@
package test
import (
"RenewCMS/api/pkg/apperr"
"net/http"
"reflect"
"strconv"
"strings"
"testing"
"time"
)
var (
contentTypeKeys = []string{"created_at", "fields", "icon", "id", "key", "name", "updated_at"}
fieldKeys = []string{"default", "key", "label", "max", "min", "options", "required", "type", "unique"}
entryKeys = []string{"content_type", "created_at", "created_by", "data", "id", "updated_at", "updated_by"}
)
func TestCreatingAContentType(t *testing.T) {
t.Run("Creating a content type", func(t *testing.T) {
env := newContentTypeEnv(t)
rec := env.admin(t, http.MethodPost, "/v1/content-type", typeBody("recipe", "Recipe", recipeFields()))
expectStatusAndBody(t, rec, http.StatusCreated, "")
body := decodeContentObject(t, rec)
if !reflect.DeepEqual(objectKeys(body), contentTypeKeys) || body["key"] != "recipe" {
t.Fatalf("unexpected body %v", body)
}
fields := body["fields"].([]any)
for index, sent := range recipeFields() {
field := fields[index].(map[string]any)
if field["key"] != sent["key"] || !reflect.DeepEqual(objectKeys(field), fieldKeys) {
t.Errorf("unexpected field %d: %v", index, field)
}
}
first := fields[0].(map[string]any)
if first["default"] != nil || fields[3].(map[string]any)["min"] != nil || len(fields[0].(map[string]any)["options"].([]any)) != 0 {
t.Errorf("expected null unset values and [] options: %v", first)
}
})
}
func TestCreatingAContentTypeWithAnInvalidBody(t *testing.T) {
many := make([]map[string]any, 51)
for index := range many {
many[index] = textField(map[string]any{"key": "f" + strconv.Itoa(index)})
}
one := []map[string]any{textField(nil)}
invalidField := func(overrides map[string]any) []map[string]any {
return []map[string]any{textField(overrides)}
}
examples := []struct {
name string
body string
status int
message string
}{
{"body not-json", "not-json", 400, apperr.BodyErrorMessage},
{"body {}", "{}", 400, "Key"},
{"key with a capital and a symbol", typeBody("Recipe!", "R", one), 400, apperr.InvalidContentTypeKeyErrorMessage},
{"key too short", typeBody("r", "R", one), 400, apperr.InvalidContentTypeKeyErrorMessage},
{"key too long", typeBody(strings.Repeat("a", 41), "R", one), 400, apperr.InvalidContentTypeKeyErrorMessage},
{"empty name", typeBody("recipe", "", one), 400, "Name"},
{"no fields", typeBody("recipe", "R", []map[string]any{}), 422, apperr.InvalidFieldErrorMessage},
{"51 fields", typeBody("recipe", "R", many), 422, apperr.InvalidFieldErrorMessage},
{"field key Title", typeBody("recipe", "R", invalidField(map[string]any{"key": "Title"})), 422, apperr.InvalidFieldErrorMessage},
{"field key 1st", typeBody("recipe", "R", invalidField(map[string]any{"key": "1st"})), 422, apperr.InvalidFieldErrorMessage},
{"field key a-b", typeBody("recipe", "R", invalidField(map[string]any{"key": "a-b"})), 422, apperr.InvalidFieldErrorMessage},
{"two fields with the key title", typeBody("recipe", "R", []map[string]any{textField(nil), textField(nil)}), 422, apperr.InvalidFieldErrorMessage},
{"a field type integer", typeBody("recipe", "R", invalidField(map[string]any{"type": "integer"})), 422, apperr.InvalidFieldErrorMessage},
{"a select field with no options", typeBody("recipe", "R", invalidField(map[string]any{"type": "select"})), 422, apperr.InvalidFieldErrorMessage},
{"a select field with an empty option", typeBody("recipe", "R", invalidField(map[string]any{"type": "select", "options": []string{"a", ""}})), 422, apperr.InvalidFieldErrorMessage},
{"a select field with a duplicated option", typeBody("recipe", "R", invalidField(map[string]any{"type": "select", "options": []string{"a", "a"}})), 422, apperr.InvalidFieldErrorMessage},
{"options on a non-select field", typeBody("recipe", "R", invalidField(map[string]any{"options": []string{"a"}})), 422, apperr.InvalidFieldErrorMessage},
{"min on a boolean field", typeBody("recipe", "R", invalidField(map[string]any{"type": "boolean", "min": 1})), 422, apperr.InvalidFieldErrorMessage},
{"max on a select field", typeBody("recipe", "R", invalidField(map[string]any{"type": "select", "options": []string{"a"}, "max": 1})), 422, apperr.InvalidFieldErrorMessage},
{"min greater than max", typeBody("recipe", "R", invalidField(map[string]any{"type": "number", "min": 5, "max": 3})), 422, apperr.InvalidFieldErrorMessage},
{"a negative min on a text field", typeBody("recipe", "R", invalidField(map[string]any{"min": -1})), 422, apperr.InvalidFieldErrorMessage},
{"a fractional max on a richtext field", typeBody("recipe", "R", invalidField(map[string]any{"type": "richtext", "max": 1.5})), 422, apperr.InvalidFieldErrorMessage},
{"a non-date min on a date field", typeBody("recipe", "R", invalidField(map[string]any{"type": "date", "min": "soon"})), 422, apperr.InvalidFieldErrorMessage},
{"a numeric max on a date field", typeBody("recipe", "R", invalidField(map[string]any{"type": "date", "max": 5})), 422, apperr.InvalidFieldErrorMessage},
{"unique on a richtext field", typeBody("recipe", "R", invalidField(map[string]any{"type": "richtext", "unique": true})), 422, apperr.InvalidFieldErrorMessage},
{"unique on a boolean field", typeBody("recipe", "R", invalidField(map[string]any{"type": "boolean", "unique": true})), 422, apperr.InvalidFieldErrorMessage},
{"a default of the wrong type", typeBody("recipe", "R", invalidField(map[string]any{"default": 5})), 422, apperr.InvalidFieldErrorMessage},
{"a default outside min and max", typeBody("recipe", "R", invalidField(map[string]any{"type": "number", "min": 1, "max": 5, "default": 9})), 422, apperr.InvalidFieldErrorMessage},
{"a default not in the options", typeBody("recipe", "R", invalidField(map[string]any{"type": "select", "options": []string{"a"}, "default": "b"})), 422, apperr.InvalidFieldErrorMessage},
{"a default on a unique field", typeBody("recipe", "R", invalidField(map[string]any{"unique": true, "default": "abc"})), 422, apperr.InvalidFieldErrorMessage},
}
t.Run("Creating a content type with an invalid body is refused and stores nothing", func(t *testing.T) {
for _, example := range examples {
t.Run(example.name, func(t *testing.T) {
env := newContentTypeEnv(t)
rec := env.admin(t, http.MethodPost, "/v1/content-type", example.body)
if rec.Code != example.status || !strings.Contains(rec.Body.String(), example.message) {
t.Errorf("expected %d containing %q, got %d %q", example.status, example.message, rec.Code, rec.Body.String())
}
if len(env.types.types) != 0 {
t.Errorf("expected no content type, got %v", env.types.types)
}
})
}
})
}
func TestContentTypeKeysAndAccess(t *testing.T) {
t.Run("A content type key can't be reused", func(t *testing.T) {
env := newContentTypeEnv(t)
env.createType(t, "recipe", recipeFields())
rec := env.admin(t, http.MethodPost, "/v1/content-type", typeBody("recipe", "Other", recipeFields()))
expectStatusAndBody(t, rec, http.StatusConflict, apperr.ContentTypeKeyTakenErrorMessage)
if len(env.types.types) != 1 {
t.Errorf("expected one content type")
}
})
t.Run("Writing content types needs a verified owner or admin", func(t *testing.T) {
examples := []struct {
caller string
userId uint32
status int
message string
}{
{"no credentials", 0, 401, ""},
{"a jwt cookie for user 4", ctUnverifiedId, 403, apperr.VerificationRequiredErrorMessage},
{"a stale token_version cookie", ctStaleId, 401, apperr.UnauthorizedErrorMessage},
{"a verified member without a role", ctMemberId, 403, apperr.OwnerOrAdminRequiredErrorMessage},
}
for _, example := range examples {
t.Run(example.caller, func(t *testing.T) {
env := newContentTypeEnv(t)
rec := env.as(t, example.userId, http.MethodPost, "/v1/content-type", typeBody("recipe", "Recipe", recipeFields()))
expectStatusAndBody(t, rec, example.status, example.message)
if len(env.types.types) != 0 {
t.Errorf("expected no content type")
}
})
}
})
t.Run("An API key acts as its creator on the content type routes", func(t *testing.T) {
env := newContentTypeEnv(t)
raw := env.issueKey(ctAdminId)
rec := env.request(t, http.MethodPost, "/v1/content-type", typeBody("recipe", "Recipe", recipeFields()), func(req *http.Request) {
req.Header.Set("Authorization", "Bearer "+raw)
})
expectStatusAndBody(t, rec, http.StatusCreated, "")
})
t.Run("Listing and reading content types", func(t *testing.T) {
env := newContentTypeEnv(t)
env.createType(t, "recipe", recipeFields())
env.createType(t, "event", dishFields())
list := env.as(t, ctMemberId, http.MethodGet, "/v1/content-type", "")
expectStatusAndBody(t, list, http.StatusOK, "")
if !strings.HasPrefix(list.Body.String(), "[") || strings.Index(list.Body.String(), `"event"`) > strings.Index(list.Body.String(), `"recipe"`) {
t.Errorf("expected both types ordered by name, got %s", list.Body.String())
}
one := env.as(t, ctMemberId, http.MethodGet, "/v1/content-type/recipe", "")
expectStatusAndBody(t, one, http.StatusOK, "")
if decodeContentObject(t, one)["key"] != "recipe" {
t.Errorf("unexpected body %s", one.Body.String())
}
})
t.Run("Reading a content type that doesn't exist or with a bad key", func(t *testing.T) {
examples := []struct{ method, key, body string }{
{http.MethodGet, "nope", ""},
{http.MethodPut, "nope", typeBody("nope", "Nope", recipeFields())},
{http.MethodDelete, "nope", ""},
{http.MethodGet, "Bad_Key", ""},
}
for _, example := range examples {
t.Run(example.method+" "+example.key, func(t *testing.T) {
env := newContentTypeEnv(t)
rec := env.admin(t, example.method, "/v1/content-type/"+example.key, example.body)
expectStatusAndBody(t, rec, http.StatusNotFound, apperr.ContentTypeNotFoundErrorMessage)
})
}
})
}
func TestUpdatingAContentType(t *testing.T) {
t.Run("Updating a content type before it has entries", func(t *testing.T) {
env := newContentTypeEnv(t)
env.createType(t, "recipe", recipeFields())
reordered := []map[string]any{
{"key": "difficulty", "label": "Difficulty", "type": "number"},
{"key": "title", "label": "Title", "type": "text"},
}
rec := env.admin(t, http.MethodPut, "/v1/content-type/recipe", typeBody("recipe", "Dish", reordered))
expectStatusAndBody(t, rec, http.StatusOK, "")
body := decodeContentObject(t, rec)
fields := body["fields"].([]any)
if body["name"] != "Dish" || len(fields) != 2 || fields[0].(map[string]any)["key"] != "difficulty" || fields[0].(map[string]any)["type"] != "number" || body["key"] != "recipe" {
t.Errorf("unexpected body %v", body)
}
})
t.Run("The key of a content type can't be changed", func(t *testing.T) {
env := newContentTypeEnv(t)
env.createType(t, "recipe", recipeFields())
rec := env.admin(t, http.MethodPut, "/v1/content-type/recipe", typeBody("dish", "Recipe", recipeFields()))
expectStatusAndBody(t, rec, http.StatusOK, "")
if decodeContentObject(t, rec)["key"] != "recipe" {
t.Errorf("expected the key to stay recipe")
}
})
t.Run("Updating a content type that has entries", func(t *testing.T) {
withField := func(modify func([]map[string]any) []map[string]any) []map[string]any {
return modify(recipeFields())
}
replace := func(key string, overrides map[string]any) func([]map[string]any) []map[string]any {
return func(fields []map[string]any) []map[string]any {
for _, field := range fields {
if field["key"] == key {
for name, value := range overrides {
field[name] = value
}
}
}
return fields
}
}
examples := []struct {
change string
fields []map[string]any
name string
status int
message string
updated bool
}{
{"a field's type changed from text to number", withField(replace("title", map[string]any{"type": "number"})), "Recipe", 422, apperr.InvalidFieldErrorMessage, false},
{"a new required field without a default", append(recipeFields(), textField(map[string]any{"key": "extra", "required": true})), "Recipe", 409, apperr.SchemaIncompatibleErrorMessage, false},
{"a new required field with a default", append(recipeFields(), textField(map[string]any{"key": "extra", "required": true, "default": "none"})), "Recipe", 200, "", true},
{"a new optional field", append(recipeFields(), textField(map[string]any{"key": "extra"})), "Recipe", 200, "", true},
{"the field notes removed", recipeFields()[:5], "Recipe", 200, "", true},
{"the option easy removed from difficulty", withField(replace("difficulty", map[string]any{"options": []string{"medium", "hard"}})), "Recipe", 409, apperr.SchemaIncompatibleErrorMessage, false},
{"the option hard removed from difficulty", withField(replace("difficulty", map[string]any{"options": []string{"easy", "medium"}})), "Recipe", 200, "", true},
{"title max lowered below the stored title's length", withField(replace("title", map[string]any{"max": 5})), "Recipe", 409, apperr.SchemaIncompatibleErrorMessage, false},
{"label, order or name changed", withField(replace("title", map[string]any{"label": "Name"})), "Dish", 200, "", true},
}
for _, example := range examples {
t.Run(example.change, func(t *testing.T) {
env := newContentTypeEnv(t)
env.createType(t, "recipe", recipeFields())
env.createEntry(t, "recipe", ctAdminId, `{"title": "Pad thai", "difficulty": "easy"}`)
before := env.types.types[1]
rec := env.admin(t, http.MethodPut, "/v1/content-type/recipe", typeBody("recipe", example.name, example.fields))
expectStatusAndBody(t, rec, example.status, example.message)
changed := !reflect.DeepEqual(env.types.types[1].Fields, before.Fields) || env.types.types[1].Name != before.Name
if changed != example.updated {
t.Errorf("expected updated=%v, got %v", example.updated, changed)
}
})
}
})
t.Run("Making a field unique is refused when stored values collide", func(t *testing.T) {
env := newContentTypeEnv(t)
loose := []map[string]any{textField(nil)}
env.createType(t, "recipe", loose)
env.createEntry(t, "recipe", ctAdminId, `{"title": "Pad thai"}`)
env.createEntry(t, "recipe", ctAdminId, `{"title": "Pad thai"}`)
rec := env.admin(t, http.MethodPut, "/v1/content-type/recipe", typeBody("recipe", "Recipe", []map[string]any{textField(map[string]any{"unique": true})}))
expectStatusAndBody(t, rec, http.StatusConflict, apperr.SchemaIncompatibleErrorMessage)
if env.types.types[1].Fields[0].Unique {
t.Errorf("expected the schema to stay unchanged")
}
})
t.Run("Values of a removed field are no longer returned", func(t *testing.T) {
env := newContentTypeEnv(t)
env.createType(t, "recipe", recipeFields())
created := decodeContentObject(t, env.createEntry(t, "recipe", ctAdminId, `{"title": "Pad thai", "difficulty": "easy", "notes": "Soak overnight"}`))
id := strconv.Itoa(int(created["id"].(float64)))
env.admin(t, http.MethodPut, "/v1/content-type/recipe", typeBody("recipe", "Recipe", recipeFields()[:5]))
got := decodeContentObject(t, env.admin(t, http.MethodGet, "/v1/content-type/recipe/entry/"+id, ""))
if _, present := got["data"].(map[string]any)["notes"]; present {
t.Errorf("expected no notes key, got %v", got["data"])
}
saved := env.admin(t, http.MethodPut, "/v1/content-type/recipe/entry/"+id, `{"data": {"title": "Pad thai", "difficulty": "easy"}}`)
expectStatusAndBody(t, saved, http.StatusOK, "")
if _, present := env.entries.entries[1].Data["notes"]; present {
t.Errorf("expected the stored document to have no notes key")
}
})
}
func TestDeletingAContentType(t *testing.T) {
t.Run("Deleting a content type", func(t *testing.T) {
env := newContentTypeEnv(t)
env.createType(t, "event", dishFields())
rec := env.admin(t, http.MethodDelete, "/v1/content-type/event", "")
expectStatusAndBody(t, rec, http.StatusNoContent, "")
if rec.Body.Len() != 0 {
t.Errorf("expected an empty body")
}
expectStatusAndBody(t, env.admin(t, http.MethodGet, "/v1/content-type/event", ""), http.StatusNotFound, apperr.ContentTypeNotFoundErrorMessage)
})
t.Run("A repository failure on update or delete returns 500 and changes nothing", func(t *testing.T) {
env := newContentTypeEnv(t)
env.createType(t, "event", dishFields())
before := env.types.types[1]
env.types.fail.failNext("Update")
rec := env.admin(t, http.MethodPut, "/v1/content-type/event", typeBody("event", "Renamed", dishFields()))
expectStatusAndBody(t, rec, http.StatusInternalServerError, "Internal server error")
if !reflect.DeepEqual(env.types.types[1], before) {
t.Errorf("expected the stored type to be unchanged after a failed update")
}
env.types.fail.failNext("Delete")
rec = env.admin(t, http.MethodDelete, "/v1/content-type/event", "")
expectStatusAndBody(t, rec, http.StatusInternalServerError, "Internal server error")
if len(env.types.types) != 1 {
t.Errorf("expected the type to remain after a failed delete")
}
})
t.Run("A content type with entries can't be deleted", func(t *testing.T) {
env := newContentTypeEnv(t)
env.createType(t, "recipe", recipeFields())
env.createEntry(t, "recipe", ctAdminId, `{"title": "Pad thai", "difficulty": "easy"}`)
rec := env.admin(t, http.MethodDelete, "/v1/content-type/recipe", "")
expectStatusAndBody(t, rec, http.StatusConflict, apperr.ContentTypeHasEntriesErrorMessage)
if len(env.types.types) != 1 || len(env.entries.entries) != 1 {
t.Errorf("expected the type and its entry to remain")
}
})
}
func TestCreatingEntries(t *testing.T) {
t.Run("Creating an entry applies defaults", func(t *testing.T) {
env := newContentTypeEnv(t)
env.createType(t, "recipe", recipeFields())
rec := env.createEntry(t, "recipe", ctAdminId, `{"title": "Pad thai", "difficulty": "easy"}`)
expectStatusAndBody(t, rec, http.StatusCreated, "")
body := decodeContentObject(t, rec)
want := map[string]any{"title": "Pad thai", "difficulty": "easy", "servings": float64(4), "vegetarian": false}
if !reflect.DeepEqual(objectKeys(body), entryKeys) || body["content_type"] != "recipe" || body["created_by"] != float64(2) || body["updated_by"] != float64(2) || !reflect.DeepEqual(body["data"], want) {
t.Errorf("unexpected body %v", body)
}
})
t.Run("An explicit value overrides the default and an explicit null is kept", func(t *testing.T) {
env := newContentTypeEnv(t)
env.createType(t, "recipe", recipeFields())
rec := env.createEntry(t, "recipe", ctAdminId, `{"title": "Soup", "difficulty": "easy", "servings": 2, "published_on": null}`)
data := decodeContentObject(t, rec)["data"].(map[string]any)
if data["servings"] != float64(2) {
t.Errorf("expected servings 2, got %v", data["servings"])
}
if value, present := data["published_on"]; !present || value != nil {
t.Errorf("expected published_on null, got %v", data)
}
})
t.Run("Creating an entry that breaks the schema is refused and stores nothing", func(t *testing.T) {
wrap := func(data string) string { return `{"data": ` + data + `}` }
examples := []struct {
body string
status int
message string
}{
{"not-json", 400, apperr.BodyErrorMessage},
{"{}", 400, apperr.BodyErrorMessage},
{`{"data": "x"}`, 400, apperr.BodyErrorMessage},
{wrap(`{"difficulty": "easy"}`), 422, "invalid_entry: title: required"},
{wrap(`{"title": null, "difficulty": "easy"}`), 422, "invalid_entry: title: required"},
{wrap(`{"title": 5, "difficulty": "easy"}`), 422, "invalid_entry: title: type"},
{wrap(`{"title": "ab", "difficulty": "easy"}`), 422, "invalid_entry: title: min"},
{wrap(`{"title": "` + strings.Repeat("é", 81) + `", "difficulty": "easy"}`), 422, "invalid_entry: title: max"},
{wrap(`{"title": "Soup", "difficulty": "extreme"}`), 422, "invalid_entry: difficulty: options"},
{wrap(`{"title": "Soup", "difficulty": "easy", "servings": 0}`), 422, "invalid_entry: servings: min"},
{wrap(`{"title": "Soup", "difficulty": "easy", "servings": 51}`), 422, "invalid_entry: servings: max"},
{wrap(`{"title": "Soup", "difficulty": "easy", "servings": "4"}`), 422, "invalid_entry: servings: type"},
{wrap(`{"title": "Soup", "difficulty": "easy", "vegetarian": "yes"}`), 422, "invalid_entry: vegetarian: type"},
{wrap(`{"title": "Soup", "difficulty": "easy", "published_on": "2026-02-30"}`), 422, "invalid_entry: published_on: type"},
{wrap(`{"title": "Soup", "difficulty": "easy", "published_on": "2026-02-01T10:00:00Z"}`), 422, "invalid_entry: published_on: type"},
{wrap(`{"title": "Soup", "difficulty": "easy", "notes": "` + strings.Repeat("n", 501) + `"}`), 422, "invalid_entry: notes: max"},
{wrap(`{"title": "Soup", "difficulty": "easy", "colour": "red"}`), 422, "invalid_entry: colour: unknown_field"},
}
for index, example := range examples {
t.Run(strconv.Itoa(index)+" "+example.message, func(t *testing.T) {
env := newContentTypeEnv(t)
env.createType(t, "recipe", recipeFields())
rec := env.as(t, ctAdminId, http.MethodPost, "/v1/content-type/recipe/entry", example.body)
expectStatusAndBody(t, rec, example.status, example.message)
if len(env.entries.entries) != 0 {
t.Errorf("expected no entry")
}
})
}
})
t.Run("Boundary values are accepted", func(t *testing.T) {
bodies := []string{
`{"title": "abc", "difficulty": "easy"}`,
`{"title": "` + strings.Repeat("é", 80) + `", "difficulty": "easy"}`,
`{"title": "Soup one", "difficulty": "easy", "servings": 1}`,
`{"title": "Soup two", "difficulty": "easy", "servings": 50}`,
`{"title": "Soup three", "difficulty": "easy", "published_on": "2026-02-28"}`,
}
env := newContentTypeEnv(t)
env.createType(t, "recipe", recipeFields())
for _, data := range bodies {
expectStatusAndBody(t, env.createEntry(t, "recipe", ctAdminId, data), http.StatusCreated, "")
}
})
}
func TestUniqueEntryValues(t *testing.T) {
t.Run("Unique fields reject duplicates and ignore the entry itself", func(t *testing.T) {
env := newContentTypeEnv(t)
env.createType(t, "recipe", recipeFields())
env.createEntry(t, "recipe", ctAdminId, `{"title": "Pad thai", "difficulty": "easy"}`)
duplicate := env.createEntry(t, "recipe", ctAdminId, `{"title": "Pad thai", "difficulty": "easy"}`)
same := env.admin(t, http.MethodPut, "/v1/content-type/recipe/entry/1", `{"data": {"title": "Pad thai", "difficulty": "easy", "servings": 6}}`)
expectStatusAndBody(t, duplicate, http.StatusConflict, "invalid_entry: title: unique")
expectStatusAndBody(t, same, http.StatusOK, "")
})
t.Run("Unique values are scoped to their content type and ignore nulls", func(t *testing.T) {
env := newContentTypeEnv(t)
env.createType(t, "recipe", recipeFields())
env.createType(t, "dish", dishFields())
expectStatusAndBody(t, env.createEntry(t, "dish", ctAdminId, `{"title": "Pad thai"}`), http.StatusCreated, "")
expectStatusAndBody(t, env.createEntry(t, "recipe", ctAdminId, `{"title": "Pad thai", "difficulty": "easy"}`), http.StatusCreated, "")
expectStatusAndBody(t, env.createEntry(t, "dish", ctAdminId, `{"title": "Soup"}`), http.StatusCreated, "")
expectStatusAndBody(t, env.createEntry(t, "dish", ctAdminId, `{"title": "Stew", "slug": null}`), http.StatusCreated, "")
})
}
func TestReadingAndChangingEntries(t *testing.T) {
t.Run("Getting an entry", func(t *testing.T) {
env := newContentTypeEnv(t)
env.createType(t, "recipe", recipeFields())
env.createType(t, "dish", dishFields())
env.createEntry(t, "recipe", ctAdminId, `{"title": "Pad thai", "difficulty": "easy"}`)
found := env.as(t, ctMemberId, http.MethodGet, "/v1/content-type/recipe/entry/1", "")
scoped := env.as(t, ctMemberId, http.MethodGet, "/v1/content-type/dish/entry/1", "")
expectStatusAndBody(t, found, http.StatusOK, "")
if !reflect.DeepEqual(objectKeys(decodeContentObject(t, found)), entryKeys) {
t.Errorf("unexpected body %s", found.Body.String())
}
expectStatusAndBody(t, scoped, http.StatusNotFound, apperr.EntryNotFoundErrorMessage)
})
t.Run("Entry routes with a bad id or a missing resource", func(t *testing.T) {
valid := `{"data": {"title": "Pad thai", "difficulty": "easy"}}`
examples := []struct {
method, path, body string
status int
message string
}{
{http.MethodGet, "/v1/content-type/recipe/entry/abc", "", 400, apperr.IdUint32ErrorMessage},
{http.MethodGet, "/v1/content-type/recipe/entry/-1", "", 400, apperr.IdUint32ErrorMessage},
{http.MethodGet, "/v1/content-type/recipe/entry/4294967296", "", 400, apperr.IdUint32ErrorMessage},
{http.MethodGet, "/v1/content-type/recipe/entry/999", "", 404, apperr.EntryNotFoundErrorMessage},
{http.MethodPut, "/v1/content-type/recipe/entry/999", valid, 404, apperr.EntryNotFoundErrorMessage},
{http.MethodDelete, "/v1/content-type/recipe/entry/999", "", 404, apperr.EntryNotFoundErrorMessage},
{http.MethodGet, "/v1/content-type/nope/entry/1", "", 404, apperr.ContentTypeNotFoundErrorMessage},
{http.MethodPost, "/v1/content-type/nope/entry", valid, 404, apperr.ContentTypeNotFoundErrorMessage},
{http.MethodGet, "/v1/content-type/nope/entry", "", 404, apperr.ContentTypeNotFoundErrorMessage},
}
for _, example := range examples {
t.Run(example.method+" "+example.path, func(t *testing.T) {
env := newContentTypeEnv(t)
env.createType(t, "recipe", recipeFields())
rec := env.as(t, ctMemberId, example.method, example.path, example.body)
expectStatusAndBody(t, rec, example.status, example.message)
})
}
})
t.Run("Replacing an entry validates the whole document and keeps provenance", func(t *testing.T) {
env := newContentTypeEnv(t)
env.createType(t, "recipe", recipeFields())
env.createEntry(t, "recipe", ctAdminId, `{"title": "Pad thai", "difficulty": "easy"}`)
env.clock = env.clock.Add(time.Hour)
rec := env.as(t, ctOwnerId, http.MethodPut, "/v1/content-type/recipe/entry/1", `{"data": {"title": "Green curry", "difficulty": "medium"}}`)
expectStatusAndBody(t, rec, http.StatusOK, "")
body := decodeContentObject(t, rec)
want := map[string]any{"title": "Green curry", "difficulty": "medium"}
if !reflect.DeepEqual(body["data"], want) || body["created_by"] != float64(2) || body["updated_by"] != float64(1) || body["updated_at"] == body["created_at"] {
t.Errorf("unexpected body %v", body)
}
refused := env.as(t, ctOwnerId, http.MethodPut, "/v1/content-type/recipe/entry/1", `{"data": {"difficulty": "medium"}}`)
expectStatusAndBody(t, refused, http.StatusUnprocessableEntity, "invalid_entry: title: required")
if env.entries.entries[1].Data["title"] != "Green curry" {
t.Errorf("expected the entry to be unchanged")
}
})
t.Run("Deleting an entry", func(t *testing.T) {
env := newContentTypeEnv(t)
env.createType(t, "recipe", recipeFields())
env.createEntry(t, "recipe", ctAdminId, `{"title": "Pad thai", "difficulty": "easy"}`)
rec := env.admin(t, http.MethodDelete, "/v1/content-type/recipe/entry/1", "")
expectStatusAndBody(t, rec, http.StatusNoContent, "")
expectStatusAndBody(t, env.admin(t, http.MethodGet, "/v1/content-type/recipe/entry/1", ""), http.StatusNotFound, apperr.EntryNotFoundErrorMessage)
})
}
func TestListingEntries(t *testing.T) {
seed := func(t *testing.T) *contentTypeEnv {
env := newContentTypeEnv(t)
env.createType(t, "recipe", recipeFields())
env.createType(t, "dish", dishFields())
for index := 1; index <= 30; index++ {
title := "Recipe " + strconv.Itoa(1000+index)
expectStatusAndBody(t, env.createEntry(t, "recipe", ctAdminId, `{"title": "`+title+`", "difficulty": "easy"}`), http.StatusCreated, "")
}
env.createEntry(t, "dish", ctAdminId, `{"title": "Dish one"}`)
return env
}
examples := []struct {
query string
status int
items int
total int
page int
size int
firstId int
lastId int
badQuery bool
}{
{"", 200, 25, 30, 1, 25, 30, 6, false},
{"?page=2", 200, 5, 30, 2, 25, 5, 1, false},
{"?size=5&page=2", 200, 5, 30, 2, 5, 25, 21, false},
{"?sort=id:asc", 200, 25, 30, 1, 25, 1, 25, false},
{"?sort=created_at:desc", 200, 25, 30, 1, 25, 30, 6, false},
{"?page=99", 200, 0, 30, 99, 25, 0, 0, false},
{"?page=1000000", 200, 0, 30, 1000000, 25, 0, 0, false},
{"?page=1000001", 400, 0, 0, 0, 0, 0, 0, true},
{"?page=0", 400, 0, 0, 0, 0, 0, 0, true},
{"?size=7", 400, 0, 0, 0, 0, 0, 0, true},
{"?sort=data:asc", 400, 0, 0, 0, 0, 0, 0, true},
{"?page=abc", 400, 0, 0, 0, 0, 0, 0, true},
}
t.Run("Listing entries is paginated and sortable", func(t *testing.T) {
for _, example := range examples {
t.Run(example.query, func(t *testing.T) {
env := seed(t)
rec := env.as(t, ctMemberId, http.MethodGet, "/v1/content-type/recipe/entry"+example.query, "")
if example.badQuery {
expectStatusAndBody(t, rec, example.status, apperr.BodyErrorMessage)
return
}
expectStatusAndBody(t, rec, example.status, "")
body := decodeContentObject(t, rec)
items := body["items"].([]any)
if len(items) != example.items || body["total"] != float64(example.total) || body["page"] != float64(example.page) || body["size"] != float64(example.size) {
t.Fatalf("unexpected page %v", body)
}
if len(items) > 0 {
first := int(items[0].(map[string]any)["id"].(float64))
last := int(items[len(items)-1].(map[string]any)["id"].(float64))
if first != example.firstId || last != example.lastId {
t.Errorf("expected ids %d..%d, got %d..%d", example.firstId, example.lastId, first, last)
}
}
})
}
})
t.Run("An empty content type lists no entries", func(t *testing.T) {
env := newContentTypeEnv(t)
env.createType(t, "event", dishFields())
rec := env.admin(t, http.MethodGet, "/v1/content-type/event/entry", "")
expectStatusAndBody(t, rec, http.StatusOK, `{"items":[],"total":0,"page":1,"size":25}`)
})
}
func TestEntryRouteAccess(t *testing.T) {
examples := []struct {
caller string
userId uint32
viaKey bool
status int
}{
{"an admin cookie", ctAdminId, false, 201},
{"an owner cookie", ctOwnerId, false, 201},
{"an active API key of admin 2", 0, true, 201},
{"no credentials", 0, false, 401},
{"a cookie for unverified 4", ctUnverifiedId, false, 403},
{"a stale token_version cookie", ctStaleId, false, 401},
}
t.Run("Entry routes accept any verified user and API keys, and refuse everyone else", func(t *testing.T) {
for _, example := range examples {
t.Run(example.caller, func(t *testing.T) {
env := newContentTypeEnv(t)
env.createType(t, "recipe", recipeFields())
body := `{"data": {"title": "Pad thai", "difficulty": "easy"}}`
rec := env.request(t, http.MethodPost, "/v1/content-type/recipe/entry", body, func(req *http.Request) {
env.asUser(t, example.userId)(req)
if example.viaKey {
req.Header.Set("Authorization", "Bearer "+env.issueKey(ctAdminId))
}
})
if rec.Code != example.status {
t.Errorf("expected %d, got %d %q", example.status, rec.Code, rec.Body.String())
}
})
}
})
t.Run("Built-in resources are not reachable through the generic engine", func(t *testing.T) {
env := newContentTypeEnv(t)
env.createType(t, "article", dishFields())
rec := env.admin(t, http.MethodGet, "/v1/content-type/article/entry", "")
expectStatusAndBody(t, rec, http.StatusOK, `{"items":[],"total":0,"page":1,"size":25}`)
})
}
+661
View File
@@ -0,0 +1,661 @@
package test
import (
"RenewCMS/internal/domain/contenttype"
"RenewCMS/internal/domain/entry"
"RenewCMS/internal/infrastructure/persistence/database"
"RenewCMS/internal/infrastructure/persistence/mappers"
persistence "RenewCMS/internal/infrastructure/persistence/repositories"
"RenewCMS/internal/infrastructure/useCases"
"encoding/json"
"errors"
"fmt"
"math/rand"
"reflect"
"sort"
"strings"
"testing"
"time"
"gorm.io/gorm"
)
func recipeSchema(t *testing.T) []contenttype.Field {
t.Helper()
min3, max80, min1, max50, max500 := float64(3), float64(80), float64(1), float64(50), float64(500)
fields, err := contenttype.ValidateFields([]contenttype.Field{
{Key: "title", Label: "Title", Type: contenttype.TypeText, Required: true, Unique: true, Min: min3, Max: max80},
{Key: "servings", Label: "Servings", Type: contenttype.TypeNumber, Default: float64(4), Min: min1, Max: max50},
{Key: "vegetarian", Label: "Vegetarian", Type: contenttype.TypeBoolean, Default: false},
{Key: "published_on", Label: "Published on", Type: contenttype.TypeDate},
{Key: "difficulty", Label: "Difficulty", Type: contenttype.TypeSelect, Required: true, Options: []string{"easy", "medium", "hard"}},
{Key: "notes", Label: "Notes", Type: contenttype.TypeRichText, Max: max500},
})
if err != nil {
t.Fatalf("sample schema: %v", err)
}
return fields
}
type contentTypeFixture struct {
types *mockContentTypeRepo
entries *mockEntryRepo
now func() time.Time
}
func newContentTypeFixture(t *testing.T) (*contentTypeFixture, contenttype.ContentType) {
t.Helper()
entries := newMockEntryRepo()
fixture := &contentTypeFixture{types: newMockContentTypeRepo(), entries: entries, now: func() time.Time { return time.Date(2026, time.October, 5, 9, 0, 0, 0, time.UTC) }}
stored, _ := fixture.types.Create(contenttype.ContentType{Key: "recipe", Name: "Recipe", Fields: recipeSchema(t)})
fixture.types.createCalls = 0
return fixture, stored
}
func TestCreateEntryUseCase(t *testing.T) {
t.Run("Use case: validating an entry against a schema returns domain sentinels", func(t *testing.T) {
breaking := []map[string]any{
{"difficulty": "easy"},
{"title": 5, "difficulty": "easy"},
{"title": "ab", "difficulty": "easy"},
{"title": "Soup", "difficulty": "extreme"},
{"title": "Soup", "difficulty": "easy", "servings": 0.0},
{"title": "Soup", "difficulty": "easy", "colour": "red"},
}
for _, data := range breaking {
fixture, _ := newContentTypeFixture(t)
create := useCases.NewCreateEntryUseCase(fixture.types, fixture.entries, fixture.now)
_, err := create.Create(useCases.CreateEntryCommand{ContentTypeKey: "recipe", Data: data, UserID: 2})
if !errors.Is(err, entry.ErrInvalidEntry) || fixture.entries.createCalls != 0 {
t.Errorf("data %v: err %v, creates %d", data, err, fixture.entries.createCalls)
}
}
})
t.Run("Use case: a duplicate unique value returns ErrUniqueViolation", func(t *testing.T) {
fixture, _ := newContentTypeFixture(t)
create := useCases.NewCreateEntryUseCase(fixture.types, fixture.entries, fixture.now)
data := func() map[string]any { return map[string]any{"title": "Pad thai", "difficulty": "easy"} }
if _, err := create.Create(useCases.CreateEntryCommand{ContentTypeKey: "recipe", Data: data(), UserID: 2}); err != nil {
t.Fatalf("first create: %v", err)
}
_, err := create.Create(useCases.CreateEntryCommand{ContentTypeKey: "recipe", Data: data(), UserID: 2})
if !errors.Is(err, entry.ErrUniqueViolation) || fixture.entries.createCalls != 1 {
t.Errorf("err %v, creates %d", err, fixture.entries.createCalls)
}
})
t.Run("Use case: the injected clock stamps the entry", func(t *testing.T) {
fixture, _ := newContentTypeFixture(t)
create := useCases.NewCreateEntryUseCase(fixture.types, fixture.entries, fixture.now)
created, err := create.Create(useCases.CreateEntryCommand{ContentTypeKey: "recipe", Data: map[string]any{"title": "Pad thai", "difficulty": "easy"}, UserID: 2})
if err != nil || !created.CreatedAt.Equal(fixture.now()) || !created.UpdatedAt.Equal(fixture.now()) || created.CreatedBy != 2 {
t.Errorf("unexpected %+v %v", created, err)
}
})
}
func TestUpdateContentTypeUseCase(t *testing.T) {
seedEntry := func(fixture *contentTypeFixture, stored contenttype.ContentType, data map[string]any) {
_, _ = fixture.entries.Create(entry.Entry{ContentTypeID: stored.ID, Data: data})
}
t.Run("Use case: schema updates re-validate stored entries", func(t *testing.T) {
fixture, stored := newContentTypeFixture(t)
seedEntry(fixture, stored, map[string]any{"title": "Pad thai", "difficulty": "easy"})
update := useCases.NewUpdateContentTypeUseCase(fixture.types, fixture.entries, fixture.now)
narrowed := recipeSchema(t)
narrowed[4].Options = []string{"hard"}
_, err := update.Update(useCases.UpdateContentTypeCommand{Key: "recipe", Name: "Recipe", Fields: narrowed})
if !errors.Is(err, contenttype.ErrSchemaIncompatible) || fixture.types.updateCalls != 0 {
t.Errorf("err %v, updates %d", err, fixture.types.updateCalls)
}
})
t.Run("Use case: a type change returns ErrInvalidField", func(t *testing.T) {
fixture, stored := newContentTypeFixture(t)
seedEntry(fixture, stored, map[string]any{"title": "Pad thai", "difficulty": "easy"})
update := useCases.NewUpdateContentTypeUseCase(fixture.types, fixture.entries, fixture.now)
retyped := recipeSchema(t)
retyped[0].Type = contenttype.TypeRichText
retyped[0].Unique = false
_, err := update.Update(useCases.UpdateContentTypeCommand{Key: "recipe", Name: "Recipe", Fields: retyped})
if !errors.Is(err, contenttype.ErrInvalidField) || fixture.types.updateCalls != 0 {
t.Errorf("err %v, updates %d", err, fixture.types.updateCalls)
}
})
t.Run("Use case: a compatible update stores the new name and fields", func(t *testing.T) {
fixture, _ := newContentTypeFixture(t)
update := useCases.NewUpdateContentTypeUseCase(fixture.types, fixture.entries, fixture.now)
updated, err := update.Update(useCases.UpdateContentTypeCommand{Key: "recipe", Name: "Dish", Fields: recipeSchema(t)[:2]})
if err != nil || updated.Name != "Dish" || len(updated.Fields) != 2 || updated.Key != "recipe" || !updated.UpdatedAt.Equal(fixture.now()) {
t.Errorf("unexpected %+v %v", updated, err)
}
})
}
func TestDeleteContentTypeUseCase(t *testing.T) {
t.Run("Use case: DeleteContentType with entries returns ErrHasEntries and nothing is deleted", func(t *testing.T) {
fixture, stored := newContentTypeFixture(t)
_, _ = fixture.entries.Create(entry.Entry{ContentTypeID: stored.ID, Data: map[string]any{}})
remove := useCases.NewDeleteContentTypeUseCase(fixture.types, fixture.entries)
err := remove.Delete("recipe")
if !errors.Is(err, contenttype.ErrHasEntries) || fixture.types.deleteCalls != 0 {
t.Errorf("err %v, deletes %d", err, fixture.types.deleteCalls)
}
})
}
func TestContentTypeDomainRules(t *testing.T) {
t.Run("Keys follow the slug rule and the length bounds", func(t *testing.T) {
accepted := []string{"ab", "recipe", "my-type-2", strings.Repeat("a", 40)}
refused := []string{"", "a", "Recipe", "my_type", "-ab", strings.Repeat("a", 41)}
for _, key := range accepted {
if err := contenttype.ValidateKey(key); err != nil {
t.Errorf("%q: %v", key, err)
}
}
for _, key := range refused {
if err := contenttype.ValidateKey(key); !errors.Is(err, contenttype.ErrInvalidKey) {
t.Errorf("%q: %v", key, err)
}
}
})
t.Run("Field values report the first broken rule", func(t *testing.T) {
fields := recipeSchema(t)
cases := []struct {
field int
value any
rule string
}{
{0, "abc", ""},
{0, 5.0, contenttype.RuleType},
{0, "ab", contenttype.RuleMin},
{1, 51.0, contenttype.RuleMax},
{2, "yes", contenttype.RuleType},
{3, "2026-02-28", ""},
{3, "2026-02-30", contenttype.RuleType},
{4, "hard", ""},
{4, "extreme", contenttype.RuleOptions},
}
for _, c := range cases {
if got := fields[c.field].Violation(c.value); got != c.rule {
t.Errorf("field %s value %v: got %q, want %q", fields[c.field].Key, c.value, got, c.rule)
}
}
})
t.Run("Defaults fill only absent keys and projection drops unknown keys", func(t *testing.T) {
fields := recipeSchema(t)
filled := entry.ApplyDefaults(fields, map[string]any{"published_on": nil, "servings": nil})
projected := entry.Project(fields, map[string]any{"title": "x", "gone": 1})
if !reflect.DeepEqual(filled, map[string]any{"published_on": nil, "servings": nil, "vegetarian": false}) {
t.Errorf("unexpected defaults %v", filled)
}
if !reflect.DeepEqual(projected, map[string]any{"title": "x"}) {
t.Errorf("unexpected projection %v", projected)
}
})
}
func TestContentTypePersistence(t *testing.T) {
t.Run("Content types and entries round-trip through the generic tables", func(t *testing.T) {
db := openUnmigratedSQLite(t)
if err := database.Migrate(db, migrationPublicURL); err != nil {
t.Fatalf("migrate: %v", err)
}
types := persistence.NewContentTypeRepository(db)
entries := persistence.NewEntryRepository(db)
created, err := types.Create(contenttype.ContentType{Key: "recipe", Name: "Recipe", Fields: recipeSchema(t)})
if err != nil {
t.Fatalf("create type: %v", err)
}
loaded, err := types.GetByKey("recipe")
if err != nil || loaded.ID != created.ID || !reflect.DeepEqual(loaded.Fields, recipeSchema(t)) {
t.Fatalf("round trip: %+v %v", loaded, err)
}
if _, err := types.GetByKey("nope"); !errors.Is(err, contenttype.ErrContentTypeNotFound) {
t.Errorf("expected not found, got %v", err)
}
first, _ := entries.Create(entry.Entry{ContentTypeID: created.ID, Data: map[string]any{"title": "Pad thai", "servings": 4.0}, CreatedBy: 2, UpdatedBy: 2})
_, _ = entries.Create(entry.Entry{ContentTypeID: created.ID, Data: map[string]any{"title": "Soup"}, CreatedBy: 2, UpdatedBy: 2})
_, _ = entries.Create(entry.Entry{ContentTypeID: created.ID + 1, Data: map[string]any{"title": "Pad thai"}})
page, err := entries.ListPage(entry.Filters{ContentTypeID: created.ID, Page: 1, Size: 1, Sort: entry.Sort{Field: entry.SortByID, Direction: entry.SortAsc}})
taken, _ := entries.FindByFieldValue(created.ID, "title", "Pad thai", 0)
self, _ := entries.FindByFieldValue(created.ID, "title", "Pad thai", first.ID)
count, _ := entries.CountByContentType(created.ID)
if err != nil || page.Total != 2 || len(page.Items) != 1 || page.Items[0].ID != first.ID || page.Items[0].Data["servings"] != 4.0 {
t.Errorf("unexpected page %+v %v", page, err)
}
if len(taken) != 1 || len(self) != 0 || count != 2 {
t.Errorf("taken %d self %d count %d", len(taken), len(self), count)
}
if _, err := entries.Get(created.ID+1, first.ID); !errors.Is(err, entry.ErrEntryNotFound) {
t.Errorf("expected scoped not found, got %v", err)
}
if err := types.Delete(created.ID); err != nil {
t.Errorf("delete: %v", err)
}
})
}
type nilListContentTypeRepo struct {
*mockContentTypeRepo
}
func (nilListContentTypeRepo) List() ([]contenttype.ContentType, error) {
return nil, nil
}
func TestListContentTypesUseCase(t *testing.T) {
t.Run("A repository failure is returned as is", func(t *testing.T) {
repo := newMockContentTypeRepo()
boom := errors.New("boom")
repo.fail.failNextWith("List", boom)
if found, err := useCases.NewListContentTypesUseCase(repo).List(); !errors.Is(err, boom) || found != nil {
t.Errorf("got %v %v", found, err)
}
})
t.Run("No content type yields an empty non-nil list", func(t *testing.T) {
found, err := useCases.NewListContentTypesUseCase(nilListContentTypeRepo{newMockContentTypeRepo()}).List()
if err != nil || found == nil || len(found) != 0 {
t.Errorf("got %#v %v", found, err)
}
})
}
func TestContentTypeSchemaBounds(t *testing.T) {
booleans := func(count int) []contenttype.Field {
fields := make([]contenttype.Field, 0, count)
for i := 0; i < count; i++ {
fields = append(fields, contenttype.Field{Key: fmt.Sprintf("f%d", i), Label: "Flag", Type: contenttype.TypeBoolean})
}
return fields
}
t.Run("A schema holds between 1 and 50 fields", func(t *testing.T) {
for count, accepted := range map[int]bool{0: false, 1: true, 50: true, 51: false} {
_, err := contenttype.ValidateFields(booleans(count))
if (err == nil) != accepted {
t.Errorf("%d fields: %v", count, err)
}
}
})
t.Run("Bounds may be equal but never inverted, and a zero length cap is whole", func(t *testing.T) {
cases := []struct {
min, max any
accepted bool
}{
{2.0, 2.0, true},
{3.0, 2.0, false},
{nil, 0.0, true},
{nil, -1.0, false},
{nil, 1.5, false},
}
for _, c := range cases {
_, err := contenttype.ValidateFields([]contenttype.Field{{Key: "title", Label: "Title", Type: contenttype.TypeText, Min: c.min, Max: c.max}})
if (err == nil) != c.accepted {
t.Errorf("min %v max %v: %v", c.min, c.max, err)
}
}
})
t.Run("Date bounds compare calendar days", func(t *testing.T) {
field := contenttype.Field{Key: "day", Label: "Day", Type: contenttype.TypeDate, Min: "2024-01-01", Max: "2024-01-02"}
cases := map[string]string{"2023-12-31": contenttype.RuleMin, "2024-01-01": "", "2024-01-02": "", "2024-01-03": contenttype.RuleMax}
for value, rule := range cases {
if got := field.Violation(value); got != rule {
t.Errorf("%s: %q", value, got)
}
}
})
}
func TestContentTypeRepositoryEdges(t *testing.T) {
open := func(t *testing.T) (*persistence.ContentTypeRepository, *persistence.EntryRepository, *gorm.DB) {
t.Helper()
db := openUnmigratedSQLite(t)
if err := database.Migrate(db, migrationPublicURL); err != nil {
t.Fatalf("migrate: %v", err)
}
return persistence.NewContentTypeRepository(db), persistence.NewEntryRepository(db), db
}
flag := []contenttype.Field{{Key: "flag", Label: "Flag", Type: contenttype.TypeBoolean}}
t.Run("Content types list by case-insensitive name and update by id", func(t *testing.T) {
types, _, _ := open(t)
if listed, err := types.List(); err != nil || len(listed) != 0 {
t.Fatalf("empty list: %v %v", listed, err)
}
_, _ = types.Create(contenttype.ContentType{Key: "zeta", Name: "zeta", Fields: flag})
beta, _ := types.Create(contenttype.ContentType{Key: "beta", Name: "Beta", Fields: flag})
_, _ = types.Create(contenttype.ContentType{Key: "alpha", Name: "Alpha", Fields: flag})
listed, err := types.List()
if err != nil || len(listed) != 3 || listed[0].Key != "alpha" || listed[1].Key != "beta" || listed[2].Key != "zeta" {
t.Fatalf("unexpected order %+v %v", listed, err)
}
beta.Name = "Gamma"
if _, err := types.Update(beta); err != nil {
t.Fatalf("update: %v", err)
}
reloaded, _ := types.GetByKey("beta")
if reloaded.Name != "Gamma" {
t.Errorf("name not updated: %q", reloaded.Name)
}
if _, err := types.Update(contenttype.ContentType{ID: 999, Name: "x", Fields: flag}); !errors.Is(err, contenttype.ErrContentTypeNotFound) {
t.Errorf("update missing: %v", err)
}
if err := types.Delete(999); !errors.Is(err, contenttype.ErrContentTypeNotFound) {
t.Errorf("delete missing: %v", err)
}
unmarshalable := []contenttype.Field{{Key: "flag", Label: "Flag", Type: contenttype.TypeBoolean, Default: make(chan int)}}
if _, err := types.Update(contenttype.ContentType{ID: beta.ID, Name: "x", Fields: unmarshalable}); err == nil {
t.Errorf("expected a marshal error")
}
if _, err := types.Create(contenttype.ContentType{Key: "chan", Name: "x", Fields: unmarshalable}); err == nil {
t.Errorf("expected a marshal error on create")
}
})
t.Run("Stored rows that cannot be decoded and a closed database are reported", func(t *testing.T) {
types, entries, db := open(t)
if err := db.Exec("INSERT INTO content_types (type_key, name, fields, created_at, updated_at) VALUES ('bad', 'Bad', 'not json', CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)").Error; err != nil {
t.Fatalf("seed: %v", err)
}
if _, err := types.List(); err == nil {
t.Errorf("expected a decode error from List")
}
if _, err := types.GetByKey("bad"); err == nil || errors.Is(err, contenttype.ErrContentTypeNotFound) {
t.Errorf("expected a decode error from GetByKey, got %v", err)
}
sqlDB, _ := db.DB()
_ = sqlDB.Close()
if _, err := types.List(); err == nil {
t.Errorf("expected a connection error from List")
}
if _, err := entries.CountByContentType(1); err == nil {
t.Errorf("expected a connection error from CountByContentType")
}
})
t.Run("Entries page, tie-break, update, delete and bulk delete per content type", func(t *testing.T) {
_, entries, _ := open(t)
same := time.Date(2026, 1, 2, 3, 4, 5, 0, time.UTC)
var ids []uint32
for _, title := range []string{"a", "b", "c"} {
created, err := entries.Create(entry.Entry{ContentTypeID: 1, Data: map[string]any{"title": title}, CreatedAt: same, UpdatedAt: same})
if err != nil {
t.Fatalf("create: %v", err)
}
ids = append(ids, created.ID)
}
other, _ := entries.Create(entry.Entry{ContentTypeID: 2, Data: map[string]any{"title": "z"}})
byCreated, err := entries.ListPage(entry.Filters{ContentTypeID: 1, Page: 1, Size: 10, Sort: entry.Sort{Field: entry.SortByCreatedAt, Direction: entry.SortAsc}})
if err != nil || len(byCreated.Items) != 3 || byCreated.Items[0].ID != ids[2] || byCreated.Items[1].ID != ids[1] || byCreated.Items[2].ID != ids[0] {
t.Errorf("ties must fall back to id desc: %+v %v", byCreated, err)
}
byID, _ := entries.ListPage(entry.Filters{ContentTypeID: 1, Page: 1, Size: 10, Sort: entry.Sort{Field: entry.SortByID, Direction: entry.SortDesc}})
if len(byID.Items) != 3 || byID.Items[0].ID != ids[2] || byID.Items[2].ID != ids[0] {
t.Errorf("id desc: %+v", byID)
}
second, _ := entries.ListPage(entry.Filters{ContentTypeID: 1, Page: 2, Size: 2, Sort: entry.Sort{Field: entry.SortByID, Direction: entry.SortAsc}})
if second.Total != 3 || len(second.Items) != 1 || second.Items[0].ID != ids[2] {
t.Errorf("page 2: %+v", second)
}
if _, err := entries.ListPage(entry.Filters{ContentTypeID: 1, Page: 1, Size: 2, Sort: entry.Sort{Field: "bogus", Direction: "sideways"}}); !errors.Is(err, entry.ErrInvalidSort) {
t.Errorf("unknown sort must be refused: %v", err)
}
if _, err := entries.ListPage(entry.Filters{ContentTypeID: 1, Page: entry.MaxPage + 1, Size: 100, Sort: entry.DefaultSort()}); !errors.Is(err, entry.ErrInvalidPage) {
t.Errorf("out of range page must be refused: %v", err)
}
if _, err := entries.ListPage(entry.Filters{ContentTypeID: 1, Page: entry.MaxPage, Size: 100, Sort: entry.DefaultSort()}); err != nil {
t.Errorf("max page must be accepted: %v", err)
}
unpaged, _ := entries.ListPage(entry.Filters{ContentTypeID: 1, Page: 1, Size: 1, Unpaged: true, Sort: entry.DefaultSort()})
if len(unpaged.Items) != 3 {
t.Errorf("unpaged: %+v", unpaged)
}
updated := byID.Items[0]
updated.Data = map[string]any{"title": "changed"}
updated.UpdatedBy = 9
if _, err := entries.Update(updated); err != nil {
t.Fatalf("update: %v", err)
}
reloaded, _ := entries.Get(1, updated.ID)
if reloaded.Data["title"] != "changed" || reloaded.UpdatedBy != 9 || reloaded.CreatedBy != 0 {
t.Errorf("update not persisted: %+v", reloaded)
}
if _, err := entries.Update(entry.Entry{ID: 999, Data: map[string]any{}}); !errors.Is(err, entry.ErrEntryNotFound) {
t.Errorf("update missing: %v", err)
}
if _, err := entries.Update(entry.Entry{ID: updated.ID, Data: map[string]any{"x": make(chan int)}}); err == nil {
t.Errorf("expected a marshal error on update")
}
if _, err := entries.Create(entry.Entry{ContentTypeID: 1, Data: map[string]any{"x": make(chan int)}}); err == nil {
t.Errorf("expected a marshal error on create")
}
if err := entries.Delete(2, ids[0]); !errors.Is(err, entry.ErrEntryNotFound) {
t.Errorf("scoped delete: %v", err)
}
if err := entries.Delete(1, ids[0]); err != nil {
t.Errorf("delete: %v", err)
}
if err := entries.DeleteByContentType(1); err != nil {
t.Errorf("bulk delete: %v", err)
}
left, _ := entries.ListPage(entry.Filters{ContentTypeID: 1, Page: 1, Size: 10, Sort: entry.DefaultSort()})
kept, err := entries.Get(2, other.ID)
if left.Total != 0 || err != nil || kept.ID != other.ID {
t.Errorf("bulk delete scope: %+v %v", left, err)
}
})
}
func TestEntrySortRules(t *testing.T) {
t.Run("Only the whitelisted field and direction pairs parse", func(t *testing.T) {
accepted := []string{"id:asc", "id:desc", "created_at:asc", "created_at:desc", "updated_at:asc", "updated_at:desc"}
for _, value := range accepted {
parsed, err := entry.ParseSort(value)
if err != nil || parsed.String() != value || !parsed.Valid() {
t.Errorf("%q: %v %v", value, parsed, err)
}
}
refused := []string{"", "id", "id:", ":asc", "data:asc", "id:up", "id:asc:x", "ID:asc", "id:ASC"}
for _, value := range refused {
if _, err := entry.ParseSort(value); !errors.Is(err, entry.ErrInvalidSort) {
t.Errorf("%q: %v", value, err)
}
}
if entry.DefaultSort().String() != "updated_at:desc" || !entry.DefaultSort().Valid() {
t.Errorf("unexpected default sort %v", entry.DefaultSort())
}
if (entry.Sort{Field: entry.SortByID}).Valid() || (entry.Sort{Direction: entry.SortAsc}).Valid() {
t.Errorf("half specified sorts must be invalid")
}
})
t.Run("The order clause is always one of the fixed strings", func(t *testing.T) {
fixed := map[string]bool{
"id ASC": true, "id DESC": true,
"created_at ASC, id DESC": true, "created_at DESC, id DESC": true,
"updated_at ASC, id DESC": true, "updated_at DESC, id DESC": true,
}
random := rand.New(rand.NewSource(7))
alphabet := []rune("abcdeitmpuxyz_:; -'\"()DROPTABLE0123")
generated := []string{"id; DROP TABLE entries", "id", "created_at", "asc", "desc", "", "id ASC"}
for range 500 {
length := random.Intn(24)
runes := make([]rune, length)
for position := range runes {
runes[position] = alphabet[random.Intn(len(alphabet))]
}
generated = append(generated, string(runes))
}
fields := append([]string{"id", "created_at", "updated_at"}, generated...)
directions := append([]string{"asc", "desc"}, generated...)
valid := 0
for _, field := range fields {
for _, direction := range directions[:12] {
clause, err := persistence.EntryOrderClause(entry.Sort{Field: entry.SortField(field), Direction: entry.SortDirection(direction)})
if err != nil {
if clause != "" || !errors.Is(err, entry.ErrInvalidSort) {
t.Fatalf("%q %q: %q %v", field, direction, clause, err)
}
continue
}
valid++
if !fixed[clause] {
t.Fatalf("%q %q produced %q", field, direction, clause)
}
}
}
if valid < 6 {
t.Errorf("expected the 6 valid combinations, got %d", valid)
}
for _, field := range generated {
for _, direction := range []string{"asc", "desc"} {
clause, err := persistence.EntryOrderClause(entry.Sort{Field: entry.SortField(field), Direction: entry.SortDirection(direction)})
if err == nil && !fixed[clause] {
t.Fatalf("%q %q produced %q", field, direction, clause)
}
}
}
})
}
func TestEntryPagingAndEquality(t *testing.T) {
t.Run("Pages beyond the maximum are refused by the use case", func(t *testing.T) {
fixture, _ := newContentTypeFixture(t)
list := useCases.NewListEntriesUseCase(fixture.types, fixture.entries)
cases := []struct {
page, size int
sort entry.Sort
err error
}{
{entry.MaxPage, 100, entry.DefaultSort(), nil},
{entry.MaxPage + 1, 25, entry.DefaultSort(), entry.ErrInvalidPage},
{1, 101, entry.DefaultSort(), entry.ErrInvalidPage},
{1, 25, entry.Sort{Field: "id"}, entry.ErrInvalidSort},
{1, 25, entry.Sort{}, entry.ErrInvalidSort},
}
for _, c := range cases {
_, err := list.ListPage(useCases.ListEntriesCommand{ContentTypeKey: "recipe", Page: c.page, Size: c.size, Sort: c.sort})
if !errors.Is(err, c.err) {
t.Errorf("page %d size %d sort %v: %v", c.page, c.size, c.sort, err)
}
}
})
t.Run("Values are equal when they decode to the same JSON value", func(t *testing.T) {
if !entry.SameValue("a", "a") || !entry.SameValue(4.0, 4.0) || !entry.SameValue(true, true) {
t.Errorf("equal values must match")
}
if entry.SameValue("a", "b") || entry.SameValue(4.0, "4") || entry.SameValue(nil, "") || entry.SameValue(1.0, 2.0) {
t.Errorf("different values must not match")
}
})
}
func TestContentTypeNameRule(t *testing.T) {
t.Run("A name is required after trimming and holds at most 100 characters", func(t *testing.T) {
cases := map[string]bool{"": false, " ": false, "\t\n": false, "a": true, " a ": true, strings.Repeat("é", 100): true, strings.Repeat("é", 101): false}
for name, accepted := range cases {
if err := contenttype.ValidateName(name); (err == nil) != accepted || (err != nil && !errors.Is(err, contenttype.ErrInvalidName)) {
t.Errorf("%q: %v", name, err)
}
}
})
t.Run("The use cases enforce it for non-HTTP callers", func(t *testing.T) {
fixture, existing := newContentTypeFixture(t)
create := useCases.NewCreateContentTypeUseCase(fixture.types, fixture.now)
update := useCases.NewUpdateContentTypeUseCase(fixture.types, fixture.entries, fixture.now)
if _, err := create.Create(useCases.CreateContentTypeCommand{Key: "fresh", Name: " ", Fields: existing.Fields}); !errors.Is(err, contenttype.ErrInvalidName) {
t.Errorf("create blank: %v", err)
}
if _, err := create.Create(useCases.CreateContentTypeCommand{Key: "fresh", Name: strings.Repeat("n", 101), Fields: existing.Fields}); !errors.Is(err, contenttype.ErrInvalidName) {
t.Errorf("create long: %v", err)
}
if _, err := update.Update(useCases.UpdateContentTypeCommand{Key: existing.Key, Name: " ", Fields: existing.Fields}); !errors.Is(err, contenttype.ErrInvalidName) {
t.Errorf("update blank: %v", err)
}
if _, err := update.Update(useCases.UpdateContentTypeCommand{Key: existing.Key, Name: strings.Repeat("n", 101), Fields: existing.Fields}); !errors.Is(err, contenttype.ErrInvalidName) {
t.Errorf("update long: %v", err)
}
if len(fixture.types.types) != 1 {
t.Errorf("nothing may be stored: %d", len(fixture.types.types))
}
})
}
func TestContentTypeStoredFormat(t *testing.T) {
t.Run("The stored field JSON keeps its exact key set", func(t *testing.T) {
model, err := mappers.ContentTypeToModel(contenttype.ContentType{Key: "recipe", Name: "Recipe", Fields: []contenttype.Field{{Key: "title", Label: "Title", Type: contenttype.TypeText}}})
if err != nil {
t.Fatalf("map: %v", err)
}
var stored []map[string]any
if err := json.Unmarshal([]byte(model.Fields), &stored); err != nil || len(stored) != 1 {
t.Fatalf("decode: %v %v", stored, err)
}
keys := make([]string, 0, len(stored[0]))
for key := range stored[0] {
keys = append(keys, key)
}
sort.Strings(keys)
expected := []string{"default", "key", "label", "max", "min", "options", "required", "type", "unique"}
if !reflect.DeepEqual(keys, expected) {
t.Errorf("stored keys %v", keys)
}
})
t.Run("A duplicate content type key surfaces as the key taken sentinel", func(t *testing.T) {
db := openUnmigratedSQLite(t)
if err := database.Migrate(db, migrationPublicURL); err != nil {
t.Fatalf("migrate: %v", err)
}
types := persistence.NewContentTypeRepository(db)
flag := []contenttype.Field{{Key: "flag", Label: "Flag", Type: contenttype.TypeBoolean}}
if _, err := types.Create(contenttype.ContentType{Key: "recipe", Name: "Recipe", Fields: flag}); err != nil {
t.Fatalf("first create: %v", err)
}
if _, err := types.Create(contenttype.ContentType{Key: "recipe", Name: "Again", Fields: flag}); !errors.Is(err, contenttype.ErrKeyTaken) {
t.Errorf("expected key taken, got %v", err)
}
other, _ := types.Create(contenttype.ContentType{Key: "dish", Name: "Dish", Fields: flag})
if err := db.Exec("DROP TABLE content_types").Error; err != nil {
t.Fatalf("drop: %v", err)
}
if _, err := types.Create(contenttype.ContentType{Key: "other", Name: "Other", Fields: flag}); err == nil || errors.Is(err, contenttype.ErrKeyTaken) {
t.Errorf("other failures must pass through: %v", err)
}
if _, err := types.Update(other); err == nil || errors.Is(err, contenttype.ErrKeyTaken) {
t.Errorf("other update failures must pass through: %v", err)
}
})
}
+1 -1
View File
@@ -216,7 +216,7 @@ func assertSiteColumnAdded(t *testing.T, db *gorm.DB) {
}
func isNewTableObject(name string) bool {
for _, prefix := range []string{"audit_", "idx_audit_", "image_variant", "idx_image_variant", "idx_images_path", "idx_sites_key", "sites", "authors", "idx_authors_", "article_authors", "idx_article_authors_"} {
for _, prefix := range []string{"audit_", "idx_audit_", "image_variant", "idx_image_variant", "idx_images_path", "idx_sites_key", "sites", "authors", "idx_authors_", "article_authors", "idx_article_authors_", "content_types", "idx_content_types_", "entries", "idx_entries_"} {
if strings.HasPrefix(name, prefix) {
return true
}
+15
View File
@@ -34,6 +34,7 @@ func (s *stubHasher) Compare(hashed string, value string) error {
type mockUserRepo struct {
users map[uint32]user.User
nextID uint32
findByIDsCalls int
fail failSwitch
clearVerificationCodeCalls int
clearVerificationCodeUserIds []uint32
@@ -112,6 +113,20 @@ func (m *mockUserRepo) GetAll() []user.User {
return result
}
func (m *mockUserRepo) FindByIDs(ids []uint32) ([]user.User, error) {
if err := m.fail.trigger("FindByIDs"); err != nil {
return nil, err
}
m.findByIDsCalls++
found := []user.User{}
for _, id := range ids {
if stored, exists := m.users[id]; exists {
found = append(found, stored)
}
}
return found, nil
}
func (m *mockUserRepo) Create(u user.User) (user.User, error) {
if err := m.fail.trigger("Create"); err != nil {
return user.User{}, err