Compare commits
14
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ad5faf3d19 | ||
|
|
89051b3f1f | ||
|
|
fba20f83c5 | ||
|
|
91d916fb74 | ||
|
|
b4cbcb0395 | ||
|
|
5404291af2 | ||
|
|
76e9e1220c | ||
|
|
8e344b2500 | ||
|
|
083cc9e23e | ||
|
|
f514146fed | ||
|
|
3c67cd2314 | ||
|
|
73a75d5cb9 | ||
|
|
e6e088c963 | ||
|
|
58d58f5a04 |
No files matched your search
@@ -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 |
|
||||
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
@@ -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"
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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))
|
||||
|
||||
@@ -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.
|
||||
@@ -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.
|
||||
@@ -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)
|
||||
|
||||
|
||||
@@ -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 | |
|
||||
@@ -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.
|
||||
@@ -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 |
|
||||
@@ -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 |
|
||||
@@ -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 |
|
||||
@@ -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 |
|
||||
@@ -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="{"theme":{"editor":"enum","default":"light","options":["system","light","dark"],"tsType":"string"}}">
|
||||
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-sel': '#e8dfd1', '--rc-on-sel': '#111111', '--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-sel': '#222222', '--rc-on-sel': '#fafafa', '--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>
|
||||
@@ -0,0 +1,428 @@
|
||||
<!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="{"$preview":{"width":1440,"height":900},"s":{"editor":null,"tsType":"object"},"mobile":{"editor":null,"tsType":"boolean"}}">
|
||||
class Component extends DCLogic {
|
||||
renderVals() {
|
||||
const s = this.props.s || {}, m = !!this.props.mobile
|
||||
const P = t => Object.fromEntries(t.split(';').filter(x => x.trim()).map(x => { const i = x.indexOf(':'); const k = x.slice(0, i).trim(); return [k.startsWith('--') ? k : k.replace(/-([a-z])/g, (_, c) => c.toUpperCase()), x.slice(i + 1).trim()] }))
|
||||
const h = React.createElement
|
||||
const D = (t, ...c) => h('div', { style: P(t) }, ...c)
|
||||
const S = (t, ...c) => h('span', { style: P(t) }, ...c)
|
||||
const I = (n, z = 16, t = '') => h('span', { 'aria-hidden': 'true', style: { display: 'inline-block', flexShrink: 0, width: z, height: z, backgroundColor: 'currentColor', WebkitMask: 'url("https://api.iconify.design/lucide/' + n + '.svg") center / contain no-repeat', mask: 'url("https://api.iconify.design/lucide/' + n + '.svg") center / contain no-repeat', ...(t ? P(t) : {}) } })
|
||||
const 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 SwR = (on, lab, help, dis) => D('display:flex;gap:16px;align-items:center;justify-content:space-between;padding:12px 0;border-bottom:1px solid var(--ui-border);opacity:' + (dis ? 0.6 : 1), D('display:flex;flex-direction:column;gap:2px;min-width:0', 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)), S('width:32px;height:18px;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)')))
|
||||
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' ? null : 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;min-width:0;border-top:1px solid var(--ui-border)', SwR(!!f.req, 'Required', 'An entry can\'t be saved with this field empty.'), SwR(!!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), t === 'boolean' && SwR(!!f.def, 'On by default', 'New entries start with this switch ' + (f.def ? 'on' : 'off') + ' when the field is left out.'))
|
||||
const right = hasMM ? [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.' }), defCtl] : [defCtl, 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. Starts with a letter. 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))),
|
||||
left,
|
||||
D('display:grid;grid-template-columns:' + g2 + ';gap:14px;align-items:start', ...right.filter(Boolean)),
|
||||
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-sel)' : 'var(--ui-bg)') + ';color:' + (on ? 'var(--rc-on-sel)' : '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-sel)' : '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'), D('display:flex;align-items:center;gap:6px;min-width:0', S(mono + 'font-size:12px;line-height:16px;color:' + (on ? 'var(--rc-on-sel)' : 'var(--ui-text-muted)') + ';overflow:hidden;text-overflow:ellipsis;white-space:nowrap;min-width:0;flex:0 1 auto', f.key || '–'), f.isNew && Bd('New', 'neu'), f.changed && Bd('Changed', 'chg'), !on && o.cause && f.changed && Bd('Possible cause', 'warn', 'triangle-alert'), f.req && h('span', { title: 'Required', 'aria-label': 'Required', style: { display: 'flex', flexShrink: 0 } }, Bd('R', 'req')), f.uniq && h('span', { title: 'Unique', 'aria-label': 'Unique', style: { display: 'flex', flexShrink: 0 } }, Bd('U', 'uniq')))),
|
||||
err && !on && I('circle-alert', 16, 'color:var(--ui-error);flex-shrink:0;margin:0 4px'), 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 === 'fkey') { fl = [...EV, { key: '2nd-date', label: 'Second date', type: 'date', isNew: true, err: { key: 'Start with a letter. Use lowercase letters, digits and underscores.' } }]; sel = 7; 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. Lowercase letters, digits and hyphens. 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:flex-start;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:320px', keyF), D('flex:1'), D('display:flex;align-items:center;gap:12px;height:32px;margin-top:26px', 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>
|
||||
@@ -0,0 +1,176 @@
|
||||
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. 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'),
|
||||
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('Field key error', N, '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.', { v: 'builder', k: 'fkey' }, 'Key · Start with a letter. Use lowercase letters, digits and underscores. · 1 problem 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. 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.', 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', 'Uses the total from the entry list response'],
|
||||
['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>:<asc|desc>, default updated_at:desc', 'Any verified user', 'Defaults omitted from the URL. Query: page, size, sort=<id|created_at|updated_at>:<asc|desc>, default updated_at:desc. The response carries total, page, size and sort']] },
|
||||
{ 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', 'Built-in types and their fields. GET /v1/content-type returns custom types only, so the read-only views use static client data (sample counts on the board are illustrative). To be closed in a backend slice before the SPA work.'],
|
||||
['2', 'Display names for created_by and updated_by. They are user ids and the user list is not open to every role. To be closed in the same slice.'],
|
||||
['3', 'A per-type icon. It does not exist, so the sidebar uses one default icon. To be closed in the same slice.'],
|
||||
['4', 'Later: per-change entry counts and diff (the API does not return them), 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', 'Confirmed: field keys and types lock per field once saved. Fields added since the last save can still change both. This is a client rule: a PUT with a changed key would remove one field and add another, and the server does not reject it.'],
|
||||
['2', 'Confirmed: the review opens only when the type already has entries (the list response total tells the client). A type without entries saves directly.'],
|
||||
['3', 'Confirmed: a new type starts with one field (Title), because a type needs at least one field.'],
|
||||
['4', 'Confirmed: the type key is 2 to 40 lowercase letters, digits and hyphens, the same slug rule as Sites. A field key is different: lowercase letters, digits and underscores, starts with a letter, up to 40. The two inputs show their own rule.'],
|
||||
['5', 'Yes or no is the label for the boolean type, Choice for select, Rich text for richtext.'],
|
||||
['6', 'Required fields carry * and the line "Fields marked * are required." Optional fields carry nothing.'],
|
||||
['7', 'A yes or no field with default false and one with no default look the same in the API sample. The inspector offers "On by default" only; no default means off. Confirm that no null default is needed.'],
|
||||
['8', 'The client does not know when the schema changes while a form is open. The design relies on 422 invalid_entry (required, unknown_field) on save and then shows the reload alert.'],
|
||||
['9', 'The Schema item sits after Users in the sidebar. The Content group sits under the main items.'],
|
||||
['10', '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.']] }
|
||||
]
|
||||
@@ -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").
|
||||
@@ -40,3 +40,4 @@ Each body lives in `docs/releases/<tag>.md`. Publish with `tea releases create -
|
||||
| `v3.2.0-beta` | Article lists, editor links and activity export |
|
||||
| `v3.2.1-beta` | Paged media library and remembered page sizes |
|
||||
| `v3.3.0-beta` | Sites, authors and search and sharing |
|
||||
| `v3.4.0-beta` | Custom content types |
|
||||
@@ -0,0 +1,70 @@
|
||||
This release adds custom content types: owners and admins define structured types such as Events or Recipes, and any verified user creates, edits and deletes their entries from the app or through a generic API. The built-in articles, authors, sites, media and users are unchanged.
|
||||
|
||||
## New
|
||||
|
||||
**Custom content types**
|
||||
|
||||
- A content type is a name, a key, an optional icon and an ordered list of 1 to 50 fields. The key is a slug of 2 to 40 characters and cannot be changed after creation.
|
||||
- A field has a key, a label, one of six types (text, rich text, number, boolean, date or select) and the options that fit its type: required, unique, a default value, a minimum and a maximum, and a list of choices for a select.
|
||||
- Changing a type that already has entries is checked first. A new required field needs a default, a removed select choice cannot still be in use, a lowered maximum cannot be below a stored value, and a field cannot become unique while stored values collide. Changing a field's type is refused. Removing a field drops its values from the entries the next time they are read or saved.
|
||||
- A content type with entries cannot be deleted.
|
||||
|
||||
**Schema screens**
|
||||
|
||||
- The new Schema item in the sidebar, after Users, opens a screen that lists every content type, custom and built-in, for owners and admins. Other users get a 403 page and no sidebar entry.
|
||||
- The schema builder creates and edits a custom type: add, remove and reorder fields, pick an icon, set each field's options in an inspector, and see the effect of a change before applying it. When the type already has entries, a review step shows how many entries are affected and names what the save will refuse.
|
||||
- A type is deleted from its builder, with a confirmation, and a type that still has entries explains why it cannot be deleted and links to them.
|
||||
- The built-in types (articles, authors, sites, media and users) can be opened read-only to see their fields.
|
||||
- The sidebar has a Content group with your custom types, showing the first few and a "Show all" link when there are many.
|
||||
|
||||
**Entries**
|
||||
|
||||
- The entry list at `/content/<key>` shows a table on desktop and cards on mobile. It is paged (5, 25, 50 or 100) and sortable by last updated, created or id, and the page, size and sort are kept in the address so a reload or a shared link opens the same view.
|
||||
- A Columns menu chooses which fields to show, up to six, and remembers the choice per type on this browser. By default the first four fields are shown.
|
||||
- The entry editor at `/content/<key>/new` and `/content/<key>/<id>` builds its form from the type. Each field type has its own control: a text box, a Markdown editor with a toolbar and preview, a number input, a switch, a date picker and a select.
|
||||
- Defaults are pre-filled and tagged. Rules (required, minimum, maximum, choices) are checked when you save, every error is shown at once, and focus goes to the first one. A message from the server, such as a duplicate value in a unique field, is shown on its field.
|
||||
- "Saved at" shows the time the server answered. A form with unsaved changes asks before you leave it. Deleting an entry asks for confirmation.
|
||||
- When the type's fields changed since the form was opened, the form is locked and offers "Reload form".
|
||||
- The entry list and editor show who created and last updated each entry, by display name.
|
||||
|
||||
## Improvements and fixes
|
||||
|
||||
- Every page-size menu now centres its items vertically.
|
||||
- The Columns and Sort menus of the entry list align their items correctly.
|
||||
- The builder's accessibility issues from the design review are fixed.
|
||||
- Markdown in entries is rendered with raw HTML disabled, images disabled and only http, https and mailto links active.
|
||||
|
||||
## API
|
||||
|
||||
- `GET /v1/content-type` lists the custom content types and `GET /v1/content-type/{key}` reads one. Both are open to any verified user or API key. A missing type answers `404` `content_type_not_found`.
|
||||
- `POST /v1/content-type`, `PUT /v1/content-type/{key}` and `DELETE /v1/content-type/{key}` are for owners and admins. A key already in use answers `409` `content_type_key_taken`, an invalid key `400` `invalid_content_type_key`, an invalid field list or icon `422` `invalid_field`, a change the stored entries cannot take `409` `schema_incompatible`, and deleting a type with entries `409` `content_type_has_entries`. A delete answers `204`.
|
||||
- A content type response has `id`, `key`, `name`, `icon`, `fields`, `created_at` and `updated_at`. The icon is `null` or a lowercase name of up to 40 characters, and a `PUT` replaces the whole type, so an absent icon clears it.
|
||||
- `GET /v1/content-type/{key}/entry` lists entries as `{ items, total, page, size }`, with `page`, `size` (5, 25, 50 or 100, default 25) and `sort` (`id`, `created_at` or `updated_at`, then `:asc` or `:desc`, default `updated_at:desc`). An invalid value answers `400`, and a page past the end answers an empty `items` with the real `total`.
|
||||
- `POST /v1/content-type/{key}/entry` creates an entry from `{ "data": { ... } }`, applying defaults, and `PUT /v1/content-type/{key}/entry/{id}` replaces its data. `GET` and `DELETE` on `/v1/content-type/{key}/entry/{id}` read and delete it, and a delete answers `204`. An entry that breaks the schema answers `422` `invalid_entry: <field>: <rule>`, a duplicate in a unique field `409` with the same shape, and a missing entry `404` `entry_not_found`.
|
||||
- An entry response has `id`, `content_type` (the type's key), `data`, `created_by`, `updated_by`, `created_at` and `updated_at`.
|
||||
- `GET /v1/builtin-type` and `GET /v1/builtin-type/{key}` return the read-only description of the built-in types. An unknown key answers `404` `builtin_type_not_found`.
|
||||
- `GET /v1/user/lookup?ids=1,2,3` resolves display names for the users who created or updated entries. It is open to any verified user or API key.
|
||||
|
||||
## Under the hood
|
||||
|
||||
- Content types and entries live in two generic tables, with the fields and the entry data stored as JSON, so no schema change runs at runtime and the SQL stays portable across SQLite, MySQL, MariaDB and PostgreSQL.
|
||||
- Schema and entry validation lives in the domain and the use cases, and the new handlers only decode requests and map errors.
|
||||
- The app has one registry of field types, used by the builder, the list cells and the entry form.
|
||||
- The list, builder and editor share their delete, save and unsaved-changes machinery, and the dashboard shell no longer calls the logout API or preloads content types itself.
|
||||
- New dependency: `markdown-it`, with its type definitions, for the Markdown preview.
|
||||
- Feature specs and QA procedures for each slice are in `features/`.
|
||||
|
||||
## Upgrading
|
||||
|
||||
- Replace the binary, or pull the new image. Back up the database first as usual.
|
||||
- The first start after the upgrade creates the two new tables for content types and entries. Nothing else changes, existing data is untouched, and a second start changes nothing.
|
||||
- No new environment variable is needed.
|
||||
|
||||
## Known limitations
|
||||
|
||||
- Entries cannot be filtered or searched by their field values yet.
|
||||
- There are no relations between types, no media fields and no permissions grid, so every verified user can read and write the entries of every type.
|
||||
- A type cannot be exported or imported yet.
|
||||
- The key `new` is not reserved, so a type with that key cannot be opened from its entry list.
|
||||
- On mobile, the entry list has no link to the builder; open the Schema item from the menu instead.
|
||||
- Moving from one entry to another by editing the address drops unsaved edits without asking.
|
||||
@@ -0,0 +1,469 @@
|
||||
Feature: Entry editor of a custom content type
|
||||
As a verified user
|
||||
I want to create, edit and delete an entry of a custom content type
|
||||
So that the content follows the fields of its type
|
||||
|
||||
Background:
|
||||
Given the SPA calls the API with relative URLs under /v1 and the "jwt" HttpOnly cookie
|
||||
And API errors are plain text
|
||||
And the routes are /content/:key/new and /content/:key/:id with meta auth "verified" and title "Content", per docs/design/screens/entry.md group "6 Entry editor", states 1 to 13
|
||||
And the structural prep of this slice is done first: ContentEntries is presentational with one owner of the list-view state, useContentTypes is split into entry and user-lookup parts, and one field-type registry (lib/fieldTypes) serves the schema builder, the list cells and this form
|
||||
And the page requests GET /v1/content-type/{key} (the type) and, on /content/:key/:id, GET /v1/content-type/{key}/entry/{id} at the same time
|
||||
And an entry is {id, content_type, data, created_by, updated_by, created_at, updated_at}, with content_type the key string
|
||||
And POST /v1/content-type/{key}/entry answers 201 with the entry, PUT .../entry/{id} answers 200 with the entry and DELETE answers 204 with no body
|
||||
And POST and PUT take {"data": {...}}; PUT replaces the whole entry and keeps created_by and created_at
|
||||
And the API refuses with 404 content_type_not_found, 404 entry_not_found, 400 for an id that is not a uint32, 401, 403, 409 "invalid_entry: <key>: unique" and 422 "invalid_entry: <key>: <required|type|min|max|options|unknown_field>", and the body names only one field per answer
|
||||
And any verified user may read and write entries; there is no owner or admin gate in the SPA
|
||||
And a "/content/:key/:id" whose id is not made of digits or does not fit a uint32 shows "Entry not found" with no entry request, and "new" is the literal route
|
||||
And the form is generated from the type's fields in schema order through the fieldTypes registry, with the six types text, richtext, number, boolean, date and select
|
||||
And the data sent holds exactly one key per field of the loaded type, with the value or null for an empty optional field, so no default is applied by the server to a field the user cleared and no unknown key is ever sent
|
||||
And a text or richtext value is counted in characters (code points) like the server, and is not trimmed
|
||||
And a required field is empty when it is null, undefined or an empty string; false and 0 are values
|
||||
And validation is done by the client against the loaded type before any request (required, type, min, max, options), one rule per field at a time in that order, and the server's single answer is mapped to its field when it gets past the client
|
||||
And "Created by" and "Updated by" names come from GET /v1/user/lookup?ids=<distinct created_by and updated_by> sent once after the entry answers, as in features/content_entry_list.feature; a missing name reads "–" with the date kept
|
||||
And dates in the footer are "12 Oct 2026, 09:14" (local time zone, 24 h)
|
||||
And the leave guard is useUnsavedChangesGuard, the same "Leave without saving?" dialog as features/schema_builder_edit.feature
|
||||
And the status chip is the builder's: "Saved", "Saved at HH:MM" (never "N min ago"), "Unsaved changes", "Saving…", "Save failed", plus "New entry" and "Not saved"
|
||||
And the SPA adds no beforeunload prompt, as nothing else in web/src does
|
||||
And Markdown is rendered with markdown-it with raw HTML disabled and only http, https and mailto links active
|
||||
And every string goes through t() and has a French entry in i18n/messages.ts
|
||||
And a copy tagged "(proposed copy)" is not in the design and is the coder's single point of change
|
||||
|
||||
Scenario: 1 New entry
|
||||
Given GET /v1/content-type/events resolves 200 with the 7 fields Title, Starts on, Ends on, Online, Capacity, Category, Description
|
||||
When the user navigates to /content/events/new
|
||||
Then the breadcrumb reads "Content", "Events", "New entry" and the title row reads "New entry" with the subtitle "Events · Fields marked * are required."
|
||||
And no entry request is sent
|
||||
And the chip reads "New entry", "Cancel" and "Save" are shown, and "Delete" is not
|
||||
And "Save" is enabled although nothing was typed
|
||||
And each required label carries " *"
|
||||
And the control of Online is Off and carries the tag "Default"
|
||||
And the help under Title reads "Each entry needs a different title.", under Capacity "Between 1 and 5000.", the placeholders read "Choose an option" (Category) and "Pick a date" (Starts on, Ends on)
|
||||
And the footer reads "Entry" "Not saved yet", "Created by" "–", "Updated by" "–"
|
||||
And on mobile the topbar reads "New entry" with an arrow-left and no action, the chip sits under the title row, and the bottom bar holds "Cancel" and "Save"
|
||||
|
||||
Scenario Outline: Defaults on a new entry
|
||||
Given the type has a field <field> with default <default>
|
||||
When the user opens /content/events/new
|
||||
Then the control holds <shown> and the tag "Default" shows next to the label
|
||||
When the user changes the value
|
||||
Then the tag goes
|
||||
And when the user restores the default value the tag shows again
|
||||
|
||||
Examples:
|
||||
| field | default | shown |
|
||||
| Online (boolean) | false | Off |
|
||||
| Capacity (number) | 100 | 100 |
|
||||
| Category (select) | Talk | Talk |
|
||||
| Starts on (date) | 2026-11-21 | 21 Nov 2026 |
|
||||
| Title (text) | Untitled | Untitled |
|
||||
| Description (richtext) | none | an empty textarea, no tag |
|
||||
|
||||
Scenario: Defaults are shown only on create
|
||||
When the user opens /content/events/42
|
||||
Then no field carries the tag "Default" and the values are those of the entry
|
||||
|
||||
Scenario: 2 Editing
|
||||
Given GET .../entry/42 resolves 200 with the entry "Lime plaster workshop" created by 3 on 2026-10-12 09:14 and updated by 5 on 2026-10-15 11:02, and the lookup names 3 "Inès Duarte" and 5 "Marta Alves"
|
||||
When the user navigates to /content/events/42
|
||||
Then the breadcrumb reads "Content", "Events", "Lime plaster workshop" and the title reads "Lime plaster workshop" with the subtitle "Events · Entry 42"
|
||||
And the chip reads "Saved"
|
||||
And "Delete", "Cancel" and "Save" are shown, "Save" is disabled
|
||||
And the controls hold the entry's values
|
||||
And the footer reads "Entry" "events / 42" (mono), "Created by" "Inès Duarte · 12 Oct 2026, 09:14", "Updated by" "Marta Alves · 15 Oct 2026, 11:02"
|
||||
And on mobile the topbar reads the title with an arrow-left and a trash-2 action, the chip sits under the title row, and the bottom bar holds "Cancel" and "Save" (disabled)
|
||||
|
||||
Scenario Outline: The page title
|
||||
Given the entry 42 whose first field <first> holds <value>
|
||||
When the user opens /content/events/42
|
||||
Then the title and the last breadcrumb read <title>
|
||||
|
||||
Examples:
|
||||
| first | value | title |
|
||||
| Title (text) | "Lime plaster workshop" | Lime plaster workshop |
|
||||
| Title (text) | null | Entry 42 |
|
||||
| Body (richtext) | "First line\n\nSecond" | First line |
|
||||
| Seats (number) | 18 | 18 |
|
||||
|
||||
Scenario: The title does not change while typing
|
||||
Given /content/events/42
|
||||
When the user types in Title
|
||||
Then the title row and the breadcrumb keep "Lime plaster workshop" until a save answers
|
||||
|
||||
Scenario Outline: Form controls per field type
|
||||
Given a field of type <type>
|
||||
Then the control is <control> with <detail>
|
||||
|
||||
Examples:
|
||||
| type | control | detail |
|
||||
| text | UInput | a counter "n / max" when max is set |
|
||||
| richtext | MarkdownField | tabs "Write" and "Preview", the toolbar bold, italic, heading, link, list, the placeholder "Write in Markdown", the help "Markdown. Switch to Preview to check the result." and a counter when max is set |
|
||||
| number | UInputNumber | the placeholder "Enter a number" and minus and plus buttons; decimals are accepted |
|
||||
| boolean | USwitch | the text "On" or "Off" next to it |
|
||||
| date | UInputDate | the placeholder "Pick a date" and a calendar; the value is "YYYY-MM-DD" with no time-zone shift |
|
||||
| select | USelect | the placeholder "Choose an option", the choices in schema order, and for an optional field a first item "None" (proposed copy) that clears it |
|
||||
|
||||
Scenario Outline: Help lines
|
||||
Given a field <field>
|
||||
Then the help under it reads <help>, and is replaced by the error when there is one
|
||||
|
||||
Examples:
|
||||
| field | help |
|
||||
| text, unique | Each entry needs a different title. (the label in lower case) |
|
||||
| number, min 1, max 5000 | Between 1 and 5000. |
|
||||
| number, min 1 | At least 1. (proposed copy) |
|
||||
| number, max 5000 | At most 5000. (proposed copy) |
|
||||
| date, min 2026-01-01, max 2027-12-31 | From 1 Jan 2026 until 31 Dec 2027. (proposed copy) |
|
||||
| richtext | Markdown. Switch to Preview to check the result. |
|
||||
| text, no unique, no number or date bounds | no help line |
|
||||
|
||||
Scenario: Layout of the generated form
|
||||
Given the 7 fields of Events on a 1440 px viewport
|
||||
Then Title is full width, Starts on and Ends on share a row, Online and Capacity share a row, Category and Description are each full width, in a column of at most 760 px
|
||||
And a date, number or boolean field pairs with the next one if that one is also a date, number or boolean, text, richtext and select are always full width
|
||||
And below md every field is full width
|
||||
|
||||
Scenario: 3 Unsaved changes and the counter
|
||||
Given /content/events/42 with Title "Lime plaster workshop" (21 characters, max 80)
|
||||
When the user types ", two days" in Title
|
||||
Then the counter beside the label reads "32 / 80" in mono, muted
|
||||
And the chip reads "Unsaved changes" and "Save" is enabled
|
||||
And a counter over the limit reads "91 / 80" in the error colour, and typing is not blocked
|
||||
And a counter shows only for a text or richtext field with a max
|
||||
|
||||
Scenario: An edit that is reverted is not an unsaved change
|
||||
Given the user changed Capacity from 18 to 20
|
||||
When the user sets it back to 18
|
||||
Then the chip reads "Saved", "Save" is disabled and the leave guard does not prompt
|
||||
|
||||
Scenario: Cancel
|
||||
Given /content/events/42, opened from the list /content/events?page=2&sort=id:asc
|
||||
When the user activates "Cancel"
|
||||
Then the router returns to /content/events?page=2&sort=id:asc when the previous history entry is the list of this type, else it navigates to /content/events
|
||||
And the leave guard runs first when there are unsaved changes
|
||||
|
||||
Scenario: 4 Markdown preview
|
||||
Given a richtext field holding "Two days of hands-on work with **lime putty** and old stone.\n\n- Bring work clothes\n- Lunch is included"
|
||||
When the user activates the "Preview" tab
|
||||
Then the textarea and the toolbar are replaced by the rendered text with a bold "lime putty" and a bulleted list of two items, in a box at least 96 px high (120 px on mobile)
|
||||
And raw HTML in the value is shown as text, never rendered, and only http, https and mailto links are active
|
||||
And the tab state is not an edit, and switching back to "Write" restores the textarea with its value, caret kept
|
||||
And an empty value in Preview reads "Nothing to preview yet." (proposed copy)
|
||||
|
||||
Scenario Outline: The Markdown toolbar
|
||||
Given the Write tab with the selection <selection>
|
||||
When the user activates <button>
|
||||
Then the textarea holds <result> and keeps the focus
|
||||
|
||||
Examples:
|
||||
| selection | button | result |
|
||||
| "lime" | Bold | **lime** |
|
||||
| "lime" | Italic | _lime_ |
|
||||
| "lime" | Heading | ## lime |
|
||||
| "lime" | Link | [lime](url) |
|
||||
| "lime" | List | - lime |
|
||||
|
||||
Scenario: Payload of a create
|
||||
Given /content/events/new with Title "Open day", Starts on 2026-11-21, Online left at its default false, Ends on, Capacity, Category and Description left empty
|
||||
When the user activates "Save"
|
||||
Then POST /v1/content-type/events/entry is sent once with {"data": {"title": "Open day", "starts_on": "2026-11-21", "ends_on": null, "online": false, "capacity": null, "category": null, "description": null}}
|
||||
And a number is sent as a JSON number, a boolean as true or false, a date as "YYYY-MM-DD", a select as the choice text
|
||||
|
||||
Scenario: Payload of an edit
|
||||
Given /content/events/42 with only Capacity changed from 18 to 20
|
||||
When the user activates "Save"
|
||||
Then PUT /v1/content-type/events/entry/42 is sent once with every field of the type, the unchanged ones with their loaded values
|
||||
And a key that the entry holds but the type no longer has is not sent
|
||||
|
||||
Scenario Outline: A boolean that was never set
|
||||
Given a boolean field <kind> and the user never touched it
|
||||
When the entry is saved
|
||||
Then the data holds <sent> for it
|
||||
|
||||
Examples:
|
||||
| kind | sent |
|
||||
| optional, no default | null |
|
||||
| optional, loaded as null | null |
|
||||
| required, no default | false |
|
||||
| optional, default true | true |
|
||||
|
||||
Scenario: 5 Saving
|
||||
Given the PUT has not answered
|
||||
Then the chip reads "Saving…" with a loader, "Save" reads "Saving…" with a loader and is disabled, "Cancel" and "Delete" are disabled
|
||||
And the form is dimmed to 70 % and every control is disabled
|
||||
And a second activation of "Save", or Enter in a field, sends no second request
|
||||
|
||||
Scenario: 6 Saved (edit)
|
||||
Given /content/events/42 with Title changed to "Lime plaster workshop, two days"
|
||||
When the PUT answers 200 with updated_by 5 and updated_at 2026-10-19 11:02 local
|
||||
Then a success toast "Entry saved" with "\"Lime plaster workshop, two days\" is up to date." is shown
|
||||
And the chip reads "Saved at 11:02", "Save" is disabled and the controls hold the answered values
|
||||
And the title, the breadcrumb and the footer "Updated by" read the answered entry ("Marta Alves · 19 Oct 2026, 11:02")
|
||||
And no "Leave without saving?" prompt is shown afterwards
|
||||
And a later edit returns the chip to "Unsaved changes"
|
||||
|
||||
Scenario: Saved (create)
|
||||
Given /content/events/new with the required fields filled
|
||||
When the POST answers 201 with id 43
|
||||
Then the router replaces the URL with /content/events/43 and no entry request is made for it, the answered entry is used
|
||||
And the same toast, the chip "Saved at HH:MM" and the footer ("Entry" "events / 43", "Created by" and "Updated by" the current user) show
|
||||
And "Delete" now shows and a Back from there goes to the page before the new form
|
||||
And no "Leave without saving?" prompt is shown
|
||||
|
||||
Scenario: Where "Saved at" comes from
|
||||
Given the answered entry has updated_at 2026-10-19T11:02:00 in the local time zone
|
||||
Then the chip text is "Saved at 11:02" built from that timestamp, never from the clock
|
||||
And a Saved chip never turns into "Saved N min ago"
|
||||
And a test builds its expected text with the same local formatter from the mocked updated_at and pins the time zone; no test freezes the system date
|
||||
|
||||
Scenario Outline: 7 Save failed
|
||||
Given the save <failure>
|
||||
Then an error alert titled "Couldn't save the entry" shows "Something went wrong on our side. Your changes are still here. Try again in a moment." with a "Try again" action
|
||||
And the chip reads "Save failed" in the error colour, the values stay, "Save" is enabled and the form is not dimmed
|
||||
When the user activates "Try again"
|
||||
Then the same body is sent again and the alert clears while it is in flight
|
||||
|
||||
Examples:
|
||||
| failure |
|
||||
| answers 500 |
|
||||
| never reaches the server |
|
||||
| answers 400 |
|
||||
| answers 422 "invalid_entry" with no field |
|
||||
|
||||
Scenario: 8 Required fields empty
|
||||
Given /content/events/new with Title and Starts on empty
|
||||
When the user activates "Save"
|
||||
Then no request is sent
|
||||
And "Fill in Title." shows under Title and "Pick a date for Starts on." under Starts on, each with the error colour on the control
|
||||
And the chip reads "Not saved" in the error colour with a circle-alert icon
|
||||
And focus moves to the Title control, the first field in schema order with an error, and the page scrolls to it
|
||||
And the controls carry aria-invalid and the message is tied to them by aria-describedby
|
||||
|
||||
Scenario Outline: Required messages
|
||||
Given an empty required field of type <type> labelled <label>
|
||||
When the user saves
|
||||
Then the message under it reads <message>
|
||||
|
||||
Examples:
|
||||
| type | label | message |
|
||||
| text | Title | Fill in Title. |
|
||||
| richtext | Notes | Fill in Notes. (proposed copy) |
|
||||
| number | Capacity | Fill in Capacity. (proposed copy)|
|
||||
| date | Starts on | Pick a date for Starts on. |
|
||||
| select | Category | Choose an option for Category. |
|
||||
|
||||
Scenario: A required boolean refused by the server
|
||||
Given /content/events/42 where Online is a required boolean the user never touched
|
||||
When the server answers 422 "invalid_entry: online: required"
|
||||
Then the message under Online reads "Choose yes or no for Online."
|
||||
And a required boolean is never refused on the client: an untouched one is sent as false
|
||||
|
||||
Scenario: 9 Rule errors
|
||||
Given /content/events/42 with Title of 91 characters, Ends on holding a value the server refuses as a date, Capacity 6000 and Category "Seminar" which is not a choice
|
||||
When the user activates "Save"
|
||||
Then only one message shows per field: "Title can be up to 80 characters." with the counter "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."
|
||||
And the chip reads "Not saved" and focus is on Title
|
||||
|
||||
Scenario Outline: Messages per rule and type
|
||||
Given a field <field> and the value <value>
|
||||
When the entry is saved
|
||||
Then the message under it reads <message>
|
||||
|
||||
Examples:
|
||||
| field | value | message |
|
||||
| Title, text, min 3 | "ab" | Title needs at least 3 characters. |
|
||||
| Title, text, max 80 | 91 characters | Title can be up to 80 characters. |
|
||||
| Title, text | 5 (server type) | Title must be text. |
|
||||
| Capacity, number, min 1 | 0 | Capacity must be at least 1. |
|
||||
| Capacity, number, max 5000 | 6000 | Capacity must be at most 5000. |
|
||||
| Capacity, number | "4" (server type) | Capacity must be a number. |
|
||||
| Online, boolean | "yes" (server type) | Online must be yes or no. |
|
||||
| Starts on, date, min 2026-01-01 | 2025-12-31 | Starts on can't be before 1 Jan 2026. |
|
||||
| Starts on, date, max 2027-12-31 | 2028-01-01 | Starts on can't be after 31 Dec 2027. |
|
||||
| Starts on, date | 2026-02-30 (server type)| Starts on must be a date, like 2026-11-21. |
|
||||
| Category, select | "Seminar" | Choose one of: Talk, Workshop or Meetup. |
|
||||
|
||||
Scenario Outline: A server answer that gets past the client
|
||||
Given the client found no error and the request is sent
|
||||
When the server answers <status> "invalid_entry: <key>: <rule>" for a key of the loaded type
|
||||
Then the message of the table above shows under the field of <key>, the chip reads "Not saved", focus moves to that field and the values stay
|
||||
|
||||
Examples:
|
||||
| status | key | rule |
|
||||
| 422 | title | min |
|
||||
| 422 | capacity | max |
|
||||
| 422 | ends_on | type |
|
||||
| 422 | category | options |
|
||||
| 422 | title | required|
|
||||
|
||||
Scenario: Errors clear field by field
|
||||
Given the errors of state 8 are shown
|
||||
When the user edits Title
|
||||
Then the message under Title goes and the chip reads "Unsaved changes"
|
||||
And the message under Starts on stays until Starts on is edited or the next save
|
||||
And nothing is validated on blur
|
||||
|
||||
Scenario: 10 Duplicate unique value (409)
|
||||
Given /content/events/new with Title "Heat pumps: what the numbers say" and another entry holds it
|
||||
When the POST answers 409 "invalid_entry: title: unique"
|
||||
Then an error alert titled "Not saved" shows "Another entry already uses this title. Change it and save again."
|
||||
And under Title "Another entry already uses this Title. Enter a different one." shows, with the counter "n / 80", and the chip reads "Not saved"
|
||||
And focus moves to Title and the values stay
|
||||
And the alert goes when Title is edited
|
||||
|
||||
Scenario Outline: The unique message per type
|
||||
Given a unique <type> field labelled <label>
|
||||
When the server answers 409 "invalid_entry: <key>: unique"
|
||||
Then the message under it reads <message> and the alert reads <alert>
|
||||
|
||||
Examples:
|
||||
| type | label | key | message | alert |
|
||||
| text | Title | title | Another entry already uses this Title. Enter a different one. | Another entry already uses this title. Change it and save again. |
|
||||
| select | Category | category | Another entry already uses this choice for Category. | Another entry already uses this choice. Change it and save again. (proposed copy) |
|
||||
| number | Capacity | capacity | Another entry already uses this Capacity. Enter a different one. (proposed copy) | Another entry already uses this capacity. Change it and save again. (proposed copy) |
|
||||
|
||||
Scenario Outline: 11 Entry not found
|
||||
Given <where>
|
||||
Then a centered state with the file-x icon reads "Entry not found" with "It may have been deleted by someone else." and a primary "Back to Events"
|
||||
And the breadcrumb reads "Content" then "Events" and the mobile title is "Events"
|
||||
And "Back to Events" navigates to /content/events
|
||||
And the leave guard does not prompt on that navigation
|
||||
|
||||
Examples:
|
||||
| where |
|
||||
| GET .../entry/999 answers 404 entry_not_found |
|
||||
| a PUT answers 404 entry_not_found (edits discarded with the page) |
|
||||
| the URL is /content/events/abc or /content/events/4294967296 (no request) |
|
||||
|
||||
Scenario Outline: Other answers while loading or saving
|
||||
Given any request of the editor
|
||||
When it answers <status> <body>
|
||||
Then <result>
|
||||
|
||||
Examples:
|
||||
| status | body | result |
|
||||
| 404 | content_type_not_found | the page "Content type not found" of features/content_entry_list.feature state 9 |
|
||||
| 403 | any | the page "You don't have access to Events" of features/content_entry_list.feature state 8 |
|
||||
| 401 | any | the existing redirect to /login with the expired reason |
|
||||
|
||||
Scenario Outline: Loading the entry fails (proposed, not drawn)
|
||||
Given GET .../entry/42 or the type <failure>
|
||||
Then an error alert reads "Couldn't load the entry" (proposed copy) with "GET /v1/content-type/events/entry/42 failed. Check your connection and try again." and a "Try again" action
|
||||
And no form shows and "Try again" sends only the failed request again
|
||||
|
||||
Examples:
|
||||
| failure |
|
||||
| answers 500 |
|
||||
| never reaches the server |
|
||||
|
||||
Scenario: Loading (proposed, not drawn)
|
||||
Given the type and the entry have not resolved
|
||||
Then the title row shows a skeleton, the form is skeleton rows with aria-busy="true", and "Save" and "Delete" are not shown
|
||||
|
||||
Scenario: 12 Schema changed since load
|
||||
Given /content/events/new was opened with the 7 fields, then Room (required) was added and Description removed
|
||||
When the POST answers 422 "invalid_entry: room: required"
|
||||
Then a warning alert titled "The fields of Events changed" shows "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." with a "Reload form" action
|
||||
And every control is disabled, the form is dimmed, "Save" is disabled
|
||||
And the values stay visible
|
||||
And the chip reads "Not saved" (the board draws "Saved" here) and "Cancel" stays enabled
|
||||
|
||||
Scenario Outline: What counts as a schema change
|
||||
Given the editor holds the type as loaded
|
||||
When the server answers 422 "invalid_entry: <key>: <rule>"
|
||||
Then <result>
|
||||
|
||||
Examples:
|
||||
| key | rule | result |
|
||||
| room | required | the key is not a field of the loaded type: state 12 |
|
||||
| description | unknown_field | state 12 |
|
||||
| colour | unknown_field | state 12 |
|
||||
| title | required | state 8 on Title (the key is known) |
|
||||
| room | unique | state 12 (409) |
|
||||
|
||||
Scenario: The alert names what changed only when the SPA can tell
|
||||
Given the type is fetched again by "Reload form"
|
||||
Then the alert copy of the design is used as is; the SPA never builds a diff of fields, since the design text names Room and the removed field only as a sample
|
||||
|
||||
Scenario: Reload form
|
||||
Given state 12
|
||||
When the user activates "Reload form"
|
||||
Then GET /v1/content-type/events is sent again and, on /content/:key/:id, GET .../entry/42 too
|
||||
And the form is rebuilt from the new type with defaults on a new entry, or the stored values on an edit; what was typed is dropped
|
||||
And the alert goes, the chip reads "New entry" or "Saved", and the URL is unchanged
|
||||
And a failure of the reload shows the load error of this slice
|
||||
|
||||
Scenario: 13 Delete entry: confirm
|
||||
Given /content/events/42 with no unsaved changes
|
||||
When the user activates "Delete" (the trash-2 action on mobile)
|
||||
Then no request is sent
|
||||
And the dialog "Delete this entry?" opens with "\"Lime plaster workshop\" will be deleted from Events. This can't be undone." (a bottom sheet on mobile)
|
||||
And the actions are "Cancel" and "Delete entry" (error colour, never the initial focus)
|
||||
And Cancel, the close icon and Esc close it with nothing sent and focus back on "Delete"
|
||||
|
||||
Scenario: Deleting
|
||||
Given the dialog is open
|
||||
When the user activates "Delete entry"
|
||||
Then DELETE /v1/content-type/events/entry/42 is sent once
|
||||
And the button reads "Deleting…" with a loader, Cancel is disabled, Esc, the close icon and the overlay do not dismiss, and a second activation sends nothing
|
||||
|
||||
Scenario: Deleted
|
||||
Given DELETE answers 204
|
||||
Then the dialog closes and the router replaces the URL with /content/events with no "Leave without saving?" prompt
|
||||
And a success toast "Entry deleted" with "\"Lime plaster workshop\" was deleted from Events." (proposed copy) is shown
|
||||
And the list loads its own data, so the entry is gone from it
|
||||
|
||||
Scenario Outline: Other answers of DELETE
|
||||
Given the dialog is open and DELETE <outcome>
|
||||
Then <result>
|
||||
|
||||
Examples:
|
||||
| outcome | result |
|
||||
| answers 404 entry_not_found | the dialog closes and the page "Entry not found" shows |
|
||||
| answers 404 content_type_not_found| the dialog closes and the page "Content type not found" shows |
|
||||
| answers 403 | the dialog closes and the page "You don't have access to Events" shows |
|
||||
| answers 401 | the existing redirect to /login with the expired reason |
|
||||
| answers 500 or fails (network) | the dialog stays with an error alert "Couldn't delete the entry" (proposed copy) and "Something went wrong on our side. Nothing was deleted. Try again in a moment."; the buttons are enabled again |
|
||||
|
||||
Scenario: Delete with unsaved edits
|
||||
Given /content/events/42 with unsaved edits
|
||||
When the user opens the delete dialog
|
||||
Then its copy uses the saved title, it does not save or discard the edits, and Cancel leaves them exactly as they were
|
||||
And on 204 the router leaves with no leave prompt
|
||||
|
||||
Scenario Outline: Leaving with unsaved edits
|
||||
Given <state>
|
||||
When the user leaves through the breadcrumb, the mobile arrow, "Cancel", the sidebar or the browser back
|
||||
Then <result>
|
||||
|
||||
Examples:
|
||||
| state | result |
|
||||
| no edit | the router navigates with no prompt |
|
||||
| an edit on /content/events/42 | the dialog "Leave without saving?" with "Keep editing" and "Discard changes" |
|
||||
| any typed value on /content/events/new | the same dialog |
|
||||
| /content/events/new untouched, defaults only | no prompt |
|
||||
| after Save answered 200 or 201 | no prompt |
|
||||
| after Delete answered 204 | no prompt |
|
||||
| state 12 with typed values | the same dialog |
|
||||
|
||||
Scenario: Switching to another entry or type reuses nothing
|
||||
Given the user edited /content/events/42 and discarded the edits to leave
|
||||
When the user opens /content/events/43 or /content/recipes/new
|
||||
Then the form is built from that route alone, with no value, error or chip carried over
|
||||
|
||||
Scenario: Stale answers are ignored
|
||||
Given a GET for /content/events/42 is in flight
|
||||
When the user navigates to /content/events/43 and the first answer arrives later
|
||||
Then it is dropped
|
||||
|
||||
Scenario: Reaching the editor from the list
|
||||
Given the list of features/content_entry_list.feature
|
||||
When the user activates "New entry" or a row
|
||||
Then the editor opens at /content/events/new or /content/events/42, no longer the catch-all 404
|
||||
|
||||
Scenario: Accessibility
|
||||
Then every control has a visible label tied to it, the required mark " *" is hidden from assistive technology and the control carries aria-required
|
||||
And the chip is a polite live region
|
||||
And the Preview tabs are a tablist with arrow-key movement, and the toolbar buttons have accessible names (Bold, Italic, Heading, Link, List)
|
||||
And dialogs trap focus, open with focus on the title and return it to the opener on close; the destructive button is never the initial focus
|
||||
And controls are 44 px high on mobile and focus is a 2 px --ui-primary outline with a 2 px offset
|
||||
@@ -0,0 +1,69 @@
|
||||
# QA: Entry editor of a custom content type (SPA slice 7)
|
||||
|
||||
Runner: Vitest + Vue Test Utils (`task test:web`). No Go test: the five entry endpoints and /v1/user/lookup already exist and the backend does not change. Kit: reuse `views/__tests__/schemaTestKit.ts` and add GET/POST/PUT/DELETE handlers for `/v1/content-type/{key}/entry[/{id}]` with the plain-text bodies `entry_not_found`, `content_type_not_found`, `invalid_entry: <key>: <rule>`, and the Events type with its 7 fields and entry 42 of SchemaFrame.dc.html. Pin the time zone. Never freeze the system date: "Saved at" is derived from the mocked `updated_at`, so the expected text is built with the same local formatter from that value.
|
||||
|
||||
## Automated
|
||||
|
||||
1. Registry (lib/fieldTypes spec, it.each over the six types): empty value, default pre-fill, control component, help line, counter rule, validate (required, type, min, max, options), message text, payload value (null for empty, false for a required boolean). The builder and the list cells still pass on the same registry.
|
||||
2. Entry API (composable spec): getEntry, createEntry, saveEntry, deleteEntry; the body is {data}; error parsing of "invalid_entry: key: rule" with status 422 and 409 into {key, rule, status}; 404 bodies; 400, 401, 403 and NetworkError pass through; lookupUsers is sent once with distinct ids.
|
||||
3. Route resolution (it.each): "new", "42", "abc", "0" (resolves to id 0, sent as is: the API answers 404 entry_not_found), "4294967296", "-1".
|
||||
4. State 1 New entry: title, subtitle, chip "New entry", asterisks, Default tag on Online, helps, placeholders, footer "Not saved yet" and "–", Save enabled, Delete absent; mobile layout.
|
||||
5. Defaults (it.each from the feature table): value shown, tag shown, tag leaves on change and returns on restore; no tag in edit.
|
||||
6. State 2 Editing: breadcrumb, title, "Entry 42", chip "Saved", Save disabled, footer names and dates after the lookup; "–" with the date kept when the lookup fails or lacks an id; mobile trash-2 action.
|
||||
7. Page title (it.each): text, null → "Entry 42", richtext first line, number; unchanged while typing.
|
||||
8. Controls and help lines (it.each): one control per type, placeholders, Off/On text, empty select "None" item on optional select only.
|
||||
9. Layout rule (pairing of date, number, boolean; full width for text, richtext, select; single column below md).
|
||||
10. State 3 Unsaved: counter "32 / 80", "91 / 80" in the error colour without blocking, no counter without max, chip, Save enabled, revert returns to clean.
|
||||
11. State 4 Preview: rendering of bold and list, raw HTML shown as text, unsafe links inert, empty preview, tab switch keeps value and caret, toolbar inserts (it.each).
|
||||
12. Payloads: create and edit bodies exactly as in the feature, explicit nulls, no unknown key, boolean table.
|
||||
13. State 5 Saving: chip, button, dimming, disabled controls, no second request on click or Enter.
|
||||
14. State 6 Saved: edit and create; toast; chip "Saved at HH:MM" from the answer; footer update; create replaces the URL to /content/events/43 with no extra GET; no leave prompt; edit after save is dirty again.
|
||||
15. State 7 Save failed (500, network, 400, 422 with no field): alert copy, chip, values kept, Try again resends the same body.
|
||||
16. State 8 Required: no request, all messages, chip "Not saved", `document.activeElement` is the first erroring control in schema order for each type (input, textarea, select trigger, date segment), aria-invalid and aria-describedby, per-type required messages (it.each).
|
||||
17. State 9 Rules: one message per field, message table (it.each), server answers that pass the client map to their field and take focus.
|
||||
18. Errors clear per field; chip returns to "Unsaved changes"; no blur validation.
|
||||
19. State 10 Unique (409): alert and field message, per-type messages, alert clears when the field is edited.
|
||||
20. State 11 Not found: GET 404, PUT 404, DELETE 404 and bad ids with no request; "Back to Events" goes to /content/events with no prompt.
|
||||
21. Content type 404, 403 and 401; load failure variants with "Try again" resending only the failed request; loading skeleton with aria-busy.
|
||||
22. State 12 Schema changed: unknown key, unknown_field, required on an unknown key, 409 on an unknown key; read-only form; Save disabled; Cancel enabled; chip "Not saved"; "Reload form" refetches the type (and the entry) and rebuilds the form; reload failure.
|
||||
23. State 13 Delete: dialog copy, focus on Cancel, Cancel/Esc/close, no request; Deleting lock; 204 replaces the URL and shows the toast; 404, 403, 401, 500 and network outcomes; delete with unsaved edits.
|
||||
24. Leave guard (it.each from the feature table), including defaults-only new form untouched, and Cancel history rule (previous entry is the list vs not).
|
||||
25. Stale answers dropped; navigating between routes carries nothing.
|
||||
26. Reaching the editor from the list: "New entry" and row links resolve to the editor (update the slice-6 specs that expected the catch-all 404). The slice-6 Background wording about `content_type_id` and `sort` is checked against the Go handler and corrected with the list code and tests if it differs.
|
||||
27. Accessibility: labels, aria-required, live-region chip, tablist keyboard, toolbar names, dialog focus.
|
||||
28. French: every new string has an entry (i18n completeness spec passes).
|
||||
|
||||
## Visual (task visual:check -- entry)
|
||||
|
||||
Register the group "6 Entry editor" in `extraSources` if needed. Every capture within 10 %, desktop and mobile, light and dark. Mock the sidebar's GET /v1/content-type and /v1/user/lookup. No state is clock-sensitive: "Saved at" comes from the response timestamp. If the runner cannot pin the zone, build `updated_at` as the builder's Saved setup does.
|
||||
|
||||
| Board state | Setup in web/visual/states.ts | Board sample data |
|
||||
|---|---|---|
|
||||
| 1 New entry | /content/events/new, Events type | "New entry", "Not saved yet", Online Off + "Default" |
|
||||
| 2 Editing | /content/events/42, lookup 3 and 5 | "Lime plaster workshop", "Entry 42", "Inès Duarte · 12 Oct 2026, 09:14", "Marta Alves · 15 Oct 2026, 11:02" |
|
||||
| 3 Unsaved changes | step: type ", two days" in Title | "Lime plaster workshop, two days", "32 / 80", focus ring on Title |
|
||||
| 4 Markdown preview | step: click "Preview" on Description | "Two days of hands-on work with lime putty and old stone." and the two bullets |
|
||||
| 5 Saving | PUT `hang: true` after an edit | "Saving…" |
|
||||
| 6 Saved | PUT 200 with updated_at 2026-10-19 11:02 local, updated_by 5 | "Saved at 11:02", "Entry saved", "Marta Alves · 19 Oct 2026, 11:02" |
|
||||
| 7 Save failed | PUT 500 after an edit | "Couldn't save the entry" |
|
||||
| 8 Required fields empty | /content/events/new, click Save | "Fill in Title.", "Pick a date for Starts on." |
|
||||
| 9 Rule errors | /content/events/42 with the board's values typed, PUT 422 for any server-side one | "91 / 80", "Capacity must be at most 5000.", "Choose one of: Talk, Workshop or Meetup." |
|
||||
| 10 Duplicate (409) | /content/events/new, title "Heat pumps: what the numbers say", POST 409 | "Another entry already uses this Title. Enter a different one." |
|
||||
| 11 Entry not found | /content/events/999, entry 404 entry_not_found | "Entry not found" |
|
||||
| 12 Schema changed | /content/events/new, POST 422 invalid_entry: room: required | "The fields of Events changed" |
|
||||
| 13 Delete entry: confirm | /content/events/42, step: click "Delete" | "Delete this entry?" |
|
||||
|
||||
Board caveats to report, never hide:
|
||||
- State 9 draws `31/11/2026` as text in Ends on; a segmented date control cannot hold it, so that field will differ.
|
||||
- State 11's breadcrumb shows the entry title, unknown on a 404.
|
||||
- State 12's chip is drawn "Saved" and its Cancel is drawn disabled; the spec uses "Not saved" and an enabled Cancel (user decision).
|
||||
- Mobile in state 9 depends on the chosen layout rule.
|
||||
|
||||
## Manual
|
||||
|
||||
- Real backend with two users: create an entry; Back from it returns to the list, not the empty form; edit; delete; the list shows the change.
|
||||
- Two tabs: change the type's fields in one (add a required field), save the entry in the other: state 12, "Reload form". Delete the entry in one tab and save in the other: state 11.
|
||||
- Duplicate a unique title for a real 409.
|
||||
- Keyboard: tab order across fields, toolbar, tabs, footer buttons; Enter in a single-line field saves; focus lands on the first error; dialogs trap focus.
|
||||
- Markdown with raw HTML and `javascript:` links stays inert in Preview.
|
||||
- Reload on /content/events/42 keeps the page; the browser back from a saved new entry goes to the page before the new form.
|
||||
@@ -0,0 +1,224 @@
|
||||
Feature: Entry list of a custom content type
|
||||
As a verified user
|
||||
I want to browse the entries of a custom content type
|
||||
So that I can find an entry before editing it
|
||||
|
||||
Background:
|
||||
Given the SPA calls the API with relative URLs under /v1 and the "jwt" HttpOnly cookie
|
||||
And API errors are plain text
|
||||
And the route is /content/:key with meta auth "verified" and title "Content", per docs/design/screens/content.md group "5 Content and entry list", states 1 to 9
|
||||
And the page requests GET /v1/content-type/{key} (the type) and GET /v1/content-type/{key}/entry?page=P&size=S&sort=O (the entries) at the same time; the entries answer {items, total, page, size} (no sort) and each item is {id, content_type (the type key), data, created_by, updated_by, created_at, updated_at}
|
||||
And the sidebar Content group of features/schema_list_and_content_nav.feature is reused unchanged; this slice only checks it in the "Many types" state
|
||||
And page, size and sort live in the URL (/content/events?page=2&size=50&sort=created_at:desc), the defaults (page 1, size 25, sort updated_at:desc) are omitted from the URL, and the request always carries explicit page and size
|
||||
And size is one of 5, 25, 50, 100; sort is <id|created_at|updated_at>:<asc|desc>; an invalid value is replaced silently by the default in the URL and in the request, so the API never answers 400 here
|
||||
And a size or sort change resets page to 1; the URL changes when a response succeeds, not when the request is sent
|
||||
And the pager, the page-size select, the summary, the loading page, the page error notice and the out-of-range redirect behave as in features/articles_pagination_screen.feature scenarios 1 to 7, 10, 10b and 11, with the content URL and request
|
||||
And the page size is not remembered
|
||||
And the columns are ID, up to 6 chosen field columns (default: the first 4 fields of the type, fewer if the type has fewer), Created, Updated and Updated by; ID, Created, Updated and Updated by are always shown
|
||||
And a field cell shows: Text truncated on one line with the full text as tooltip; Rich text as its first line in plain text, truncated; Number right-aligned with tabular figures; Yes or no as an icon plus "Yes" or "No"; Date as day, month and year ("21 Nov 2026") with no time-zone shift; Choice as a small outline tag; an empty value as "–"
|
||||
And Created reads "12 Oct 2026" and Updated reads "15 Oct 2026" (date only, local time zone), ID is mono and muted
|
||||
And "Updated by" is the display_name from one GET /v1/user/lookup?ids=<distinct updated_by of the page> sent after the entries answer; until it resolves, and if it fails or does not know the id, the cell shows a muted "–"
|
||||
And the desktop list is a table with a 36 px header and 48 px rows; below md it is a card list with 68 px cards, each card a link with a chevron-right, showing the first field, the second field, the first Choice field as a tag if the type has one, and "· {Updated by}"; cards ignore the column picker
|
||||
And every row is a link to /content/:key/:id (a link on the first field cell on desktop, the whole card on mobile); the click uses the router
|
||||
And "New entry" (primary, plus icon, in the title row on desktop; a floating button on mobile) navigates to /content/:key/new
|
||||
And /content/:key/new and /content/:key/:id are not routed in this slice and land on the catch-all 404 until the entry editor slice
|
||||
And "Edit content type" (ghost, settings-2 icon, right of the toolbar) navigates to /schema/:key; it is shown to owner and admin only and not on mobile
|
||||
And no filter or search exists
|
||||
And every string goes through t() and has a French entry in i18n/messages.ts
|
||||
And a copy tagged "(proposed copy)" is not in the design and is the coder's single point of change
|
||||
|
||||
Scenario: 1 Populated, one page
|
||||
Given GET /v1/content-type/events resolves 200 with 7 fields and GET .../entry?page=1&size=25&sort=updated_at:desc resolves 200 with 7 items and total 7
|
||||
When the user navigates to /content/events
|
||||
Then the breadcrumb reads "Content" then "Events", the title "Events" with the subtitle "events · 7 fields"
|
||||
And "New entry" is in the title row and the toolbar reads "Sort by" "Last updated", a direction button, "Columns", then "Edit content type" at the right
|
||||
And the table headers read "ID" "Title" "Starts on" "Ends on" "Online" "Created" "Updated" "Updated by" and the Updated header shows an arrow-down icon
|
||||
And 7 rows show, the first row ID 42 "Lime plaster workshop" "21 Nov 2026" "22 Nov 2026" "No" "12 Oct 2026" "15 Oct 2026" "Marta Alves"
|
||||
And no pager, no page-size select, only the text "7 entries" ("1 entry" for one, proposed copy)
|
||||
And the sidebar row Events is the current page and the URL has no query
|
||||
|
||||
Scenario: 2 Paginated, 5 per page
|
||||
Given GET .../entry?page=1&size=5&sort=updated_at:desc resolves 200 with 5 items and total 37
|
||||
When the user navigates to /content/events?size=5
|
||||
Then the summary reads "Showing 1–5 of 37", the page-size select reads "5 per page" and the paginator shows First, Previous (both disabled), 1 (current), 2, an ellipsis, 8, Next, Last
|
||||
And on mobile the paginator reads Previous (disabled), "Page 1 of 8", Next
|
||||
And activating Next sends page=2 and, on success, the URL is /content/events?size=5&page=2
|
||||
|
||||
Scenario: 3 Columns menu
|
||||
Given the populated state of the 7-field type Events
|
||||
When the user activates "Columns"
|
||||
Then a popover opens on desktop and a bottom sheet on mobile, titled "Columns" with "4 of 6"
|
||||
And the sheet adds the text "Choose up to 6 fields to show. 4 selected." and the actions "Reset" and "Done"; the popover has "Reset" only
|
||||
And each of the 7 fields is a checkbox row with its type icon, its label and its key in mono, in schema order; Title, Starts on, Ends on and Online are checked
|
||||
And a last row with a clock icon reads "Created and updated dates always show" with a disabled, unchecked checkbox
|
||||
When the user checks "Capacity"
|
||||
Then the table gets a Capacity column (right-aligned) at once, with no request, and the count reads "5 of 6"
|
||||
And Esc, a click outside or "Done" closes it and returns focus to "Columns"
|
||||
|
||||
Scenario Outline: The column cap and the stored choice
|
||||
Given the 7-field type Events and <before>
|
||||
When <action>
|
||||
Then <after>
|
||||
|
||||
Examples:
|
||||
| before | action | after |
|
||||
| 6 fields checked | the user opens the menu | the unchecked fields are disabled and the text "You can show up to 6 fields." (proposed copy) shows |
|
||||
| 5 fields checked | the user checks a 6th | it is checked and the others become disabled |
|
||||
| 6 fields checked | the user unchecks one | the others are enabled again |
|
||||
| the default 4 and nothing stored | the user checks "Capacity" | localStorage renewcms-content-columns-events is ["title","starts_on","ends_on","online","capacity"] |
|
||||
| a stored selection | the user activates "Reset" | the default 4 apply and the stored key is removed |
|
||||
| stored ["title","gone","capacity"] | the page loads | the columns are Title and Capacity, and nothing is written |
|
||||
| stored with 8 valid keys | the page loads | the first 6 in schema order show |
|
||||
| stored "not json" or [] | the page loads | the default 4 show |
|
||||
| localStorage throws or is undefined | the user changes the selection | the columns change for this visit and no error shows |
|
||||
| stored for events | the user opens /content/recipes | Recipes uses its own key and its default |
|
||||
|
||||
Scenario: The last field column cannot be unchecked
|
||||
Given the 7-field type Events with exactly one field checked
|
||||
When the user opens the Columns menu
|
||||
Then that field's checkbox is disabled, so at least one field column always shows and every row has its link
|
||||
And a stored empty selection loads as the default 4
|
||||
|
||||
Scenario: A type with fewer than 4 fields
|
||||
Given a type with 2 fields
|
||||
When the user opens its list
|
||||
Then both field columns show and "of 6" in the menu still reads the cap
|
||||
|
||||
Scenario Outline: Sort control
|
||||
Given GET .../entry resolves 200 and the user is on /content/events?page=3
|
||||
When the user chooses "<option>" in the "Sort by" select
|
||||
Then GET ...&sort=<sort>&page=1 is sent and, on success, the URL is <url>
|
||||
And the sorted column header shows the arrow icon of its direction
|
||||
|
||||
Examples:
|
||||
| option | sort | url |
|
||||
| ID | id:desc | /content/events?sort=id:desc |
|
||||
| Created | created_at:desc | /content/events?sort=created_at:desc |
|
||||
| Last updated | updated_at:desc | /content/events |
|
||||
|
||||
Scenario Outline: Direction button
|
||||
Given the user is on <from>
|
||||
When the user activates the direction button
|
||||
Then GET ...&sort=<sort>&page=1 is sent and, on success, the URL is <url>
|
||||
And the button shows arrow-up-narrow-wide when ascending and arrow-down-wide-narrow when descending, with the accessible name "Sort ascending" or "Sort descending" for the next action (proposed copy)
|
||||
|
||||
Examples:
|
||||
| from | sort | url |
|
||||
| /content/events | updated_at:asc | /content/events?sort=updated_at:asc |
|
||||
| /content/events?sort=updated_at:asc | updated_at:desc | /content/events |
|
||||
| /content/events?sort=id:desc | id:asc | /content/events?sort=id:asc |
|
||||
|
||||
Scenario Outline: Sort values in the URL
|
||||
When the user navigates to /content/events?sort=<value>
|
||||
Then <result>
|
||||
|
||||
Examples:
|
||||
| value | result |
|
||||
| created_at:asc | GET carries sort=created_at:asc and the select reads "Created" with the ascending direction icon |
|
||||
| title:asc | GET carries sort=updated_at:desc and the URL is replaced by /content/events |
|
||||
| data:asc | GET carries sort=updated_at:desc and the URL is replaced by /content/events |
|
||||
| id | GET carries sort=updated_at:desc and the URL is replaced by /content/events |
|
||||
|
||||
Scenario: Sort is kept across paging and size changes
|
||||
Given the URL is /content/events?sort=id:asc
|
||||
When the user activates Next, or changes the size
|
||||
Then every request carries sort=id:asc and the URL keeps it (a size change also resets the page)
|
||||
|
||||
Scenario: Switching to another type resets the page
|
||||
Given the user is on /content/events?page=3&size=50&sort=id:asc
|
||||
When the user opens /content/recipes from the sidebar
|
||||
Then the requests are for recipes with page=1, size=25 and sort=updated_at:desc, its own columns apply and no Events row shows meanwhile
|
||||
|
||||
Scenario: 4 Many types in the sidebar
|
||||
Given GET /v1/content-type returns 14 custom types, the 4th named "Frequently asked questions and answers"
|
||||
When the user opens /content/events
|
||||
Then on desktop the Content group shows "Content", the first 5 types and the selected one, the long name truncated, and "Show all 14"
|
||||
And on mobile the drawer shows the group expanded with "All content types 14" collapsed row
|
||||
And behaviour is as in features/schema_list_and_content_nav.feature
|
||||
|
||||
Scenario: 5 Loading
|
||||
Given the type and the entries have not resolved
|
||||
When the user navigates to /content/events
|
||||
Then the title row shows "Events" once the type has resolved and a skeleton until then, "New entry" is disabled and the toolbar is shown
|
||||
And the list is 8 skeleton rows on desktop (6 on mobile) with a 48 px row (68 px on mobile) and aria-busy="true"
|
||||
And when both resolve the rows replace the skeleton
|
||||
|
||||
Scenario: 6 Empty for this type
|
||||
Given GET .../entry resolves 200 with items [] and total 0
|
||||
When the user navigates to /content/events
|
||||
Then the empty state reads "No entries yet" with "Use New entry to add the first entry. Each entry follows the fields of this content type." and a "New entry" action
|
||||
And the toolbar stays, the pager, the summary and the count text do not show
|
||||
And "New entry" navigates to /content/events/new
|
||||
And an out-of-range page with total 0 shows this state and the URL becomes /content/events
|
||||
|
||||
Scenario Outline: 7 Error loading entries
|
||||
Given the type resolves 200 and GET .../entry <failure>
|
||||
When the user navigates to /content/events
|
||||
Then an error alert reads "Couldn't load entries" with "GET /v1/content-type/events/entry failed. Check your connection and try again." and a "Try again" action
|
||||
And no toolbar, no list and no pager show; the title row stays
|
||||
When the user activates "Try again"
|
||||
Then the skeleton (state 5) shows and the failed request is sent again
|
||||
|
||||
Examples:
|
||||
| failure |
|
||||
| resolves with a 500 response |
|
||||
| never reaches the server |
|
||||
|
||||
Scenario: Error loading the type
|
||||
Given GET /v1/content-type/events answers 500
|
||||
Then the same alert shows with "GET /v1/content-type/events failed. Check your connection and try again." (proposed copy)
|
||||
And "Try again" sends only the failed request again
|
||||
|
||||
Scenario Outline: 8 Forbidden (403)
|
||||
Given <which> answers 403
|
||||
When the user navigates to /content/events
|
||||
Then a centered state with the lock icon reads "You don't have access to Events" with "Your account can't open this content right now. If you think this is a mistake, ask an owner or an admin." and "Go to Home"
|
||||
And no toolbar or list shows and "Go to Home" navigates to /home
|
||||
And the title uses the type name when the type loaded, else the key
|
||||
|
||||
Examples:
|
||||
| which |
|
||||
| the entries request |
|
||||
| the type request |
|
||||
|
||||
Scenario Outline: 9 Type not found
|
||||
Given <which> answers 404 content_type_not_found
|
||||
When the user navigates to /content/unknown
|
||||
Then a centered state with the file-x icon reads "Content type not found" with "It may have been deleted, or the address may be mistyped." and "Go to Home"
|
||||
And the breadcrumb reads "Content" only, the mobile title is "Content" and no sidebar row is current
|
||||
And "Go to Home" navigates to /home
|
||||
|
||||
Examples:
|
||||
| which |
|
||||
| the type request |
|
||||
| the entries request |
|
||||
|
||||
Scenario: A deleted type behind the sidebar
|
||||
Given Recipes was deleted in features/schema_builder_delete.feature
|
||||
When the user opens /content/recipes
|
||||
Then the "Content type not found" state shows with no further request than the type's
|
||||
|
||||
Scenario: Session expired
|
||||
Given any of the requests answers 401
|
||||
Then the existing redirect to /login with the expired reason happens
|
||||
|
||||
Scenario: Stale answers are ignored
|
||||
Given a request for page 2 is in flight
|
||||
When the user changes the sort and that request resolves later
|
||||
Then its answer is dropped and only the latest request updates the list and the URL
|
||||
|
||||
Scenario: Updated by lookup
|
||||
Given the page has entries by users 3, 3 and 5
|
||||
Then GET /v1/user/lookup?ids=3,5 is sent once after the entries answer and the cells read the display names
|
||||
And when it answers 500 or lacks id 5 the cells read "–" and no error shows
|
||||
|
||||
Scenario: Navigation actions
|
||||
Given the populated state and an owner
|
||||
Then "New entry" and the first-cell links go to /content/events/new and /content/events/42, "Edit content type" goes to /schema/events
|
||||
And with a role other than owner or admin "Edit content type" is not rendered
|
||||
And below md "Edit content type" is not rendered and the New entry button is a floating button (hidden while loading and in the error state)
|
||||
|
||||
Scenario: Accessibility
|
||||
Then the table has a visually hidden caption "Events, sorted by last updated, newest first" ("sorted by {id|created|updated}, {ascending|descending}" otherwise; proposed copy, French entry)
|
||||
And "Columns", the direction button and the select have accessible names; the picker traps focus on mobile and is operable with Space and Esc
|
||||
And controls are 44 px on mobile and focus is a 2 px --ui-primary outline with a 2 px offset
|
||||
@@ -0,0 +1,52 @@
|
||||
# QA: Entry list of a custom content type (SPA slice 6)
|
||||
|
||||
Runner: Vitest + Vue Test Utils (`task test:web`). No Go test: both endpoints and /v1/user/lookup already exist and the backend does not change. Kit: reuse `views/__tests__/schemaTestKit.ts` (add GET /v1/content-type/{key}, GET .../entry with page/size/sort, and /v1/user/lookup handlers; Events with the 7 fields and 7/37 entries of SchemaFrame.dc.html). Pin the time zone; never freeze the system date.
|
||||
|
||||
## Automated
|
||||
|
||||
1. Composable (useContentTypes.spec): `getContentType(key)`; `listEntries(key, {page,size,sort})` builds the query, returns {items,total,page,size,sort}, passes status and plain text through (403, 404, 500), NetworkError passes through. `lookupUsers(ids)` sends the distinct ids once and returns display names.
|
||||
2. URL parsing (it.each): invalid/missing page, size, sort fall back to 1, 25, updated_at:desc and are replaced in the URL; defaults omitted; size and sort change reset page; the URL changes on success only.
|
||||
3. State 1 Populated: title, subtitle "events · 7 fields", toolbar, headers, first row values, "7 entries", no pager; singular "1 entry".
|
||||
4. State 2 Paginated (size=5, total 37): "Showing 1–5 of 37", "5 per page", pager; mobile "Page 1 of 8"; Next sends page=2 and updates the URL on success.
|
||||
5. Reuse of Articles pager behaviours (it.each): last page, loading page (aria-busy, disabled controls, "Loading page 2…"), error keeps rows with Retry, out-of-range redirect with notice, total 0 on out-of-range shows empty.
|
||||
6. Cells (it.each per field type): truncation, rich text first line, number alignment, Yes/No icon, date without shift, Choice tag, empty "–"; Created and Updated formats.
|
||||
7. Updated by: one lookup with distinct ids after the entries; "–" before it resolves, on failure and for an unknown id.
|
||||
8. State 3 Columns: popover on desktop (Reset only), sheet on mobile (Reset and Done); "4 of 6", sentence, rows with icon, label and key; the Created/updated row disabled; live column change with no request; cap at 6 with message and disabled rows; Esc/outside/Done close and return focus.
|
||||
9. Column persistence (it.each from the feature table): writes, Reset removes, unknown keys dropped, more than 6 truncated, invalid JSON, per-type keys, throwing/undefined localStorage, load never writes.
|
||||
10. Sort: the three options and the direction button (it.each), accessible names, URL and request, header arrow, sort kept across paging, invalid URL values replaced.
|
||||
11. State 4: with 14 types the sidebar shows 5 + selected + "Show all 14"; mobile drawer collapsed row "All content types 14" (sidebar logic itself stays in ContentNav.spec).
|
||||
12. State 5 Loading: skeleton rows (8 / 6), aria-busy, "New entry" disabled.
|
||||
13. State 6 Empty: copy, "New entry" navigates to /content/events/new, no pager.
|
||||
14. State 7 Error (500 and network): copy, "Try again" sends the failed request again; type-load failure variant.
|
||||
15. State 8 Forbidden (entries 403, type 403): copy, name fallback to the key, "Go to Home" goes to /home.
|
||||
16. State 9 Not found (type 404, entries 404): copy, breadcrumb "Content", no current sidebar row; deleted-type scenario.
|
||||
17. Navigation: New entry, first-cell links, mobile card link, "Edit content type" to /schema/events; hidden for a non-owner/admin and on mobile; mobile floating button hidden in loading and error.
|
||||
18. 401 redirect; stale answer dropped after a sort change; switching type resets page/size/sort and columns.
|
||||
19. Accessibility: caption text per sort, accessible names, keyboard on the picker and the select.
|
||||
20. French: every new string has an entry (i18n completeness spec passes).
|
||||
|
||||
## Visual (task visual:check -- content)
|
||||
|
||||
Register the group "5 Content and entry list" in `extraSources` if not registered. Every capture within 10 %, desktop and mobile, light and dark. Nothing is clock-sensitive. Mock every /v1 call including the sidebar's GET /v1/content-type and /v1/user/lookup.
|
||||
|
||||
| Board state | Setup in web/visual/states.ts | Board sample data |
|
||||
|---|---|---|
|
||||
| 1 Populated | /content/events, 7 entries (ROWS of SchemaFrame.dc.html), owner session | "Lime plaster workshop", "Marta Alves", "events · 7 fields", "7 entries" |
|
||||
| 2 Paginated, 5 per page | /content/events?size=5, total 37, 5 items | "Showing 1–5 of 37", "Page 1 of 8" (mobile) |
|
||||
| 3 Columns menu | /content/events, step: click "Columns" | "4 of 6", Title, Starts on, Ends on, Online checked |
|
||||
| 4 Many types | /content/events with 14 types (CT list of the board); mobile: open the drawer and expand the group | "Frequently asked questions and answers", "Show all 14" |
|
||||
| 5 Loading | entries `hang: true` | skeleton rows |
|
||||
| 6 Empty | entries total 0 | "No entries yet" |
|
||||
| 7 Error | entries 500 | "Couldn't load entries" |
|
||||
| 8 Forbidden | entries 403 | "You don't have access to Events" |
|
||||
| 9 Type not found | /content/unknown, type 404 content_type_not_found | "Content type not found" |
|
||||
|
||||
Board caveats to report, never hide: the mobile card shows a Category tag that the default 4 columns do not include; the desktop picker is drawn without Done; the mobile frames hide "Edit content type", so mobile has no path to the builder (design follow-up).
|
||||
|
||||
## Manual
|
||||
|
||||
- Real backend, owner and a non-owner/admin if one exists: list a type with 37 entries; sort, page, change size; reload keeps the URL state.
|
||||
- Columns: choose 6, reload, switch type and back; clear localStorage and see the default.
|
||||
- Click "New entry" and a row: the 404 page is expected until the editor slice; Back returns to the list with its URL.
|
||||
- Keyboard: tab order toolbar (select, direction, Columns, Edit), table links, pager; the picker and the sheet focus order; hover tooltip on truncated text.
|
||||
- Delete a type in another tab, then reload /content/<key>: not found page.
|
||||
@@ -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
|
||||
@@ -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,516 @@
|
||||
Feature: Create a custom content type in the Schema builder
|
||||
As an owner or admin
|
||||
I want to define a new content type (name, key and ordered fields) on /schema/new
|
||||
So that users can write entries of that type
|
||||
|
||||
Background:
|
||||
Given the SPA calls the API with relative URLs under /v1 and the "jwt" HttpOnly cookie
|
||||
And API errors are plain text
|
||||
And POST /v1/content-type takes {key, name, fields[{key, label, type, required, unique, default, min, max, options}]}
|
||||
And the builder never sends an "icon" key
|
||||
And POST answers 201 with the content type, 400 invalid_content_type_key, 409 content_type_key_taken, 422 invalid_field, 403 or 500
|
||||
And the route /schema/new is declared before /schema/:key, has meta auth "verified" and title "Schema", and renders the builder
|
||||
And a route meta flag, not a path pattern, tells the shell that /schema/new needs the custom list only
|
||||
And only owners and admins can use Schema; the SPA decides from the session role, the API still enforces it
|
||||
And the six field types are text "Text", richtext "Rich text", number "Number", boolean "Yes or no", date "Date" and select "Choice"
|
||||
And the limits are a type name of up to 100 characters, a type key of 2 to 40, 1 to 50 fields, a field key of up to 40 characters and 1 to 50 choices
|
||||
And the layout is: Name and Key with the status chip, Discard and Save on top; the FieldList on the left; the FieldInspector on the right; the ApiPreview at the bottom
|
||||
And below 48rem the FieldList is the page, the FieldInspector is a 92% bottom sheet closed with "Done", the ApiPreview is a bottom sheet, and Discard and Save sit in a bottom bar
|
||||
And every string goes through t() and has a French entry in i18n/messages.ts
|
||||
And a copy tagged "(proposed copy)" is not in the design and is the coder's single point of change
|
||||
|
||||
Scenario: Reaching the builder
|
||||
Given the Schema list is Populated or Empty
|
||||
When the user activates "New content type" (header button, empty-state button or the mobile floating button)
|
||||
Then the router navigates to /schema/new
|
||||
And the builder is shown, not the "Content type not found" page
|
||||
And /schema/events and /schema/unknown still show "Content type not found" for a key that is not built-in
|
||||
|
||||
Scenario: Roles and sessions
|
||||
Given <who> opens /schema/new
|
||||
Then <result>
|
||||
|
||||
Examples:
|
||||
| who | result |
|
||||
| a verified owner or admin | the builder |
|
||||
| a verified user who is neither | "You don't have access to Schema" with "Go to Home", URL unchanged |
|
||||
| an unverified user | the redirect to /register/pending |
|
||||
| a signed-out visitor | the redirect to /login |
|
||||
|
||||
Scenario: The builder needs no built-in list
|
||||
Given an owner opens /schema/new as the first page of the session
|
||||
Then GET /v1/content-type is called once for the sidebar
|
||||
And GET /v1/builtin-type is never called
|
||||
And the builder is shown as soon as the session is ready, with no skeleton
|
||||
|
||||
Scenario: New type, desktop (design state 1)
|
||||
Given an owner opens /schema/new on a 1440 px viewport
|
||||
Then the breadcrumb is "Schema" (a link to /schema) then "New content type"
|
||||
And "Name" is an empty text input with the placeholder "For example, Events", marked required, with maxlength 100
|
||||
And "Key" is a read-only mono input with the placeholder "events" and the help "Used in URLs and the API. Lowercase letters, digits and hyphens. It can't change after you save."
|
||||
And the list header reads "Fields" and "1 of 50"
|
||||
And one row is shown with the label "Title" and the key "title" in mono, selected, with the badge "New"
|
||||
And "Add field" is shown under the list
|
||||
And the inspector title is "Field: Title" with the badge "New"
|
||||
And "Label" holds "Title"
|
||||
And "Key" holds "title" with the Auto badge and the help "The name used in the API. Starts with a letter. Lowercase letters, digits and underscores."
|
||||
And the type tiles show Text selected
|
||||
And "Required" is off with "An entry can't be saved with this field empty."
|
||||
And "Unique values" is off
|
||||
And "Default value" is empty with "Used when an entry is created and this field is left out."
|
||||
And "Shortest" and "Longest" are empty with "Counted in characters. Entries show a counter."
|
||||
And "Save" and "Discard" are disabled
|
||||
And no status chip is shown
|
||||
And no "entries use this content type" bar is shown
|
||||
And the API preview bar is collapsed
|
||||
|
||||
Scenario: New type, mobile (design state 1)
|
||||
Given the same page on a 390 px viewport
|
||||
Then the topbar shows an arrow-left and the title "New content type"
|
||||
And Name and Key are stacked above the list, then the rows, then the "API preview" row with a chevron
|
||||
And no inspector is shown until a row is activated
|
||||
And the bottom bar holds Discard and Save
|
||||
|
||||
Scenario Outline: The key follows the name until it is edited
|
||||
Given an empty new type
|
||||
When the user types the name "<name>"
|
||||
Then the Key holds "<key>" with the Auto badge, read-only
|
||||
|
||||
Examples:
|
||||
| name | key |
|
||||
| Events | events |
|
||||
| Press mentions | press-mentions |
|
||||
| Café & Bar | cafe-bar |
|
||||
| Job openings! | job-openings |
|
||||
| 2026 Awards | 2026-awards |
|
||||
| !!! | (empty, mode empty) |
|
||||
| a name of 60 letters | the first 40 characters, without a trailing hyphen |
|
||||
|
||||
Scenario: Editing and resetting the key
|
||||
Given the name "Events" and the Auto key "events"
|
||||
When the user activates the pencil
|
||||
Then the Key becomes editable, the Auto badge goes and "Reset to match the name" is shown
|
||||
When the user types the key "agenda" then edits the name to "Events and talks"
|
||||
Then the Key stays "agenda"
|
||||
When the user activates "Reset to match the name"
|
||||
Then the Key is "events-and-talks" with the Auto badge
|
||||
|
||||
Scenario Outline: Type-level rules (design states 6 and 14)
|
||||
Given a new type with a valid field
|
||||
When the user sets <input> to <value> and activates Save
|
||||
Then <message> is shown under <input> with an alert icon
|
||||
And POST /v1/content-type is not called
|
||||
|
||||
Examples:
|
||||
| input | value | message |
|
||||
| Name | (empty or spaces) | Give the content type a name. |
|
||||
| Key | e | Use 2 to 40 lowercase letters, digits or hyphens. |
|
||||
| Key | Events | Use 2 to 40 lowercase letters, digits or hyphens. |
|
||||
| Key | my_type | Use 2 to 40 lowercase letters, digits or hyphens. |
|
||||
| Key | -events | Use 2 to 40 lowercase letters, digits or hyphens. |
|
||||
| Key | events--2 | Use 2 to 40 lowercase letters, digits or hyphens. |
|
||||
| Key | new | The key "new" is reserved. Choose a different key. (proposed copy) |
|
||||
|
||||
Scenario Outline: Accepted type keys
|
||||
Given a new type with a valid field and the name "X"
|
||||
When the user types the key "<key>" and activates Save
|
||||
Then POST /v1/content-type is called with that key
|
||||
|
||||
Examples:
|
||||
| key |
|
||||
| ab |
|
||||
| press-mentions |
|
||||
| 2026-awards |
|
||||
| 40 lowercase letters |
|
||||
|
||||
Scenario: Type-level errors together (design state 6)
|
||||
Given a new type with no name, the key "e" and no field
|
||||
When the user activates Save
|
||||
Then "Give the content type a name.", "Use 2 to 40 lowercase letters, digits or hyphens." and "A content type needs at least one field." are shown
|
||||
And the empty list shows "No fields yet" with the message in the error colour
|
||||
And the chip reads "3 problems to fix"
|
||||
And Save is disabled until all three are fixed, and Discard stays enabled
|
||||
And the inspector shows "Field settings" and "Add a field, then choose its type and rules here."
|
||||
|
||||
Scenario: When errors are shown
|
||||
Given a new type whose name is empty
|
||||
Then no error is shown while nothing was edited
|
||||
When the user edits an input, an error for that input shows as they type
|
||||
And when the user activates Save, every error of the form shows at once
|
||||
And errors are tied to their input with aria-describedby and aria-invalid
|
||||
And a row with an error shows an alert icon, not only the red border
|
||||
|
||||
Scenario Outline: The status chip
|
||||
Given <situation>
|
||||
Then the chip reads "<chip>"
|
||||
|
||||
Examples:
|
||||
| situation | chip |
|
||||
| a pristine new type | (no chip) |
|
||||
| an edit with no error | Unsaved changes |
|
||||
| three inputs in error | 3 problems to fix |
|
||||
| one input in error | 1 problem to fix |
|
||||
| the POST in flight | Saving… |
|
||||
| the POST failed with 500 | Save failed |
|
||||
| navigator.onLine is false | Waiting for connection |
|
||||
|
||||
Scenario Outline: Counting problems
|
||||
Given <errors>
|
||||
Then the chip counts <count>
|
||||
|
||||
Examples:
|
||||
| errors | count |
|
||||
| no name, a one-letter key, no field | 3 |
|
||||
| a field with no label, a field with min above max, a choice list with a blank and a duplicate | 3 |
|
||||
| one choice list with a blank row and a duplicate row | 1 |
|
||||
| one field with a bad key | 1 |
|
||||
|
||||
Scenario: Field list rows
|
||||
Given a type with the fields Title, Starts on, Online
|
||||
Then each row shows a grip button labelled "Move <label>", the icon box of its type, the label and the key in mono
|
||||
And an unselected row shows its badges "New", "Required", "Unique" and an alert icon when in error
|
||||
And the selected row is on the sand background and shows Move up, Move down and Remove
|
||||
And a field without a label reads "Untitled field" and a field without a key reads "–"
|
||||
|
||||
Scenario: Adding a field
|
||||
Given the list has 1 field
|
||||
When the user activates "Add field"
|
||||
Then a row is appended, selected, with a Text type and no label, and the label input is focused
|
||||
And the header reads "2 of 50"
|
||||
And at 50 fields "Add field" is disabled and the header reads "50 of 50"
|
||||
|
||||
Scenario Outline: Field key from the label
|
||||
Given a new field is selected
|
||||
When the user types the label "<label>"
|
||||
Then its Key holds "<key>" with the Auto badge
|
||||
|
||||
Examples:
|
||||
| label | key |
|
||||
| Title | title |
|
||||
| Starts on | starts_on |
|
||||
| Éléments | elements |
|
||||
| Ends on (date) | ends_on_date |
|
||||
| 2nd room | nd_room |
|
||||
| Title (when "title" exists)| title_2 |
|
||||
| a label of 60 letters | the first 40 characters |
|
||||
|
||||
Scenario Outline: Field key rules (design state 7)
|
||||
Given a new field is selected with the Key in manual mode
|
||||
When the user types the key "<key>"
|
||||
Then <outcome>
|
||||
|
||||
Examples:
|
||||
| key | outcome |
|
||||
| Title | "Start with a letter. Use lowercase letters, digits and underscores." under Key |
|
||||
| 1st | the same message |
|
||||
| a-b | the same message |
|
||||
| a b | the same message |
|
||||
| (empty) | the same message |
|
||||
| starts_on | no error |
|
||||
| a | no error |
|
||||
| a_40_characters | no error, and a 41st character cannot be typed |
|
||||
|
||||
Scenario: Duplicate field keys
|
||||
Given two fields whose keys are both "title" in manual mode
|
||||
Then "Another field already uses this key." (proposed copy) is shown under the Key of the second field
|
||||
And the chip counts one problem for that field
|
||||
|
||||
Scenario: A single field key error (design state 7)
|
||||
Given a new field with the key "start-date" and everything else valid
|
||||
Then the Key shows the error with the alert icon and the chip reads "1 problem to fix"
|
||||
And Save is disabled
|
||||
|
||||
Scenario Outline: The inspector follows the type
|
||||
Given a new field of type "<type>"
|
||||
Then the limits are labelled <limits>
|
||||
And "Unique values" is <unique>
|
||||
And the default control is <default>
|
||||
|
||||
Examples:
|
||||
| type | limits | unique | default |
|
||||
| text | "Shortest" and "Longest" with the suffix "characters" | available | a text input, placeholder "No default" |
|
||||
| richtext | "Shortest" and "Longest" with the suffix "characters" | disabled with "Not available for rich text." | a textarea, placeholder "No default" |
|
||||
| number | "Lowest value" and "Highest value" | available | a number input, placeholder "No default" |
|
||||
| boolean | none; "Yes or no fields have no limits." | disabled with "Not available for yes or no fields." | the switch "On by default" with help "New entries start with this switch off when the field is left out." |
|
||||
| date | "Earliest date" and "Latest date" | available | a date input, placeholder "No default" |
|
||||
| select | none; "Limits come from the choices below." | available | a select of the choices, placeholder "None" |
|
||||
|
||||
Scenario: Type tiles
|
||||
Given the inspector of a new field
|
||||
Then six radio tiles are shown, each with its icon, name and description
|
||||
| tile | icon | description |
|
||||
| Text | type | Short text, like a title or a name |
|
||||
| Rich text | pilcrow | Long text with formatting, written in Markdown|
|
||||
| Number | hash | Whole or decimal numbers |
|
||||
| Yes or no | toggle-left | An on or off switch |
|
||||
| Date | calendar | A calendar day, without a time |
|
||||
| Choice | list | One option from a list you define |
|
||||
And the selected tile is on the sand background
|
||||
And the help under "Longest" reads "Counted in characters. Entries show a counter." for Text and Rich text, and "Entries outside the range are refused." for Number and Date
|
||||
|
||||
Scenario: Changing the type of a new field
|
||||
Given a Number field with min 1, max 5000, default 20 and unique on
|
||||
When the user picks the tile "Yes or no"
|
||||
Then the label, the key and Required are kept
|
||||
And min, max, default, options and unique are reset
|
||||
When the user picks "Choice"
|
||||
Then the choice list editor is shown with no choice
|
||||
|
||||
Scenario Outline: Field rules
|
||||
Given a new field of type "<type>" with <settings>
|
||||
Then <message> is shown under <where>
|
||||
|
||||
Examples:
|
||||
| type | settings | message | where |
|
||||
| text | an empty label or spaces | Give the field a label. | Label |
|
||||
| number | min 6000, max 5000 | Lowest value can't be above the highest value. | the limits |
|
||||
| text | min 10, max 3 | Shortest can't be longer than longest. (proposed copy) | the limits |
|
||||
| date | min 2027-12-31, max 2026-01-01 | Earliest date can't be after the latest date. (proposed copy) | the limits |
|
||||
| text | min 2.5 | Use a whole number, 0 or more. (proposed copy) | the limit |
|
||||
| text | min -1 | Use a whole number, 0 or more. (proposed copy) | the limit |
|
||||
| number | min 1, max 5000, default 0 | The default value is outside the limits. (proposed copy) | Default value |
|
||||
| text | max 3, default "abcd" | The default value is outside the limits. (proposed copy) | Default value |
|
||||
| select | no choice | Add at least one choice. (proposed copy) | the choice list|
|
||||
| select | a blank choice | Choices can't be blank. | that row |
|
||||
| select | "Talk" twice | Two choices are the same. | the second row |
|
||||
| number | min 1, max 5000 | no error | - |
|
||||
| number | min 5, max 5 | no error | - |
|
||||
| text | min 0 | no error | - |
|
||||
|
||||
Scenario: Unique and default
|
||||
Given a Text field with the default "Draft"
|
||||
When the user turns "Unique values" on
|
||||
Then the Default value input is disabled with "A field with unique values can't have a default."
|
||||
And the default is not sent
|
||||
When the user turns "Unique values" off
|
||||
Then the default "Draft" is back
|
||||
|
||||
Scenario: Choice list editor (design state 8)
|
||||
Given a Choice field with the choices Talk, Workshop, Meetup
|
||||
Then "Choices" is shown with the required marker and "3 of 50"
|
||||
And each choice is a row with a grip, a text input, Remove, and the placeholder "Choice"
|
||||
And an input "Add a choice" with the button "Add" is shown
|
||||
And the help reads "Add 1 to 50 choices. Each one needs a different name. Removing a choice that entries use will be refused when you save."
|
||||
When the user types "Panel" in "Add a choice" and activates Add (or presses Enter)
|
||||
Then the choice is appended and the input is emptied and keeps the focus
|
||||
And the Default value select lists the choices
|
||||
When the selected default choice is removed or renamed
|
||||
Then the default is cleared
|
||||
|
||||
Scenario: Choice list limits and errors
|
||||
Given a Choice field with 5 choices, the fourth blank and the fifth equal to the first
|
||||
Then "Choices can't be blank." is shown under the fourth row and "Two choices are the same." under the fifth, each with an alert icon
|
||||
And the field counts as one problem
|
||||
And at 50 choices the Add button is disabled
|
||||
And choices are compared after trimming, case-sensitively
|
||||
|
||||
Scenario: Reordering choices
|
||||
Given a Choice field with 3 choices
|
||||
When the user uses the grip of the second choice
|
||||
Then Move up and Move down work as for fields, with the same live region ("Moving Workshop. Position 2 of 3. ...")
|
||||
|
||||
Scenario: Removing a field
|
||||
Given a list with 3 fields
|
||||
When the user activates Remove on the selected one
|
||||
Then it disappears with no undo row (an undo row only exists for saved fields, slice 4)
|
||||
And the next row is selected, or the previous one at the end, or none if the list is empty
|
||||
And the header counts one less
|
||||
|
||||
Scenario Outline: Moving fields with the buttons
|
||||
Given a list Title, Starts on, Ends on with <selected> selected
|
||||
When the user activates <button>
|
||||
Then the order becomes <order>
|
||||
And the selected row stays selected and keeps the focus on the same button when possible
|
||||
|
||||
Examples:
|
||||
| selected | button | order |
|
||||
| Starts on | Move up | Starts on, Title, Ends on |
|
||||
| Starts on | Move down | Title, Ends on, Starts on |
|
||||
|
||||
Scenario Outline: Disabled ends
|
||||
Given a list of 3 fields with <row> selected
|
||||
Then <button> is disabled
|
||||
|
||||
Examples:
|
||||
| row | button |
|
||||
| Title | Move up |
|
||||
| Ends on | Move down |
|
||||
|
||||
Scenario: Keyboard reorder (design state 9)
|
||||
Given the list Title, Starts on, Ends on
|
||||
When the user focuses the grip "Move Starts on" and presses Space
|
||||
Then the row is picked up with the primary outline
|
||||
And the polite live region reads "Moving Starts on. Position 2 of 3. Press Up or Down to move, Space to drop, Esc to cancel."
|
||||
When the user presses Up
|
||||
Then the row is first and the live region reads "Moving Starts on. Position 1 of 3. ..."
|
||||
When the user presses Space
|
||||
Then the new order is kept and the live region announces the drop
|
||||
When the user picks it up again, moves it and presses Esc
|
||||
Then the order returns to what it was before the pick-up
|
||||
|
||||
Scenario: No pointer drag in this slice
|
||||
Then rows cannot be dragged with the pointer
|
||||
|
||||
Scenario: Selecting a field on mobile
|
||||
Given a 390 px viewport
|
||||
When the user activates a row
|
||||
Then a bottom sheet titled "Field: <label>" opens with the inspector, Move up, Move down and Remove (proposed placement), and a "Done" button
|
||||
And focus moves to the sheet title
|
||||
When the user activates Done
|
||||
Then the sheet closes and the focus returns to the row
|
||||
|
||||
Scenario: API preview (design state 10)
|
||||
Given the type key "events" and the fields Title, Starts on, Online, Capacity, Category
|
||||
When the user opens "API preview"
|
||||
Then the panel shows "Where entries of this type live" with these five routes
|
||||
| GET | /v1/content-type/events/entry |
|
||||
| POST | /v1/content-type/events/entry |
|
||||
| GET | /v1/content-type/events/entry/{id} |
|
||||
| PUT | /v1/content-type/events/entry/{id} |
|
||||
| DELETE | /v1/content-type/events/entry/{id} |
|
||||
And "A sample entry. Values come from each field's type and default." with the JSON of a sample entry
|
||||
And "Updates as you edit. Fields you add or remove here appear after you save."
|
||||
And the collapsed bar shows "API preview", "GET /v1/content-type/events/entry" in mono and "Copy JSON"
|
||||
And the key falls back to "events" while the Key is empty
|
||||
|
||||
Scenario Outline: Sample values in the preview
|
||||
Given a field "f" of type "<type>" with <settings>
|
||||
Then the sample entry data holds <value> for "f"
|
||||
|
||||
Examples:
|
||||
| type | settings | value |
|
||||
| text | no default | "Example text" |
|
||||
| text | default "Draft" | "Draft" |
|
||||
| richtext | no default | "Markdown text" |
|
||||
| number | no default, no min | 0 |
|
||||
| number | min 1 | 1 |
|
||||
| number | min 1, default 20 | 20 |
|
||||
| boolean | no default | false |
|
||||
| boolean | on by default | true |
|
||||
| date | no default | "2026-11-21" |
|
||||
| select | choices Talk, Workshop | "Talk" |
|
||||
| select | default "Workshop" | "Workshop" |
|
||||
| select | no choice yet | null |
|
||||
|
||||
Scenario: The sample entry envelope and live updates
|
||||
Then the sample is {"id": 42, "content_type": <key>, "data": {...}, "created_by": 3, "updated_by": 3, "created_at": "2026-10-15T11:02:00Z", "updated_at": "2026-10-15T11:02:00Z"} indented by 2 spaces
|
||||
And the data keys follow the field order and skip fields without a valid key
|
||||
And it updates on every edit, reorder and removal
|
||||
And it contains no date from the clock
|
||||
|
||||
Scenario: Copy JSON
|
||||
When the user activates "Copy JSON"
|
||||
Then the sample entry JSON is written to the clipboard
|
||||
And the button reads "Copied" for 2 seconds, then "Copy JSON" again
|
||||
And the same happens in the mobile sheet
|
||||
|
||||
Scenario: API preview on mobile
|
||||
Given a 390 px viewport
|
||||
When the user activates the row "API preview"
|
||||
Then a bottom sheet titled "API preview" shows "GET /v1/content-type/events/entry", the JSON and a full-width "Copy JSON" button
|
||||
|
||||
Scenario: Saving a valid type
|
||||
Given the name "Events", the key "events" and these fields
|
||||
| label | key | type | required | unique | default | min | max | options |
|
||||
| Title | title | text | true | true | | | 80 | |
|
||||
| Starts on | starts_on | date | true | false | | 2026-01-01 | 2027-12-31 | |
|
||||
| Online | online | boolean | false | false | on | | | |
|
||||
| Capacity | capacity | number | false | false | 20 | 1 | 5000 | |
|
||||
| Category | category | select | false | false | Talk | | | Talk, Workshop, Meetup |
|
||||
| Description | description | richtext | false | false | | | 5000 | |
|
||||
When the user activates Save
|
||||
Then POST /v1/content-type is called once with the key "events", the name "Events" and the fields in list order
|
||||
And each field carries exactly key, label, type, required, unique, default, min, max, options
|
||||
And unset default, min and max are null, and options are [] for a non-select field
|
||||
And the boolean default is true, an off switch sends null, a date bound is "YYYY-MM-DD", the name is trimmed, choices are trimmed
|
||||
And the body has no "icon" key
|
||||
|
||||
Scenario: Saving (design state 11, create)
|
||||
Given the POST has not answered
|
||||
Then the chip reads "Saving…" with a loader, Save shows a loader and is disabled, Discard is disabled
|
||||
And Name, Key and the inspector are dimmed and not editable
|
||||
And Add field, the grips, the Move and Remove buttons are disabled
|
||||
And a second activation of Save sends no second request
|
||||
|
||||
Scenario: Saved (design state 12, create)
|
||||
Given the POST answers 201 with the content type "events" named "Events" and 6 fields
|
||||
Then a success toast "Content type saved" with "Events now has 6 fields." is shown
|
||||
And the content types store holds "events" in name order when its list was loaded
|
||||
And the sidebar Content group lists "Events"
|
||||
And the router replaces the URL with /schema, where the Events row is listed
|
||||
And no "Leave without saving?" prompt is shown
|
||||
And with one field the toast reads "Events now has 1 field." (proposed copy)
|
||||
|
||||
Scenario: Key already taken (design state 14)
|
||||
Given the name "Events", the key "events" and the fields Title (required) and Starts on (date)
|
||||
When the POST answers 409 with the body "content_type_key_taken"
|
||||
Then under Key: The key "events" is already used by another content type. Choose a different key.
|
||||
And the Key is editable (manual mode), has the error and the focus, and the Auto badge is hidden
|
||||
And the chip reads "1 problem to fix" and Save is disabled
|
||||
And the fields and the name are untouched
|
||||
When the user edits the key
|
||||
Then the error goes and Save is enabled
|
||||
|
||||
Scenario: The server refuses a key or a field
|
||||
Given the POST answers <status> with <body>
|
||||
Then <outcome>
|
||||
|
||||
Examples:
|
||||
| status | body | outcome |
|
||||
| 400 | invalid_content_type_key | the key message under Key, as in the rules above |
|
||||
| 422 | invalid_field | the banner "Check the fields marked in the list." (proposed title and placement), edits kept |
|
||||
| 403 | Only ... | the page "You don't have access to Schema" |
|
||||
| 401 | (any) | the existing redirect to /login with the expired reason |
|
||||
|
||||
Scenario Outline: Save failed (design state 13)
|
||||
Given the POST <failure>
|
||||
Then an error alert titled "Couldn't save the content type" shows "Something went wrong on our side. Your changes are still here. Try again in a moment."
|
||||
And it has a "Try again" action and the chip reads "Save failed"
|
||||
And every edit is kept and Save stays enabled
|
||||
When the user activates "Try again"
|
||||
Then the same body is sent again
|
||||
|
||||
Examples:
|
||||
| failure |
|
||||
| answers 500 |
|
||||
| fails (network) |
|
||||
|
||||
Scenario: Offline (design state 16)
|
||||
Given the user has edited the form and navigator.onLine becomes false
|
||||
Then the banner "You're offline. Changes will be saved when you reconnect." with a wifi-off icon is shown
|
||||
And the chip reads "Waiting for connection"
|
||||
And Save is disabled and every edit is kept
|
||||
When the connection returns
|
||||
Then the banner goes, Save is enabled again and nothing is sent by itself
|
||||
|
||||
Scenario: Discard
|
||||
Given the user has edited the form
|
||||
When the user activates Discard
|
||||
Then Name and Key are empty, the list holds the starter field Title, errors and the chip are cleared
|
||||
And nothing is sent and the URL stays /schema/new
|
||||
And Discard and Save are disabled again
|
||||
|
||||
Scenario Outline: Leaving with unsaved edits
|
||||
Given <state>
|
||||
When the user leaves through the breadcrumb, the mobile arrow, the sidebar or the browser back
|
||||
Then <result>
|
||||
|
||||
Examples:
|
||||
| state | result |
|
||||
| a pristine form | the router navigates with no prompt |
|
||||
| an edited name, key or field | the dialog "Leave without saving?" with "Keep editing" and "Discard changes" is shown |
|
||||
| after Save answered 201 | the router navigates with no prompt |
|
||||
|
||||
Scenario: Keep editing or discard on leave
|
||||
Given the leave dialog is open
|
||||
When the user chooses "Keep editing" (or dismisses the dialog)
|
||||
Then the user stays on /schema/new with every edit
|
||||
When the user chooses "Discard changes"
|
||||
Then the router navigates away
|
||||
|
||||
Scenario: Accessibility of the builder
|
||||
Then every control has a visible label
|
||||
And the type tiles are a radio group
|
||||
And the field list is one tab stop and arrow keys move between rows
|
||||
And controls are 44 px high on mobile
|
||||
And focus is a 2 px ring in the primary colour
|
||||
@@ -0,0 +1,82 @@
|
||||
# QA: Schema builder, create flow (SPA slice 3)
|
||||
|
||||
Runner: Vitest + Vue Test Utils (`task test:web`). No Go test: the POST /v1/content-type contract is already covered by features/custom_content_types.qa.md and nothing changes in the backend.
|
||||
Same pattern as features/schema_builtin_view.qa.md: mock `/v1` through the api composable (extend `views/__tests__/schemaTestKit.ts` with a POST handler and a configurable responder), mount with the real router and a resolved session whose role varies, use `components/__tests__/viewport.ts` for desktop (1440) and mobile (390), fake timers for the 2 s "Copied" and any delay. Never freeze the system date. Tests that touch the clipboard stub `navigator.clipboard.writeText`. Online/offline is driven by dispatching the window `offline` and `online` events.
|
||||
|
||||
## Automated
|
||||
|
||||
Fixtures: the three custom types and five built-in types of schemaTestKit; the "Events" form of the feature (6 fields) as the full-save case; a 201 response for it with id 4 and updated_at; the plain-text bodies `content_type_key_taken`, `invalid_content_type_key`, `invalid_field`.
|
||||
|
||||
Pure logic (suggested files lib/__tests__/schemaBuilder*.spec.ts; each rule table is an it.each over the feature's Examples):
|
||||
1. Type key derivation: the 7 name rows; empty result keeps the key empty.
|
||||
2. Field key derivation: the 7 label rows, including the `_2` suffix against an existing key and the 40-character cut.
|
||||
3. Type validation: name, key (the 7 rejected rows, the 4 accepted rows including 40 characters), fields count 0 / 1 / 50 / 51, reserved key "new".
|
||||
4. Field validation: label, key (8 rows), duplicate keys, limits ordering per type, whole non-negative limits for text, default against limits and length, choice rules (blank, duplicate after trim, none, 50 max), unique disabled for richtext and boolean, default dropped when unique. Assert each message string.
|
||||
5. Problem counting: the 4 rows of the feature (per field and per type-level input, never per message).
|
||||
6. Payload builder: the 6-field table gives the exact JSON, with null for unset values, [] options, boolean off to null, trimmed name and choices, ISO date bounds, no "icon", no unique default.
|
||||
7. Sample entry: the 12 value rows, the envelope with fixed ids and timestamps, key fallback "events", field order, skipped invalid keys, 2-space indentation.
|
||||
8. Type change reset (Number to Yes or no to Choice).
|
||||
|
||||
Store (extend stores/__tests__/contentTypes.spec.ts):
|
||||
9. add(type) inserts by name order when status is "ready", does nothing when "idle" (the next load returns it), does not touch built-in items, and does not trigger a request.
|
||||
|
||||
Composable and API (extend composables/__tests__/useContentTypes.spec.ts):
|
||||
10. createContentType posts JSON to /v1/content-type and returns the type; ApiError carries status and plain-text body for 400, 409, 422, 403, 500; NetworkError passes through.
|
||||
|
||||
Builder view (new views/__tests__/SchemaBuilderView.spec.ts and component specs for FieldList, FieldInspector, ChoiceList, ApiPreview), one test per feature scenario:
|
||||
11. Reaching the builder from the list button, the empty-state button and the mobile floating button; /schema/events and /schema/unknown still show "Content type not found".
|
||||
12. Roles: owner, admin, a role that is neither (403 page, no field shown), unverified and signed-out redirects (extend routerGuard.spec). Route registered before /schema/:key with the right meta, and GET /v1/builtin-type never called on /schema/new (assert the calls list).
|
||||
13. State 1 desktop: breadcrumb, Name and Key copy, "1 of 50", starter row, inspector copy, Save and Discard disabled, no chip, collapsed API bar, no "entries use" bar.
|
||||
14. State 1 mobile: topbar arrow-left and title, stacked Name and Key, "API preview" row, bottom bar, no inspector.
|
||||
15. Auto key and manual key: pencil, Auto badge, reset, key stays after a name edit.
|
||||
16. Type-level errors (it.each of the 7 rows) and state 6 together: the three messages, "No fields yet", "3 problems to fix", Save disabled then enabled after fixes, Discard enabled.
|
||||
17. When errors appear: none on a pristine form; per input while typing; all on Save; aria-describedby and aria-invalid wiring; alert icon on a row in error.
|
||||
18. Chip table (7 rows).
|
||||
19. Field list: row content, badges, selected row buttons, "Untitled field" and "–".
|
||||
20. Add field: appended, selected, label focused, counter, disabled at 50.
|
||||
21. Inspector per type (it.each over 6 types): labels, unique state with its message, default control, help texts, tiles with icons and descriptions; type change reset.
|
||||
22. Field rules (it.each over the Examples), unique and default interaction, key rules (state 7) and duplicate key.
|
||||
23. Choice list: add by button and Enter with focus kept, remove, reorder, default cleared on remove or rename, blank and duplicate flags, 50 cap, counter.
|
||||
24. Removing a field: selection moves, no undo row, empty list state.
|
||||
25. Move buttons and disabled ends (it.each); keyboard reorder: Space, Up, Down, Space and Esc, live region text at each step, order restored on Esc. Assert no drag handler on rows.
|
||||
26. Mobile sheets: row opens the field sheet with Done, focus to the title and back; API sheet with Copy JSON.
|
||||
27. API preview: routes, texts, sample JSON live update, key fallback, collapsed bar, Copy JSON writes the exact JSON and shows "Copied" for 2 s (fake timers).
|
||||
28. Save: the exact POST body, one request on double activation, the Saving state (dimmed, disabled controls, loader).
|
||||
29. Success: toast copy including the singular, store.add, sidebar item, router.replace('/schema'), no leave prompt, the list shows the new row without a second GET /v1/content-type.
|
||||
30. Key taken: 409 message, key editable with focus and no Auto badge, "1 problem to fix", Save disabled, enabled again after an edit.
|
||||
31. Server refusals: 400 invalid_content_type_key, 422 invalid_field banner, 403 page, 401 redirect.
|
||||
32. Save failed: 500 and network, banner copy, edits kept, "Try again" resends the same body.
|
||||
33. Offline: banner copy, chip, Save disabled, edits kept, recovery without any request.
|
||||
34. Discard resets to the blank form and sends nothing.
|
||||
35. Leave guard: pristine, edited, after save; Keep editing, dismiss and Discard changes.
|
||||
|
||||
Existing tests to update:
|
||||
36. features/schema_builtin_view.qa.md item 11 and SchemaTypeView.spec: remove /schema/new from the "Unknown key" it.each (it is now the builder).
|
||||
37. French: every new string has a French entry (the existing i18n completeness spec must pass).
|
||||
|
||||
## Visual (task visual:check -- schema)
|
||||
|
||||
Run `task visual:check -- schema`; every capture within 10 % at desktop and mobile, light and dark. Nothing in the covered states is clock-sensitive. Mock GET /v1/auth/me (owner "Marta Alves") and GET /v1/content-type (the 3 custom types) with the sidebar mock of the existing Schema states, plus every other /v1 call the page makes. The shell and sidebar are the board's `AppFrame`; if the board marks the sidebar differently from the SPA, report it, do not fix it silently.
|
||||
|
||||
Setups to add in `web/visual/states.ts` (screen `schema`):
|
||||
|
||||
| Board state | Setup | Sample data (from the frame) |
|
||||
|---|---|---|
|
||||
| New type | open /schema/new, no steps | empty name and key (placeholders "For example, Events" and "events"), starter field Title/title, Text, optional |
|
||||
| Type-level errors | open /schema/new; steps: edit the key and type "e", Remove the starter field, activate Save | empty name, key "e", no fields, chip "3 problems to fix" |
|
||||
| Key already taken | open /schema/new; mock POST /v1/content-type as 409 with the body `content_type_key_taken`; steps: type the name "Events", turn Required on for Title, Add field with the label "Starts on" and the Date tile (key starts_on), select the first row, activate Save | name "Events", key "events", fields Title (required) and Starts on (date), the key error, chip "1 problem to fix" |
|
||||
|
||||
Known visual differences to report, never hide: the missing `...` button (D15), the absent chip in the pristine state (Q2), and the Key help copy (Q1) if the board text is kept.
|
||||
|
||||
`skip: 'pending'` (drawn on the Events edit screen, which exists in slice 4): Editing an existing type, Locked key: tooltip, Unsaved changes, Field errors, Choice list editor, Keyboard reorder, API preview open, Saving, Saved, Save failed, Schema incompatible, Offline. Field key error (state 7) has no board frame: Vitest only. If check.ts demands an entry for it, add a pending skip, and report it.
|
||||
|
||||
The "Review and delete" group is slice 4/5: every state stays pending.
|
||||
|
||||
## Manual
|
||||
|
||||
- Keyboard: Tab order is Name, Key (pencil), Save, Discard, field list (one stop, arrows move between rows), inspector top to bottom, API preview. Screen reader (NVDA or VoiceOver): the live region reads each reorder step; the tile group announces its selected tile; errors are read with their input.
|
||||
- Focus ring on every control; hover and motion on rows, tiles, sheets and the Copy JSON button; sheet open and close focus return on a real phone.
|
||||
- Clipboard: Copy JSON pastes the exact sample entry in a real browser (permission prompt behaviour).
|
||||
- Real backend: as owner, then admin, create a type with all six field types including a Choice default and a unique Title. Check the type in `GET /v1/content-type`, in the sidebar Content group, and in the Schema list. Create the same key again for a real 409. Send an invalid body through curl to compare the 400 and 422 texts with the mapped messages.
|
||||
- Real offline: switch the browser offline, edit, reconnect, press Save.
|
||||
- Reload or close the tab with unsaved edits (not handled by the leave guard): note the browser behaviour.
|
||||
@@ -0,0 +1,157 @@
|
||||
Feature: Delete a custom content type from the Schema builder
|
||||
As an owner or admin
|
||||
I want to delete a custom type that has no entries
|
||||
So that unused types leave the schema, the API and the sidebar
|
||||
|
||||
Background:
|
||||
Given the SPA calls the API with relative URLs under /v1 and the "jwt" HttpOnly cookie
|
||||
And API errors are plain text
|
||||
And the edit builder, its store, entry count, leave guard, chip and banners of features/schema_builder_edit.feature are reused unchanged unless a scenario below says otherwise
|
||||
And DELETE /v1/content-type/{key} answers 204 with no body
|
||||
And DELETE answers 404 content_type_not_found, 409 content_type_has_entries, 403 or 500
|
||||
And the number of entries is the "total" already loaded from GET /v1/content-type/{key}/entry?page=1&size=5; no other request is made to open a dialog
|
||||
And the dialogs are DeleteTypeDialog (UModal + UAlert, color "error" on the destructive action; a bottom sheet on mobile) from docs/design/screens/schema.md group "3 Review and delete", states 5 to 7
|
||||
And every string goes through t() and has a French entry in i18n/messages.ts
|
||||
And a copy tagged "(proposed copy)" is not in the design and is the coder's single point of change
|
||||
|
||||
Scenario: The overflow menu (proposed placement, see open question 1)
|
||||
Given an owner opens /schema/recipes
|
||||
Then the top bar holds an icon button "More actions" (proposed copy) with the ellipsis icon, after Discard and Save on desktop and as the topbar action on mobile
|
||||
When the user activates it
|
||||
Then a menu opens with one item "Delete content type" with a trash-2 icon in the error colour
|
||||
And Esc or a click outside closes it and returns focus to the button
|
||||
|
||||
Scenario Outline: Where the menu is available
|
||||
Given <page>
|
||||
Then <result>
|
||||
|
||||
Examples:
|
||||
| page | result |
|
||||
| /schema/new | no overflow menu |
|
||||
| /schema/articles (built-in, read-only) | no overflow menu and no delete |
|
||||
| /schema/events (edit) | the overflow menu |
|
||||
|
||||
Scenario Outline: The menu is disabled while another action runs
|
||||
Given /schema/recipes and <state>
|
||||
Then the "More actions" button is disabled
|
||||
|
||||
Examples:
|
||||
| state |
|
||||
| the PUT is in flight (Saving, Applying) |
|
||||
| a delete is in flight |
|
||||
|
||||
Scenario: Blocked, the type has entries (design group 3, state 5)
|
||||
Given /schema/events has 37 entries
|
||||
When the user chooses "Delete content type"
|
||||
Then no request is sent
|
||||
And the dialog "You can't delete Events yet" opens with "A content type can only be deleted when it has no entries."
|
||||
And a warning alert reads "Events has 37 entries" with "Delete all of its entries first, then delete the content type."
|
||||
And the actions are "Close" and "View entries"; there is no delete button
|
||||
And the count is grouped like the info bar ("1,200 entries") and a single entry reads "Recipes has 1 entry" (proposed copy)
|
||||
|
||||
Scenario: View entries
|
||||
Given the blocked dialog or the fallback dialog is open
|
||||
When the user activates "View entries"
|
||||
Then the dialog closes and the router navigates to /content/events (see open question 4)
|
||||
|
||||
Scenario: Close the blocked dialog
|
||||
Given the blocked dialog is open
|
||||
When the user chooses "Close", the close icon or presses Esc
|
||||
Then the dialog closes, the page and every edit are unchanged and focus returns to the menu button
|
||||
|
||||
Scenario: Confirm, the type has no entries (design group 3, state 6)
|
||||
Given /schema/recipes has 0 entries
|
||||
When the user chooses "Delete content type"
|
||||
Then no request is sent
|
||||
And the dialog "Delete Recipes?" opens with "Recipes has no entries. Its fields and its API routes will be deleted. This can't be undone."
|
||||
And the body reads "Key: " then "recipes" in mono
|
||||
And the actions are "Cancel" and "Delete content type" (error colour)
|
||||
And Cancel, the close icon and Esc close it with nothing sent and focus returned to the menu button
|
||||
|
||||
Scenario: Deleting (proposed, see open question 3)
|
||||
Given the confirm dialog is open
|
||||
When the user activates "Delete content type"
|
||||
Then DELETE /v1/content-type/recipes is sent once
|
||||
And the button reads "Deleting…" with a loader, Cancel is disabled
|
||||
And Esc, the close icon and a click on the overlay do not dismiss the dialog
|
||||
And a second activation sends nothing
|
||||
|
||||
Scenario: Deleted
|
||||
Given DELETE answers 204
|
||||
Then the dialog closes
|
||||
And the content types store drops "recipes" (store.drop) with no GET /v1/content-type
|
||||
And the router navigates to /schema with no "Leave without saving?" prompt
|
||||
And a success toast "Content type deleted" with "Recipes was deleted." (proposed copy) is shown
|
||||
And the Schema list no longer shows Recipes and the sidebar Content group no longer lists it
|
||||
And no request to GET /v1/content-type/recipes/... is made afterwards
|
||||
|
||||
Scenario: Back or reload after a delete
|
||||
Given Recipes was deleted
|
||||
When the user opens /schema/recipes
|
||||
Then the page "Content type not found" with "It may have been deleted, or the address may be mistyped." is shown
|
||||
|
||||
Scenario: Server fallback, entries appeared (design group 3, state 7)
|
||||
Given the page loaded Recipes with 0 entries
|
||||
When the user confirms and DELETE answers 409 content_type_has_entries
|
||||
Then the dialog stays open with the title "Delete Recipes?" and the error alert "Recipes now has entries" with "Someone added an entry after this page loaded, so nothing was deleted. Delete the entries first, then try again."
|
||||
And the actions are "Close" and "View entries"; there is no delete button
|
||||
And the store still holds Recipes and the user stays on /schema/recipes
|
||||
And "Close" closes the dialog; the loaded count is not refreshed, so choosing "Delete content type" again opens the confirm dialog (see open question 2)
|
||||
|
||||
Scenario Outline: Other answers of DELETE
|
||||
Given the confirm dialog is open and DELETE <outcome>
|
||||
Then <result>
|
||||
|
||||
Examples:
|
||||
| outcome | result |
|
||||
| answers 404 content_type_not_found | the dialog closes, the store drops the type and the page "Content type not found" is shown (proposed, see open question 5) |
|
||||
| answers 403 "Only ..." | the dialog closes and the page "You don't have access to Schema" is shown |
|
||||
| answers 401 | the existing redirect to /login with the expired reason |
|
||||
| answers 500 or fails (network) | the dialog stays open with the error alert "Couldn't delete the content type" (proposed copy) and "Something went wrong on our side. Nothing was changed. Try again in a moment."; "Cancel" and "Delete content type" are enabled again and the store is untouched |
|
||||
|
||||
Scenario: Retry after a failure
|
||||
Given the dialog shows the 500 alert
|
||||
When the user activates "Delete content type"
|
||||
Then the same DELETE is sent again and the alert clears while it is in flight
|
||||
|
||||
Scenario: Offline
|
||||
Given the page is offline (the existing offline banner is shown)
|
||||
When the confirm dialog is open
|
||||
Then "Delete content type" is disabled and nothing is sent
|
||||
And when the connection returns it is enabled again and nothing is sent by itself
|
||||
|
||||
Scenario Outline: Unsaved edits and the delete (the leave guard)
|
||||
Given /schema/<key> with unsaved edits (chip "Unsaved changes")
|
||||
When the user chooses "Delete content type"
|
||||
Then the dialog is the one of the saved type's count, its copy never mentions the edits
|
||||
And opening it does not discard, validate or save the edits
|
||||
And <after>
|
||||
|
||||
Examples:
|
||||
| key | after |
|
||||
| recipes | on Cancel, Close, 409 and 500, the edits, the chip and the undo rows are exactly as they were |
|
||||
| recipes | on 204 the router leaves with no "Leave without saving?" prompt and the edits are discarded with the page |
|
||||
| events | the blocked dialog is shown for the saved count (37), and Close keeps every edit |
|
||||
|
||||
Scenario: Delete after a refused save
|
||||
Given the banner "Nothing was changed" is shown for Recipes
|
||||
When the user deletes the type with no entries
|
||||
Then the delete flow is the same and the banner goes with the page
|
||||
|
||||
Scenario: Session and role
|
||||
Given a user who is neither owner nor admin opens /schema/recipes
|
||||
Then the page "You don't have access to Schema" is shown and no menu exists
|
||||
And the API still answers 403 to DELETE for that user
|
||||
|
||||
Scenario: Accessibility of the delete flow
|
||||
Then the menu button has an accessible name and the menu is keyboard operable
|
||||
And dialogs trap focus, open with focus on the title and return it to "More actions" on close
|
||||
And while Deleting, focus stays on the dialog title
|
||||
And the destructive button is never the default focus (focus starts on Cancel or Close)
|
||||
And controls are 44 px high on mobile and focus is a 2 px ring in the primary colour
|
||||
|
||||
Scenario: Key error on a new field in the edit builder (design state 7, visual only)
|
||||
Given /schema/events and a field added with the label "Second date", type Date and the key "2nd-date"
|
||||
Then the board shows 8 fields, that row selected with the badge "New", the Key "2nd-date" with "Start with a letter. Use lowercase letters, digits and underscores." and the alert icon, and the chip "1 problem to fix"
|
||||
And Save is disabled
|
||||
And behaviour is as in schema_builder_edit.feature "A single field key error on a new field"
|
||||
@@ -0,0 +1,42 @@
|
||||
# QA: Schema builder, delete (SPA slice 5)
|
||||
|
||||
Runner: Vitest + Vue Test Utils (`task test:web`). No Go test: DELETE /v1/content-type/{key} is already covered by features/custom_content_types.qa.md and the backend does not change.
|
||||
Same kit as features/schema_builder_edit.qa.md (`views/__tests__/schemaTestKit.ts`: add a DELETE handler per status, plain-text bodies content_type_has_entries and content_type_not_found; Events with total 37, Recipes with 4 fields and total 0). Never freeze the system date.
|
||||
|
||||
## Automated
|
||||
|
||||
1. Composable (useContentTypes.spec): `deleteContentType(key)` sends DELETE to /v1/content-type/{key}, resolves on 204 with no body parsing, ApiError carries status and plain text for 404, 409, 403, 500; NetworkError passes through.
|
||||
2. Store: `remove(key)` drops the custom type, keeps order of the rest, never touches built-ins, makes no request, does nothing for an unknown key. reset() unchanged.
|
||||
3. Menu: shown in edit mode only (not /schema/new, not built-in view, not for a non-owner/admin); one item "Delete content type"; Esc closes and returns focus; disabled while Saving, Applying and Deleting.
|
||||
4. Blocked (total 37): no request; copy, warning alert, "Close" and "View entries", no delete button; singular and 1,200 grouping (proposed copy); Close/Esc/close icon keep edits; View entries navigates to /content/events.
|
||||
5. Confirm (total 0): no request; copy, "Key: recipes" in mono; Cancel/Esc/close icon send nothing; focus starts on Cancel.
|
||||
6. Deleting: one DELETE, "Deleting…" with loader, Cancel disabled, Esc/overlay/close icon do not dismiss, second activation sends nothing, focus on the title.
|
||||
7. Deleted: 204 closes the dialog, store.drop called, navigates to /schema with no leave prompt even with unsaved edits, toast copy, list and sidebar Content group no longer show the type, no GET /v1/content-type afterwards; reopening /schema/recipes shows "Content type not found".
|
||||
8. Fallback 409: dialog keeps title "Delete Recipes?", error alert copy, "Close" and "View entries", no delete button, store untouched, user stays on the page, edits kept.
|
||||
9. Other answers (it.each): 404 (dialog closes, store drops, not-found page), 403 (access page), 401 (redirect to /login with expired reason), 500 and network (alert copy in the dialog, store untouched, retry sends the same DELETE and clears the alert).
|
||||
10. Offline: Delete disabled with the dialog open, enabled on reconnect, nothing sent by itself.
|
||||
11. Unsaved edits: dialog uses the saved count; opening, Cancel, Close and failures leave edits, chip and undo rows unchanged; 204 leaves with no prompt; blocked dialog for Events keeps edits.
|
||||
12. Accessibility: focus return to "More actions", destructive button not default focus, menu keyboard use.
|
||||
13. Structural refactor (SchemaTypeView.vue, six flags simplified): no new behaviour. Every existing SchemaTypeView/SchemaBuilder spec, schema_builtin_view, create and edit specs pass unchanged with no edit to their assertions; if one needs a change, stop and report. The resolver outcomes (built-in, custom edit, create, not found, forbidden, loading, error) are covered by one it.each over the former flag combinations.
|
||||
14. French: every new string has an entry (i18n completeness spec passes).
|
||||
|
||||
## Visual (task visual:check -- schema)
|
||||
|
||||
Every capture within 10 %, desktop and mobile, light and dark. Register nothing new in `extraSources` (group "3 Review and delete" is already registered).
|
||||
|
||||
| Board state | Setup in web/visual/states.ts | Board sample data |
|
||||
|---|---|---|
|
||||
| Delete type: blocked | path /schema/events, steps: open "More actions", choose "Delete content type" | "You can't delete Events yet", "Events has 37 entries" |
|
||||
| Delete type: confirm | path /schema/recipes (Recipes 4 fields, entry total 0), same steps | "Delete Recipes?", "Key: recipes" |
|
||||
| Delete type: server fallback (409) | path /schema/recipes, DELETE mocked 409 content_type_has_entries, steps: open menu, choose item, "Delete content type" | "Recipes now has entries" |
|
||||
| Field key error | replace `skip: 'pending'`; path /schema/events (the board draws it in the edit builder, not /schema/new); steps: Add field, label "Second date", type Date, set key "2nd-date" | 8 fields, row selected, chip "1 problem to fix" |
|
||||
|
||||
Board caveat (report, never hide): in the three delete frames the page behind the dialog is the Events builder while the dialog says Recipes (the frame reuses one builder). The overlay is compared as drawn (see open question 6). The desktop overflow menu itself is not drawn on any board: it is not visually checked.
|
||||
|
||||
## Manual
|
||||
|
||||
- Real backend, owner and admin: create a type with entries and try to delete it (dialog blocked, no request). Delete the entries, delete the type (204), check the sidebar and the list, reload /schema/<key>.
|
||||
- Race: open Recipes, add an entry elsewhere, confirm the delete and check the real 409 fallback.
|
||||
- Delete a type while another tab shows it, then act in the other tab (404 page).
|
||||
- Keyboard: Tab to "More actions", open with Enter, dialogs trap focus and return it. Screen reader announces the dialog titles and the error alert.
|
||||
- Real offline: open the confirm dialog, go offline, reconnect.
|
||||
@@ -0,0 +1,450 @@
|
||||
Feature: Edit a custom content type in the Schema builder
|
||||
As an owner or admin
|
||||
I want to change the name and fields of a saved custom type
|
||||
So that the type follows the content it holds
|
||||
|
||||
Background:
|
||||
Given the SPA calls the API with relative URLs under /v1 and the "jwt" HttpOnly cookie
|
||||
And API errors are plain text
|
||||
And the builder, FieldList, FieldInspector, ChoiceList, ApiPreview, status chip and leave guard of features/schema_builder_create.feature are reused unchanged unless a scenario below says otherwise
|
||||
And PUT /v1/content-type/{key} takes {name, icon, fields[{key, label, type, required, unique, default, min, max, options}]} and answers 200 with the content type
|
||||
And PUT answers 400 (name or icon), 404 content_type_not_found, 409 schema_incompatible, 422 invalid_field, 403 or 500
|
||||
And the number of entries comes from GET /v1/content-type/{key}/entry?page=1&size=5, field "total"
|
||||
And the route /schema/:key keeps meta auth "verified" and title "Schema"
|
||||
And the content types store is the source of the loaded type; no GET /v1/content-type/{key} is made
|
||||
And only owners and admins can use Schema; the SPA decides from the session role, the API still enforces it
|
||||
And every string goes through t() and has a French entry in i18n/messages.ts
|
||||
And a copy tagged "(proposed copy)" is not in the design and is the coder's single point of change
|
||||
|
||||
Scenario Outline: Resolving the key of /schema/:key
|
||||
Given the custom list holds events, recipes, press-mentions and the built-in list holds articles, authors, sites, media, users
|
||||
When an owner opens /schema/<key>
|
||||
Then <result>
|
||||
|
||||
Examples:
|
||||
| key | result |
|
||||
| events | the builder in edit mode |
|
||||
| articles | the read-only built-in view, unchanged from schema_builtin_view.feature |
|
||||
| unknown | "Content type not found" |
|
||||
| new | the create builder, unchanged |
|
||||
|
||||
Scenario: Reaching the editor from the list
|
||||
Given the Schema list is Populated
|
||||
Then each custom row is a link to /schema/<key> on the table and on the mobile cards
|
||||
And built-in rows still link to /schema/<key>
|
||||
When the user activates the row "Events"
|
||||
Then the router navigates to /schema/events and the builder opens in edit mode
|
||||
|
||||
Scenario: Loading, the session store and the entry count
|
||||
Given an owner opens /schema/events as the first page of the session
|
||||
Then GET /v1/content-type is called once and GET /v1/builtin-type once (the resolver needs both)
|
||||
And GET /v1/content-type/events/entry?page=1&size=5 is called once
|
||||
And the Schema skeleton is shown until the type, the built-in list and the count are known
|
||||
And no GET /v1/content-type/events is made
|
||||
|
||||
Scenario Outline: The count or the list cannot be loaded
|
||||
Given <failure>
|
||||
Then the page shows the error "Couldn't load content type" (proposed copy) with the line "<line>" and a "Try again" action
|
||||
And no builder, no Save is shown
|
||||
When the user activates "Try again"
|
||||
Then the failed request is sent again and the builder opens when it succeeds
|
||||
|
||||
Examples:
|
||||
| failure | line |
|
||||
| the entry count answers 500 or fails (network) | GET /v1/content-type/events/entry failed. Check your connection and try again. (proposed copy) |
|
||||
|
||||
Scenario: The entry count answers 404
|
||||
Given the entry count answers 404 content_type_not_found
|
||||
Then the page shows "Content type not found"
|
||||
|
||||
Scenario Outline: Roles and sessions in edit mode
|
||||
Given <who> opens /schema/events
|
||||
Then <result>
|
||||
|
||||
Examples:
|
||||
| who | result |
|
||||
| a verified owner or admin | the builder in edit mode |
|
||||
| a verified user who is neither | "You don't have access to Schema" with "Go to Home", URL unchanged |
|
||||
| an unverified user | the redirect to /register/pending |
|
||||
| a signed-out visitor | the redirect to /login |
|
||||
|
||||
Scenario: Session-owned store
|
||||
Given an owner has loaded the custom and built-in lists
|
||||
When the user signs out
|
||||
Then the content types store is reset
|
||||
And the next signed-in user's first Schema page loads both lists again
|
||||
And an in-progress edit is not carried to another session or to a second visit of /schema/events
|
||||
|
||||
Scenario: Editing an existing type, desktop (design state 2)
|
||||
Given /schema/events is Events with 7 saved fields and 37 entries, on a 1440 px viewport
|
||||
Then the breadcrumb is "Schema" (a link) then "Events"
|
||||
And "Name" holds "Events" and is editable
|
||||
And "Key" holds "events" in mono, read-only, with a lock icon, no pencil, no Auto badge and no "Reset to match the name"
|
||||
And the chip reads "Saved"
|
||||
And the info bar reads "37 entries use this content type. Changes are checked against them when you save." with an info icon, under the type bar and above the list
|
||||
And the list header reads "Fields" and "7 of 50" with the 7 rows in saved order, none carrying a badge "New" or "Changed"
|
||||
And "Add field" is shown under the list
|
||||
And the first row is selected and the inspector title is "Field: Title" with no "New" badge
|
||||
And "Save" and "Discard" are disabled
|
||||
And the API preview bar is collapsed
|
||||
|
||||
Scenario: Editing an existing type, mobile (design state 2)
|
||||
Given the same page on a 390 px viewport
|
||||
Then the topbar shows an arrow-left, the title "Events"
|
||||
And Name and Key are stacked, then the info bar, then the rows, then the "API preview" row
|
||||
And no inspector is shown until a row is activated
|
||||
And the bottom bar holds the chip "Saved", Discard and Save
|
||||
|
||||
Scenario Outline: The info bar follows the count
|
||||
Given the entry count answers <total>
|
||||
Then <bar>
|
||||
|
||||
Examples:
|
||||
| total | bar |
|
||||
| 0 | no info bar is shown |
|
||||
| 1 | "1 entry uses this content type. Changes are checked against it when you save." (proposed copy) |
|
||||
| 37 | "37 entries use this content type. Changes are checked against them when you save." |
|
||||
| 1200 | "1,200 entries use this content type. Changes are checked against them when you save." |
|
||||
|
||||
Scenario: The locked type key (design state 3)
|
||||
Given /schema/events
|
||||
When the user hovers or focuses the locked key
|
||||
Then a tooltip reads "The key is used in URLs and the API, so it can't change after the type is created."
|
||||
And the tooltip closes on blur, mouse out and Esc
|
||||
And the key input cannot be typed in and no key error can appear
|
||||
|
||||
Scenario: Saved fields are locked
|
||||
Given the saved field Starts on (date) is selected
|
||||
Then "Key" holds "starts_on" with a lock icon, no Auto badge, read-only, with the help "Used in the API, so it can't change."
|
||||
And "Type" shows "Can't change after saving" with a lock icon
|
||||
And the six tiles are shown, the date tile selected and the other five at reduced emphasis and not selectable
|
||||
And label, Required, Unique values, Default value, limits and choices stay editable
|
||||
|
||||
Scenario: Fields added since the last save are not locked
|
||||
Given the user activates "Add field" on /schema/events
|
||||
Then the new row is selected with the badge "New", an Auto key, six selectable tiles and no lock
|
||||
And the key and type behave as in the create builder
|
||||
And a label typed for it derives its key without colliding with any saved key
|
||||
|
||||
Scenario Outline: What marks a saved field as changed
|
||||
Given the saved field <field> is selected
|
||||
When the user <edit>
|
||||
Then its row and its inspector title show the badge "Changed"
|
||||
When the user restores the original value
|
||||
Then the badge goes
|
||||
|
||||
Examples:
|
||||
| field | edit |
|
||||
| Capacity | sets Highest value to 2000 |
|
||||
| Title | renames the label to "Name of event" |
|
||||
| Starts on| turns Required off |
|
||||
| Category | adds the choice "Panel" |
|
||||
| Online | turns the default on |
|
||||
|
||||
Scenario: Reordering is not a change of a field (proposed)
|
||||
Given the saved fields in saved order
|
||||
When the user moves Ends on above Starts on
|
||||
Then no row shows "Changed"
|
||||
And the chip reads "Unsaved changes" and Save is enabled
|
||||
|
||||
Scenario: Unsaved changes (design state 4)
|
||||
Given Events with 37 entries
|
||||
When the user sets Capacity's Highest value to 2000, adds Speaker (Text) and Room (Choice, required, default "Main hall", choices "Main hall" and "Studio"), and removes Description
|
||||
Then the chip reads "Unsaved changes" and Save and Discard are enabled
|
||||
And Capacity shows "Changed", Speaker and Room show "New"
|
||||
And an undo row after the list reads "Description will be removed" with the action "Undo", with a minus icon and a dashed border
|
||||
And the header reads "8 of 50"
|
||||
And the info bar stays
|
||||
|
||||
Scenario: Removing a saved field and undoing it
|
||||
Given Events with the saved field Description at position 7
|
||||
When the user activates Remove on Description
|
||||
Then it leaves the list and an undo row "Description will be removed" appears
|
||||
And the next row (or the previous one at the end) is selected
|
||||
When the user activates "Undo"
|
||||
Then Description returns at position 7 with its original values and no badge
|
||||
And the undo row goes, and with no other edit the chip returns to "Saved" and Save is disabled
|
||||
|
||||
Scenario: Several removals
|
||||
Given the user removed Description and Ends on
|
||||
Then two undo rows are shown, one per field, in the order of the removals (proposed)
|
||||
And each Undo restores its own field at its original position
|
||||
|
||||
Scenario: A removed key stays reserved (proposed)
|
||||
Given the user removed the saved field Description
|
||||
When the user adds a field labelled "Description"
|
||||
Then its Auto key is "description_2"
|
||||
And "Undo" on the removed field still restores "description" without a duplicate key
|
||||
|
||||
Scenario: Undo at the limit of 50 fields (proposed)
|
||||
Given 50 fields are in the list and one saved field is in an undo row
|
||||
Then "Undo" is disabled until a field is removed
|
||||
|
||||
Scenario: Removing every field
|
||||
Given the user removed all saved fields
|
||||
Then the list shows "No fields yet" with "A content type needs at least one field." in the error colour
|
||||
And undo rows are shown for the removed fields
|
||||
And the chip counts one problem and Save is disabled
|
||||
|
||||
Scenario: Name edit only
|
||||
Given Events
|
||||
When the user changes the name to "Events and talks"
|
||||
Then the Key stays "events"
|
||||
And the chip reads "Unsaved changes"
|
||||
And the sidebar and the list keep "Events" until the PUT answers
|
||||
|
||||
Scenario Outline: Type-level rules in edit mode
|
||||
Given Events
|
||||
When the user sets Name to <value>
|
||||
Then <message> is shown under Name with an alert icon
|
||||
And Save is disabled and no request is sent
|
||||
|
||||
Examples:
|
||||
| value | message |
|
||||
| (empty or spaces) | Give the content type a name. |
|
||||
|
||||
Scenario: Field errors (design state 5)
|
||||
Given Events
|
||||
When the user empties the label of Ends on, sets Capacity's Lowest value to 6000, and gives Category the choices Talk, Workshop, a blank and Talk
|
||||
Then the chip reads "3 problems to fix" and Save is disabled
|
||||
And the three rows are outlined with an alert icon
|
||||
And the messages "Give the field a label.", "Lowest value can't be above the highest value.", "Choices can't be blank." and "Two choices are the same." are shown under their inputs
|
||||
And errors follow the timing and the counting rules of the create builder
|
||||
|
||||
Scenario: A single field key error on a new field (design state 7)
|
||||
Given Events and a field added since the last save with the key "start-date"
|
||||
Then the Key shows "Start with a letter. Use lowercase letters, digits and underscores." with the alert icon and the chip reads "1 problem to fix"
|
||||
And a saved field never shows a key error
|
||||
|
||||
Scenario: The choice list of a saved Choice field (design state 8)
|
||||
Given the saved field Category with the choices Talk, Workshop, Meetup is selected
|
||||
Then every control of the create builder's choice list works, including add, remove, reorder and the 50 cap
|
||||
And the help keeps "Removing a choice that entries use will be refused when you save."
|
||||
And the default select lists the choices and is cleared when its choice is removed or renamed
|
||||
|
||||
Scenario: Keyboard reorder in edit mode (design state 9)
|
||||
Given Events with 7 saved fields and Ends on at position 3
|
||||
When the user focuses the grip "Move Ends on", presses Space then Up
|
||||
Then the polite live region reads "Moving Ends on. Position 2 of 7. Press Up or Down to move, Space to drop, Esc to cancel."
|
||||
And Esc restores the order and Space drops it
|
||||
|
||||
Scenario: API preview in edit mode (design state 10)
|
||||
Given Events
|
||||
When the user opens "API preview"
|
||||
Then the routes use the locked key "events"
|
||||
And the sample entry follows the current fields, so added fields appear and removed ones disappear as the user edits
|
||||
And the note "Updates as you edit. Fields you add or remove here appear after you save." is shown
|
||||
And Copy JSON, the "Copied" label and the mobile sheet behave as in the create builder
|
||||
|
||||
Scenario: Saving a type that has no entries
|
||||
Given Recipes with 4 saved fields and 0 entries
|
||||
When the user changes the label of Servings and activates Save
|
||||
Then PUT /v1/content-type/recipes is called once with no review dialog
|
||||
And the body has exactly name, icon and fields
|
||||
|
||||
Scenario: The PUT body
|
||||
Given Events with the loaded icon "calendar" (or null)
|
||||
When the user saves
|
||||
Then the body is {name, icon, fields} with name trimmed
|
||||
And "icon" equals the loaded icon, so an edit never changes it (proposed, see open question)
|
||||
And no "key" is sent in the body
|
||||
And the fields are in list order, undo-row fields are not sent, and each field carries exactly key, label, type, required, unique, default, min, max, options
|
||||
And unset default, min and max are null, options are [] for a non-select field, a date bound is "YYYY-MM-DD", the boolean default is true or null
|
||||
And the key and type of every saved field equal the loaded ones
|
||||
|
||||
Scenario: Saving (design state 11, no entries)
|
||||
Given the PUT has not answered
|
||||
Then the chip reads "Saving…" with a loader, Save shows a loader and is disabled, Discard is disabled
|
||||
And Name, the inspector, Add field, grips, Move, Remove and Undo are dimmed and disabled
|
||||
And a second activation of Save sends no second request
|
||||
|
||||
Scenario: Saved (design state 12)
|
||||
Given the PUT answers 200 with Events and 8 fields
|
||||
Then a success toast "Content type saved" with "Events now has 8 fields." is shown
|
||||
And the user stays on /schema/events
|
||||
And every badge "New" and "Changed" and every undo row clear
|
||||
And the added fields become saved fields: their key and type are now locked
|
||||
And the chip reads "Saved at" followed by the time (HH:MM) of the response's updated_at, Save and Discard are disabled
|
||||
And the content types store holds the answered type in place, so the list, the sidebar Content group and the field count show the new name and count with no second GET /v1/content-type
|
||||
And with one field the toast reads "Events now has 1 field." (proposed copy)
|
||||
And no "Leave without saving?" prompt is shown afterwards
|
||||
|
||||
Scenario: Edit after saving
|
||||
Given the form was just saved
|
||||
When the user edits the name
|
||||
Then the chip reads "Unsaved changes" again
|
||||
And Discard returns to the last saved state, not to the state at page load
|
||||
|
||||
Scenario: Discard
|
||||
Given the user edited the name, a field and removed a field
|
||||
When the user activates Discard
|
||||
Then the form returns to the loaded type, with the first row selected, no badge, no undo row, no error and the chip "Saved"
|
||||
And nothing is sent and the URL stays /schema/events
|
||||
|
||||
Scenario Outline: Leaving with unsaved edits
|
||||
Given <state>
|
||||
When the user leaves through the breadcrumb, the mobile arrow, the sidebar or the browser back
|
||||
Then <result>
|
||||
|
||||
Examples:
|
||||
| state | result |
|
||||
| no edit | the router navigates with no prompt |
|
||||
| an edit, even one only in an undo row | the dialog "Leave without saving?" with "Keep editing" and "Discard changes" |
|
||||
| after Save answered 200 | the router navigates with no prompt |
|
||||
| after Discard | the router navigates with no prompt |
|
||||
|
||||
Scenario: Save on a type with entries opens the review (design group 3, state 1)
|
||||
Given Events with 37 entries, the edits of the "Unsaved changes" scenario and no error
|
||||
When the user activates Save
|
||||
Then no PUT is sent yet
|
||||
And the dialog "Review changes to Events" with "Apply them to save the content type." opens (a bottom sheet on mobile)
|
||||
And the summary reads "Add 2 fields, change 1, remove 1" and "Events has 37 entries. Each one is checked against the new fields when you apply."
|
||||
And the changes are listed in this order: additions, changes, removals, each in list order
|
||||
And the footer note reads "Flagged changes can be refused if existing entries don't fit. If that happens, nothing is changed."
|
||||
And "Back to editing" and "Apply changes" are shown
|
||||
|
||||
Scenario Outline: Review rows
|
||||
Given Events with entries and the edit <edit>
|
||||
Then the review shows the row "<title>" with the text "<text>" and <flag>
|
||||
|
||||
Examples:
|
||||
| edit | title | text | flag |
|
||||
| adds Speaker, Text, optional | Add Speaker | Text, optional. | no flag |
|
||||
| adds Room, Choice, required, default "Main hall" | Add Room | Choice, required, default "Main hall". Existing entries get the default, so they still fit. | no flag |
|
||||
| adds Seats, Number, required, no default | Add Seats | Number, required. Existing entries have no value for it. (proposed copy) | "Entries may not fit" |
|
||||
| sets Capacity's Highest value from 5000 to 2000 | Change Capacity | Highest value goes from 5000 to 2000. | "Entries may not fit" |
|
||||
| raises Capacity's Lowest value from 1 to 10 (proposed copy) | Change Capacity | Lowest value goes from 1 to 10. | "Entries may not fit" |
|
||||
| sets a first Longest on Title (80) where none was set (proposed copy) | Change Title | Longest is now 80. | "Entries may not fit" |
|
||||
| turns Required on for Ends on (proposed copy) | Change Ends on | Now required. | "Entries may not fit" |
|
||||
| turns Unique values on for Category (proposed copy) | Change Category | Values must now be unique. | "Entries may not fit" |
|
||||
| removes the choice Meetup from Category (proposed copy) | Change Category | Choice removed: "Meetup". | "Entries may not fit" |
|
||||
| loosens Capacity's Highest value from 5000 to 8000 (proposed copy) | Change Capacity | Highest value goes from 5000 to 8000. | no flag |
|
||||
| renames the label of Title to "Name" (proposed copy) | Change Title | Label goes from "Title" to "Name". | no flag |
|
||||
| adds the choice "Panel" to Category (proposed copy) | Change Category | Choice added: "Panel". | no flag |
|
||||
| removes Description | Remove Description | Entries stop returning its values. | "Removes data" |
|
||||
|
||||
Scenario Outline: The summary line
|
||||
Given Events with entries and <changes>
|
||||
Then the summary reads "<summary>"
|
||||
|
||||
Examples:
|
||||
| changes | summary |
|
||||
| 2 added, 1 changed, 1 removed | Add 2 fields, change 1, remove 1 |
|
||||
| 1 added | Add 1 field |
|
||||
| 1 changed, 2 removed | Change 1, remove 2 |
|
||||
| 1 changed | Change 1 |
|
||||
|
||||
Scenario Outline: When the review opens
|
||||
Given Events with 37 entries
|
||||
When the user makes <edit> and activates Save
|
||||
Then <result>
|
||||
|
||||
Examples:
|
||||
| edit | result |
|
||||
| only a name change or only a reorder | the PUT is sent at once, with no review (proposed) |
|
||||
| a field added, changed or removed | the review opens |
|
||||
| a name change and a changed field | the review opens and lists only the field change (proposed) |
|
||||
|
||||
Scenario: Back to editing from the review
|
||||
Given the review is open
|
||||
When the user chooses "Back to editing" (or presses Esc or the close icon)
|
||||
Then the dialog closes, no PUT is sent and every edit is kept
|
||||
|
||||
Scenario: Applying (group 3, state 2)
|
||||
Given the review is open
|
||||
When the user activates "Apply changes"
|
||||
Then PUT /v1/content-type/events is sent once
|
||||
And the confirm button reads "Applying…" with a loader and the dialog's other actions are disabled
|
||||
And Esc, the close icon and a click on the overlay do not dismiss the dialog
|
||||
And a second activation sends nothing
|
||||
|
||||
Scenario: Applied
|
||||
Given the PUT answers 200
|
||||
Then the dialog closes, the toast, the cleared badges, the locks and the chip "Saved at" are as in "Saved (design state 12)"
|
||||
And the info bar and the count are unchanged
|
||||
|
||||
Scenario: Refused (design state 15 and group 3, state 3)
|
||||
Given the user applied the edits "Capacity's Highest value goes from 5000 to 2000" plus "Description removed"
|
||||
When the PUT answers 409 with the body "schema_incompatible"
|
||||
Then the review is replaced by the dialog "Nothing was changed" with "RenewCMS refused the changes because some entries don't fit the new fields. It doesn't say which entries."
|
||||
And an error alert reads "Your content type is as it was" with "No field was added, changed or removed."
|
||||
And the section "The change that can cause this in your edit" lists only the flagged changes, here Change Capacity with "Highest value goes from 5000 to 2000. An entry may have a higher value." and the badge "Possible cause"
|
||||
And Removes-data rows are not listed as a cause
|
||||
And the explanation reads "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."
|
||||
And "Discard changes" and "Back to editing" are shown
|
||||
And no entry, id or value is ever named
|
||||
And every edit is still in the form and the store still holds the type as loaded
|
||||
|
||||
Scenario: Refused with no flagged change (proposed)
|
||||
Given the 409 comes back for edits that have no flagged change
|
||||
Then the dialog shows "Nothing was changed", the "Your content type is as it was" alert and the explanation
|
||||
And the section "The change that can cause this in your edit" is omitted
|
||||
|
||||
Scenario: Back to editing after a refusal (design state 15)
|
||||
Given the refusal dialog is open
|
||||
When the user chooses "Back to editing"
|
||||
Then the dialog closes and the page shows the error alert "Nothing was changed" with "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." and the action "Review changes"
|
||||
And the rows of the flagged changes show the badge "Possible cause" next to "Changed" or "New"
|
||||
And the chip reads "Unsaved changes" and Save stays enabled
|
||||
When the user activates "Review changes"
|
||||
Then the review dialog (group 3, state 1) opens again, with the same rows
|
||||
|
||||
Scenario: Discard changes after a refusal
|
||||
Given the refusal dialog is open
|
||||
When the user chooses "Discard changes"
|
||||
Then the dialog closes and the form returns to the loaded type, with no banner, no badge and the chip "Saved"
|
||||
|
||||
Scenario: The refusal markers clear
|
||||
Given the banner "Nothing was changed" is shown
|
||||
When a PUT succeeds, or the user activates Discard
|
||||
Then the banner and every "Possible cause" badge go
|
||||
And when the user undoes or reverts a flagged change, that row loses its "Possible cause" badge
|
||||
|
||||
Scenario Outline: Other answers of the PUT
|
||||
Given the PUT answers <status> with <body>
|
||||
Then <outcome>
|
||||
|
||||
Examples:
|
||||
| status | body | outcome |
|
||||
| 422 | invalid_field | the review dialog closes and the banner "Check the fields marked in the list." (proposed copy) is shown, edits kept |
|
||||
| 400 | Bad request body | the review closes and "Give the content type a name." is shown under Name, edits kept (proposed copy) |
|
||||
| 404 | content_type_not_found | the page "Content type not found" and the store drops the type (proposed copy) |
|
||||
| 403 | Only ... | the page "You don't have access to Schema" |
|
||||
| 401 | (any) | the existing redirect to /login with the expired reason |
|
||||
|
||||
Scenario Outline: Save failed (design state 13)
|
||||
Given the PUT <failure>
|
||||
Then the review dialog (if open) closes
|
||||
And an error alert titled "Couldn't save the content type" shows "Something went wrong on our side. Your changes are still here. Try again in a moment."
|
||||
And it has a "Try again" action and the chip reads "Save failed"
|
||||
And every edit is kept and Save stays enabled
|
||||
When the user activates "Try again"
|
||||
Then the same body is sent again, through the review again when the type has entries
|
||||
|
||||
Examples:
|
||||
| failure |
|
||||
| answers 500 |
|
||||
| fails (network) |
|
||||
|
||||
Scenario: Offline (design state 16)
|
||||
Given the user edited Events and navigator.onLine becomes false
|
||||
Then the banner "You're offline. Changes will be saved when you reconnect." with a wifi-off icon is shown
|
||||
And the chip reads "Waiting for connection", Save is disabled and every edit is kept
|
||||
When the connection returns
|
||||
Then the banner goes, Save is enabled again and nothing is sent by itself
|
||||
|
||||
Scenario: Offline while the review is open
|
||||
Given the review dialog is open and navigator.onLine becomes false
|
||||
Then "Apply changes" is disabled and the edits are kept
|
||||
|
||||
Scenario: Mobile field sheet in edit mode
|
||||
Given a 390 px viewport
|
||||
When the user activates the row Capacity
|
||||
Then the sheet "Field: Capacity" opens with the inspector, the locked key, Move up, Move down, Remove and "Done"
|
||||
And Remove inside the sheet closes the sheet and shows the undo row
|
||||
|
||||
Scenario: Accessibility of the edit mode
|
||||
Then the lock icons have a text alternative or are tied to the field's help text
|
||||
And dialogs trap focus, return it to the opener on close, and the Applying dialog keeps focus on its title
|
||||
And the undo row's "Undo" is a button reachable by keyboard
|
||||
And controls are 44 px high on mobile and focus is a 2 px ring in the primary colour
|
||||
@@ -0,0 +1,103 @@
|
||||
# QA: Schema builder, edit (SPA slice 4; delete is slice 5)
|
||||
|
||||
Runner: Vitest + Vue Test Utils (`task test:web`). No Go test: PUT /v1/content-type/{key} and the entry list are already covered by features/custom_content_types.qa.md and nothing changes in the backend.
|
||||
Same pattern as features/schema_builder_create.qa.md: mock `/v1` through the api composable (extend `views/__tests__/schemaTestKit.ts` with PUT and the entry count handlers, and a full "Events" type with the board's 7 saved fields), mount with the real router and a resolved session whose role varies, `components/__tests__/viewport.ts` for 1440 and 390, fake timers where a delay exists. Never freeze the system date. "Saved at HH:MM" is asserted with /^Saved at \d{2}:\d{2}$/ only.
|
||||
|
||||
## Automated
|
||||
|
||||
Fixtures: Events (id 1, 7 saved fields as drawn on the board: 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) with icon "calendar"; Recipes (4 saved fields, 0 entries); the entry-count body {items:[],total:37,page:1,size:1}; plain-text bodies schema_incompatible, content_type_has_entries, content_type_not_found, invalid_field.
|
||||
|
||||
Pure logic (lib/__tests__, it.each over the feature's Examples):
|
||||
1. Form from a ContentType: API field to BuilderField (number default to string, boolean default to defaultOn, options, ISO dates), saved flag, locked keyMode, and the round trip: loaded form to payload equals the loaded fields (no spurious diff).
|
||||
2. Change detection per saved field: Changed on and off by restoring the value; reorder-only is not a field change; New for added fields.
|
||||
3. Diff for the review: adds, changes, removes in that order, the summary line (singular, zero parts omitted), the row texts of the "Review rows" table, the flags ("Entries may not fit", "Removes data", none), and the flagged-only list used by the refusal. Name-only or reorder-only means no review.
|
||||
4. Payload for PUT: {name, icon, fields}, no key, icon equal to the loaded one (null stays null), undo-row fields excluded, saved key and type unchanged.
|
||||
5. Field key derivation against saved keys and keys in undo rows (`description_2`).
|
||||
6. Undo bookkeeping: positions, several removals, limit of 50.
|
||||
7. Info-bar copy for 0, 1, 37 and 1200 entries.
|
||||
|
||||
Store (stores/__tests__/contentTypes.spec.ts):
|
||||
8. replace(type) swaps by key and keeps order by name when the name changed, does nothing when "idle", never touches built-in items, no request. reset() clears both slices (signed-out case).
|
||||
|
||||
Composable and API (composables/__tests__/useContentTypes.spec.ts):
|
||||
9. updateContentType PUTs JSON to /v1/content-type/{key} and returns the type. countEntries reads `total` from the size=5 request. ApiError carries status and plain-text body for 400, 404, 409, 422, 403, 500. NetworkError passes through.
|
||||
|
||||
Resolver and routing:
|
||||
10. Key resolver (built-in, custom, none, loading) for events, articles, unknown, new. /schema/new is still the create builder, GET /v1/builtin-type result is awaited for /schema/:key. Custom rows of SchemaTable and the mobile cards are links to /schema/<key>.
|
||||
11. Roles: owner, admin, neither (403 page), unverified and signed-out redirects (extend routerGuard.spec) on /schema/events.
|
||||
12. Session reset: sign-out resets the store and discards any edit state; a second visit starts from the store, not from an old draft.
|
||||
|
||||
Builder view in edit mode (new views/__tests__/SchemaBuilderEdit*.spec.ts), one test per scenario:
|
||||
13. Loading: calls list (assert once each), skeleton until type, list and count are known, no GET /v1/content-type/events.
|
||||
14. Count or list failure: error copy, Try again re-sends, builder shown after success. Count 404 gives "Content type not found".
|
||||
15. State 2 desktop and mobile: breadcrumb, Name editable, locked Key without pencil/Auto/Reset, chip "Saved", info bar, "7 of 50", no badges, first row selected, Save and Discard disabled, collapsed API bar. Mobile topbar, stack order, bottom bar.
|
||||
16. Info bar for 0, 1, 37, 1200.
|
||||
17. Locked key tooltip on hover and on focus, closes on blur and Esc, input not editable.
|
||||
18. Saved fields locked: key lock and help, "Can't change after saving", tiles not selectable, other controls editable. New fields unlocked.
|
||||
19. Changed badge table (5 rows) and revert; reorder-only is no Changed badge but dirty.
|
||||
20. State 4 end to end: badges, undo row text and action, header count, chip.
|
||||
21. Remove and Undo: position restored, no residue, chip back to "Saved". Several removals, reserved key, Undo disabled at 50, empty list error.
|
||||
22. Name-only edit keeps the key; empty name error and disabled Save.
|
||||
23. Field errors (state 5) and single field key error on a new field; a saved field never shows a key error.
|
||||
24. Choice list on a saved Choice field (state 8) and keyboard reorder (state 9) with the live-region texts.
|
||||
25. API preview in edit mode (state 10): locked key in the routes, live sample, note text.
|
||||
26. PUT without entries: one request, no dialog, exact body (icon preserved, no key), Saving state (state 11) with dimmed/disabled controls and no second request on double activation.
|
||||
27. Saved (state 12): toast copy incl. singular, stays on the page, badges and undo rows cleared, newly saved fields now locked, chip /^Saved at \d{2}:\d{2}$/, store.replace, list/sidebar/count updated with no extra GET, no leave prompt, edit after save and Discard back to last saved.
|
||||
28. Discard: back to the loaded form, nothing sent.
|
||||
29. Leave guard (5 rows) with Keep editing, dismiss and Discard changes.
|
||||
30. Review (group 3, state 1): opens only for adds/changes/removes with total > 0; no PUT yet; summary, rows (the table), order, footer note, Back to editing, Esc, mobile sheet.
|
||||
31. Applying (state 2): one PUT, loader, non-dismissable (Esc, overlay, close icon), second activation ignored.
|
||||
32. Applied: dialog closes, same results as item 27.
|
||||
33. Refused: 409 schema_incompatible: refusal dialog copy, only flagged changes listed with "Possible cause", no entry named, store untouched, edits kept. Without flagged change: section omitted. Back to editing: banner "Nothing was changed", "Review changes" reopens the review, row markers. Discard changes resets. Markers clear on success, Discard or revert.
|
||||
34. Other PUT answers: 422 banner, 400 name message, 404 not-found page and store drop, 403 page, 401 redirect.
|
||||
35. Save failed (state 13): 500 and network, review closes, banner and chip, edits kept, Try again resends the same body through the review again.
|
||||
36. Offline (state 16) and offline with the review open.
|
||||
37. Mobile field sheet in edit mode.
|
||||
40. Accessibility: focus return from dialogs, Applying focus on its title, Undo reachable by keyboard.
|
||||
|
||||
Existing tests to update:
|
||||
41. features/schema_builtin_view.qa.md and SchemaTypeView.spec: "Content type not found" for a key that is neither built-in nor custom; events is now the editor. features/schema_list_and_content_nav.qa.md and SchemaView.spec: custom rows are links.
|
||||
42. features/schema_builder_create.qa.md item 29/31: nothing changes for create; assert that the create builder still never sends "icon" (regression guard next to the edit icon test).
|
||||
43. French: every new string has a French entry (the i18n completeness spec must pass).
|
||||
|
||||
## Visual (task visual:check -- schema)
|
||||
|
||||
Run `task visual:check -- schema`. Every capture within 10 %, desktop and mobile, light and dark. Mock GET /v1/auth/me (owner "Marta Alves"), GET /v1/builtin-type, and GET /v1/content-type with the 3 custom types. Replace the placeholder Events fields of `schemaCustomTypes` in `web/visual/states.ts` with the board's full 7 fields (EV), keep 7 as the list's field count, and add Recipes with the board's 4 fields (RC). Mock GET /v1/content-type/events/entry as total 37 and /recipes/entry as total 0. Register the group "3 Review and delete" in `extraSources` of `web/visual/check.ts`.
|
||||
|
||||
Setups to replace `skip: 'pending'` in `web/visual/states.ts` (screen `schema`, steps are Playwright actions on the SPA):
|
||||
|
||||
| Board state | Setup (path /schema/events unless noted) | Board sample data |
|
||||
|---|---|---|
|
||||
| Editing an existing type | no steps | Events, 7 saved fields, Title selected, info bar "37 entries use this content type…", chip "Saved", locked key |
|
||||
| Locked key: tooltip | select the row "Starts on", hover (focus on mobile) the locked key | tooltip text, Starts on selected |
|
||||
| Unsaved changes | steps: Capacity Highest value 2000, Add field "Speaker", Add field "Room" with Choice, Required, choices Main hall and Studio, default Main hall, remove Description, select Capacity | rows New and Changed, undo row "Description will be removed", chip "Unsaved changes" |
|
||||
| Field errors | steps: empty the label of Ends on, Capacity Lowest value 6000, Category choices Talk, Workshop, blank, Talk, select Capacity | chip "3 problems to fix" and the four messages |
|
||||
| Choice list editor | steps: Category choices Talk, Workshop, Meetup, blank, Talk, select Category | "5 of 50", chip "1 problem to fix" |
|
||||
| Keyboard reorder | steps: focus the grip "Move Ends on", press Space, press Up | live region "Moving Ends on. Position 2 of 7. …", Ends on picked up |
|
||||
| API preview open | steps: open "API preview" (sheet on mobile) | key events, board's sample JSON |
|
||||
| Saved | `skip: 'clock-sensitive'` | the chip says "Saved at 11:02" |
|
||||
| Save failed | PUT mocked 500; same edits as Unsaved changes; steps: Save, Apply changes | banner "Couldn't save the content type", chip "Save failed" |
|
||||
| Schema incompatible | PUT mocked 409 schema_incompatible; same edits; steps: Save, Apply changes, Back to editing | banner "Nothing was changed" with "Review changes", "Possible cause" on Capacity |
|
||||
| Offline | same edits; steps: go offline | offline banner, chip "Waiting for connection" |
|
||||
| Saving | see open question 6 | |
|
||||
| Review before saving | same edits; steps: Save | dialog copy and the 4 rows of group 3 state 1 |
|
||||
| Applying | PUT mocked to hang; steps: Save, Apply changes | "Applying…" |
|
||||
| Refused (schema_incompatible) | PUT mocked 409; steps: Save, Apply changes | refusal dialog with Change Capacity |
|
||||
|
||||
Not checked: "Review with counts and diff" (scope Later, not built; leave it out of `extraSources`). "Field key error" has no board frame: keep it as a documented `skip: 'pending'` with that reason and cover it in Vitest only. Do not hide it.
|
||||
Known visual differences to report, never hide: the Key help copy (Q1) on /schema/new.
|
||||
|
||||
## Manual
|
||||
|
||||
- Real backend, as owner and admin:
|
||||
- Create Events with all six field types and some entries.
|
||||
- Open it from the list. Edit the name and a label. Confirm the review does not open for a name-only edit and does for a field edit.
|
||||
- Lower Capacity's Highest value below an existing entry's value. Confirm the real 409 `schema_incompatible`, the refusal dialog and that nothing changed (reload).
|
||||
- Add a required field with no default (409). Add one with a default (200 and existing entries get it).
|
||||
- Turn Unique on over duplicate values (409). Remove a Choice option that entries use (409). Remove a field and check entries no longer return it.
|
||||
- Create a type through curl with an `icon`, edit it in the SPA, and check the icon is still returned by GET.
|
||||
- Check that `GET /v1/content-type/{key}/entry?page=1&size=5` is accepted as the count request.
|
||||
- Keyboard: Tab order is Name, locked Key (tooltip on focus), Save, Discard, the field list (one stop, arrows move between rows), the inspector, Undo, API preview. Dialogs trap focus and return it to the trigger. Screen reader: the lock states are announced, the live region reads each reorder step, errors are read with their input.
|
||||
- Hover and motion on the lock tooltip, the undo row and the dialogs. Sheet open and close focus return on a real phone.
|
||||
- Real offline: edit, go offline with the review open, reconnect, press Apply.
|
||||
- Reload or close the tab with unsaved edits (not handled by the leave guard): note the browser behaviour.
|
||||
@@ -0,0 +1,170 @@
|
||||
Feature: Read-only view of a built-in content type
|
||||
As an owner or admin
|
||||
I want to open a built-in type from the Schema list and read its fields
|
||||
So that I can see the rules RenewCMS applies without being able to change them
|
||||
|
||||
Background:
|
||||
Given the SPA calls the API with relative URLs under /v1 and the "jwt" HttpOnly cookie
|
||||
And GET /v1/builtin-type returns [{key, name, fields}] for owners and admins only
|
||||
And each field is {key, label, type, required, unique, default, min, max, options}
|
||||
And API errors are plain text
|
||||
And the route /schema/:key has meta auth "verified" and title "Schema"
|
||||
And the contentTypes store already exposes builtinItems, builtinStatus and load({builtin: true})
|
||||
And the view takes its data from builtinItems, matched on the route key, and never calls GET /v1/builtin-type/{key}
|
||||
And only owners and admins can use Schema; the SPA decides from the session role, the API still enforces it
|
||||
And a session whose role is neither owner nor admin is a test double for the forbidden states
|
||||
And the built-in types are articles ("Articles"), authors, sites, media and users with 5, 5, 8, 6 and 6 fields in the sample data
|
||||
|
||||
Scenario: A built-in row of the Schema list is a link
|
||||
Given the Schema list is Populated
|
||||
When the user looks at the five built-in rows
|
||||
Then each row is a single link to /schema/<its key> whose accessible name is the type name
|
||||
And the row keeps its lock icon, name, "Built-in" badge, key, field count and a chevron-right at the end
|
||||
And on desktop its "Last updated" cell reads "Managed by RenewCMS"
|
||||
And below 640 px the card of a built-in type shows "<key> · <n> fields" with no "Updated" text and a chevron-right
|
||||
And custom rows are not links and show no chevron
|
||||
|
||||
Scenario: Opening a built-in type from the list
|
||||
Given the Schema list is Populated
|
||||
When the user activates the "Articles" row
|
||||
Then the router navigates to /schema/articles
|
||||
And GET /v1/builtin-type is not called a second time
|
||||
|
||||
Scenario: Read-only view of a built-in type (design state 6, desktop)
|
||||
Given an owner or admin is signed in
|
||||
And GET /v1/builtin-type returns the type "articles" named "Articles" with the fields
|
||||
| label | key | type | required | unique | min | max | default |
|
||||
| Title | title | text | true | false | | 200 | |
|
||||
| Slug | slug | text | true | true | | | |
|
||||
| Body | body | richtext | false | false | | 10000 | |
|
||||
| Online | online | boolean | false | false | | | false |
|
||||
| Published on | published_on | date | false | false | | | |
|
||||
When they open /schema/articles
|
||||
Then the breadcrumb is "Schema" (a link to /schema) then "Articles"
|
||||
And the h1 "Articles" is shown with a lock icon and a "Built-in" badge
|
||||
And an info alert titled "Managed by RenewCMS" says "Articles is a built-in type. You can read its fields here, but you can't edit it, delete it or add fields."
|
||||
And a table has the columns "Label", "Key", "Type", "Rules"
|
||||
And the rows are, in this order
|
||||
| Label | Key | Type | Rules |
|
||||
| Title | title | Text | Required · up to 200 characters |
|
||||
| Slug | slug | Text | Required · unique |
|
||||
| Body | body | Rich text | Up to 10,000 characters |
|
||||
| Online | online | Yes or no | Off by default |
|
||||
| Published on | published_on | Date | – |
|
||||
And each row starts with the icon of its type
|
||||
And the note "Entries of built-in types are managed from their own screens, like Articles and Authors." is shown under the table
|
||||
And there is no "New content type", edit, delete, add field, save or discard action
|
||||
And the keys are shown in the mono style
|
||||
And GET /v1/content-type and GET /v1/builtin-type are each called once
|
||||
|
||||
Scenario: Read-only view of a built-in type on mobile
|
||||
Given the same data and a 390 px wide viewport
|
||||
When they open /schema/articles
|
||||
Then the topbar shows an arrow-left and the title "Articles"
|
||||
And the fields are cards in order, each with the icon box of its type, the label, and the key in mono followed by " · " and the rules
|
||||
And the Type column is not shown
|
||||
And the "Built-in" badge, the alert and the note are shown
|
||||
|
||||
Scenario Outline: Field types show their label and icon
|
||||
Given a built-in field of type "<type>"
|
||||
Then the Type cell reads "<label>" with the icon <icon>
|
||||
|
||||
Examples:
|
||||
| type | label | icon |
|
||||
| text | Text | type |
|
||||
| richtext | Rich text | pilcrow |
|
||||
| number | Number | hash |
|
||||
| boolean | Yes or no | toggle-left |
|
||||
| date | Date | calendar |
|
||||
| select | Choice | list |
|
||||
|
||||
Scenario Outline: The Rules cell is derived from the field
|
||||
Given a field of type "<type>" with <settings>
|
||||
Then the Rules cell reads "<rules>"
|
||||
|
||||
Examples:
|
||||
| type | settings | rules |
|
||||
| text | required, max 200 | Required · up to 200 characters |
|
||||
| text | required, unique | Required · unique |
|
||||
| richtext | max 10000 | Up to 10,000 characters |
|
||||
| boolean | default false | Off by default |
|
||||
| boolean | default true | On by default |
|
||||
| date | nothing | – |
|
||||
| text | min 3, max 80 (proposed copy) | 3 to 80 characters |
|
||||
| text | min 3 (proposed copy) | At least 3 characters |
|
||||
| number | min 1, max 5000 (proposed copy) | Between 1 and 5000 |
|
||||
| number | min 1 (proposed copy) | At least 1 |
|
||||
| number | max 5000 (proposed copy) | At most 5000 |
|
||||
| select | 3 options (proposed copy) | 3 choices |
|
||||
| text | default "Draft" (proposed copy) | Default: Draft |
|
||||
|
||||
Scenario: Back to the list
|
||||
Given the read-only view is shown
|
||||
When the user activates the "Schema" breadcrumb, or the arrow-left on mobile
|
||||
Then the router navigates to /schema
|
||||
|
||||
Scenario: Deep link and reload load what the view needs
|
||||
Given the user opens /schema/articles as the first page of the session
|
||||
Then the session is resolved, then GET /v1/builtin-type is called once
|
||||
And the view shows the read-only view when it answers 200
|
||||
|
||||
Scenario: Loading
|
||||
Given GET /v1/builtin-type has not answered
|
||||
When an owner opens /schema/articles
|
||||
Then nothing is shown in the content area during the first 150 ms
|
||||
And after 150 ms skeleton rows are shown
|
||||
And the not-found page and the 403 page are not shown
|
||||
|
||||
Scenario Outline: Unknown key
|
||||
Given GET /v1/builtin-type returns the five built-in types
|
||||
When an owner opens <path>
|
||||
Then the page "Content type not found" is shown with "It may have been deleted, or the address may be mistyped."
|
||||
And the URL stays <path> and nothing redirects
|
||||
And no field table is shown
|
||||
|
||||
Examples:
|
||||
| path | why |
|
||||
| /schema/unknown | a mistyped key |
|
||||
| /schema/events | a custom type; its builder is a later slice |
|
||||
|
||||
Scenario Outline: Error
|
||||
Given GET /v1/builtin-type <failure>
|
||||
When an owner opens /schema/articles
|
||||
Then an alert shows "Couldn't load content types"
|
||||
And it shows "GET /v1/builtin-type failed. Check your connection and try again."
|
||||
And a "Try again" action is shown
|
||||
And no table is shown
|
||||
|
||||
Examples:
|
||||
| failure |
|
||||
| answers 500 |
|
||||
| fails (network) |
|
||||
|
||||
Scenario: Retry recovers
|
||||
Given the view is in the Error state
|
||||
When the user activates "Try again"
|
||||
Then GET /v1/builtin-type is called again
|
||||
And when it answers 200 the read-only view replaces the alert
|
||||
|
||||
Scenario: Forbidden for a user who is not owner or admin
|
||||
Given a verified user whose role is neither owner nor admin is signed in
|
||||
When they open /schema/articles
|
||||
Then the URL stays /schema/articles and nothing redirects
|
||||
And the page shows "You don't have access to Schema"
|
||||
And it shows "Only owners and admins can change content types. You can still add and edit entries from the Content menu."
|
||||
And a "Go to Home" action navigates to /home
|
||||
And GET /v1/builtin-type is never called
|
||||
|
||||
Scenario: The API answers 403
|
||||
Given the session says owner or admin but GET /v1/builtin-type answers 403
|
||||
When they open /schema/articles
|
||||
Then the same "You don't have access to Schema" page is shown
|
||||
|
||||
Scenario: An unverified or signed-out user keeps the existing redirects
|
||||
Given the user is not verified or not signed in
|
||||
When they open /schema/articles
|
||||
Then they are redirected to /register/pending or /login as for any other "verified" route
|
||||
|
||||
Scenario: The list and the view share one load
|
||||
Given the user opens /schema, then /schema/articles, then goes back
|
||||
Then GET /v1/builtin-type and GET /v1/content-type are each called once in the session
|
||||
@@ -0,0 +1,42 @@
|
||||
# QA: Read-only view of a built-in type (SPA slice 2)
|
||||
|
||||
Runner: Vitest + Vue Test Utils (`task test:web`). No Go test: there is no backend change.
|
||||
Same pattern as features/schema_list_and_content_nav.qa.md: mock `/v1` through the existing api composable, mount with a test router (routes /schema, /schema/:key) and a resolved session whose role varies. The forbidden cases use a session with an unknown role.
|
||||
|
||||
## Automated
|
||||
|
||||
Fixtures: the five built-in types with the board's sample data; "articles" has the 5 fields of the board (Title, Slug, Body, Online, Published on), the others only need a `fields` array of the right length (5, 5, 8, 6, 6). Three custom types as in slice 1.
|
||||
|
||||
SchemaTable / list (extend SchemaView.spec and the SchemaTable spec):
|
||||
1. Built-in rows are single links (`a` with href /schema/<key>), accessible name = type name, chevron present, "Managed by RenewCMS" in the desktop Last updated cell, no "Updated" text on the mobile card (use `components/__tests__/viewport.ts`).
|
||||
2. Custom rows are not links and have no chevron. Replaces the slice-1 test "rows are not links".
|
||||
3. Activating the "Articles" row navigates to /schema/articles; no second GET /v1/builtin-type.
|
||||
|
||||
Read-only view (new SchemaBuiltinView.spec), one test per state:
|
||||
4. Read-only: owner and admin. Assert the breadcrumb, h1 with lock and "Built-in", alert title and text, columns, the five rows (label, key, type label, rules) in order, the note, and the absence of any new/edit/delete/add/save/discard button. Both /v1 calls made once.
|
||||
5. Mobile: arrow-left + title, cards with key and rules, no Type column.
|
||||
6. Type labels and icons (it.each over the 6 types).
|
||||
7. Rules derivation (it.each over the Examples table of the feature, incl. 10,000 separator, the en dash for empty, and capitalisation of the first part). Cases tagged "proposed copy" are separate it.each rows so a design change touches them only.
|
||||
8. Back: the breadcrumb and the mobile arrow push /schema.
|
||||
9. Deep link: a store in its initial state loads the builtin list once on mount.
|
||||
10. Loading: unresolved promise, fake timers. Nothing at 149 ms, skeleton at 150 ms, no not-found or 403 page. A fast response never shows the skeleton.
|
||||
11. Unknown key: it.each over /schema/unknown, /schema/events. Assert the "Content type not found" page copy, URL unchanged, no table.
|
||||
12. Error: 500 and network failure. Assert the alert copy ("GET /v1/builtin-type failed. ..."), "Try again", no table. Retry then returns 200 and the view replaces the alert (second call made).
|
||||
13. Forbidden: unknown role gives the 403 page copy, "Go to Home" navigates to /home, URL stays /schema/articles, builtin-type never called. Plus a case where builtin-type answers 403 for an owner.
|
||||
14. Shared load: navigating /schema -> /schema/articles -> back calls each list endpoint once.
|
||||
|
||||
Router and guard:
|
||||
15. `/schema/:key` is registered with auth "verified" and title "Schema". Unverified and signed-out users get the existing redirects (extend routerGuard.spec). /schema (exact) is unchanged.
|
||||
|
||||
## Visual (task visual:check -- schema)
|
||||
|
||||
Run `task visual:check -- schema`; every capture within 10 % at desktop and mobile, light and dark. Nothing is clock-sensitive.
|
||||
- Replace `skip: 'pending'` of state 6 in `web/visual/states.ts` with a real setup: open /schema/articles. Mock GET /v1/session, GET /v1/content-type (the 3 custom types), GET /v1/builtin-type with the five types. "articles" must carry the board's 5 fields: Title (text, required, max 200), Slug (text, required, unique), Body (richtext, max 10000), Online (boolean, default false), Published on (date, none). Field counts 5, 5, 8, 6, 6. Keys in the mock follow the board's sample text ("articles" etc.), since the view resolves the key from data. Use the sidebar mock of states 1-5 and mock every other /v1 call the screen makes.
|
||||
- States 1 to 5 must still pass after the list-row change (chevron on built-in rows, "Managed by RenewCMS" in Last updated). If the board and the slice-1 rendering differ on custom rows' chevron, report it, do not fix it silently.
|
||||
- Loading, Error, Unknown key and Forbidden-on-detail have no board frame: Vitest only, not in the visual check.
|
||||
|
||||
## Manual
|
||||
|
||||
- Keyboard: Tab order list rows (each row one stop), Enter on a focused built-in row opens it; visible focus ring; the breadcrumb and back arrow are reachable.
|
||||
- Hover on a built-in row, and focus/hover motion.
|
||||
- Real backend: log in as owner and as admin, open each of the five built-in rows, compare the rendered Rules with the actual fields returned by GET /v1/builtin-type (the board's rules are illustrative), and confirm a plain user gets the 403 page on /schema/article.
|
||||
@@ -0,0 +1,194 @@
|
||||
Feature: Schema list and content navigation in the back-office
|
||||
As an owner or admin
|
||||
I want to see the custom and built-in content types on a Schema screen
|
||||
And as any verified user I want a Content menu with one link per custom type
|
||||
So that I can reach the content types I manage and write entries for
|
||||
|
||||
Background:
|
||||
Given the SPA calls the API with relative URLs under /v1 and the "jwt" HttpOnly cookie
|
||||
And GET /v1/content-type returns a JSON array of {id, key, name, icon, fields, created_at, updated_at}
|
||||
And GET /v1/builtin-type returns a JSON array of {key, name, fields}, for owners and admins only
|
||||
And API errors are plain text
|
||||
And the session store exposes the role of the signed-in user, and only owner and admin exist today
|
||||
And a session whose role is neither owner nor admin (absent or unknown) is a test double for the forbidden states
|
||||
And the Schema screen is the route /schema with meta auth "verified", title "Schema"
|
||||
And only owners and admins can use Schema; the SPA decides from the session role, the API still enforces it
|
||||
And the typed API client exposes listContentTypes() and listBuiltinTypes()
|
||||
And a content types store loads them once per session and exposes loading, error and items
|
||||
And this slice does not add the Vitest runner, it already exists (task test:web)
|
||||
|
||||
Scenario Outline: The Schema entry is shown to owners and admins only
|
||||
Given a verified user with role "<role>" is signed in
|
||||
When the back-office shell renders
|
||||
Then the sidebar <schema_entry> a "Schema" entry linking to /schema, with the "shapes" icon, placed after "Users"
|
||||
And no existing nav item changed
|
||||
|
||||
Examples:
|
||||
| role | schema_entry |
|
||||
| owner | shows |
|
||||
| admin | shows |
|
||||
| unknown | does not show |
|
||||
|
||||
Scenario: The Content group lists one link per custom type
|
||||
Given a verified user is signed in
|
||||
And GET /v1/content-type returns the types "events" (Events), "recipes" (Recipes) and "press-mentions" (Press mentions)
|
||||
When the back-office shell renders
|
||||
Then the sidebar shows a "Content" group under the main items
|
||||
And the group contains three links, in the API order, to /content/events, /content/recipes and /content/press-mentions
|
||||
And each row shows the type name
|
||||
And the row of the type matching the current route /content/:key is marked as the current page
|
||||
|
||||
Scenario Outline: Each type shows its icon, or the default icon
|
||||
Given a custom type "recipes" with icon <icon>
|
||||
When the sidebar renders
|
||||
Then the row for "recipes" shows <shown>
|
||||
|
||||
Examples:
|
||||
| icon | shown |
|
||||
| "chef-hat" | the icon i-lucide-chef-hat (in bundle) |
|
||||
| null | the default icon "files" |
|
||||
| "not-bundled" | the default icon "files" |
|
||||
|
||||
Scenario: A long type name is truncated in one line and keeps its full name available
|
||||
Given a custom type named "Frequently asked questions and answers"
|
||||
When the sidebar renders on desktop
|
||||
Then the label is cut with an ellipsis on one line and does not widen the sidebar
|
||||
And the full name is available in a tooltip and as the link's accessible name
|
||||
|
||||
Scenario: With more than 5 types the desktop group shows 5 and the selected one
|
||||
Given 14 custom types and the current route is /content/<selected>
|
||||
When the sidebar renders on desktop
|
||||
Then the group shows the first 5 types, plus the selected type if it is not among them
|
||||
And a "Show all 14" action follows
|
||||
When the user activates "Show all 14"
|
||||
Then all 14 types are listed
|
||||
|
||||
Scenario: With 5 types or fewer there is no "Show all"
|
||||
Given 5 custom types
|
||||
When the sidebar renders
|
||||
Then all 5 are listed and no "Show all" action appears
|
||||
|
||||
Scenario: On mobile the group is one collapsed row in the drawer
|
||||
Given 14 custom types and a 390 px wide viewport
|
||||
When the user opens the drawer
|
||||
Then the Content group shows one collapsed row "All content types" with the count 14
|
||||
When the user expands it
|
||||
Then the 14 types are listed with rows 44 px high
|
||||
|
||||
Scenario: No custom type hides the group
|
||||
Given GET /v1/content-type returns []
|
||||
When the shell renders
|
||||
Then there is no Content group and no empty placeholder in the sidebar
|
||||
|
||||
Scenario Outline: A failing content type request does not break the shell
|
||||
Given GET /v1/content-type <failure>
|
||||
When the shell renders
|
||||
Then the Content group is not shown
|
||||
And the rest of the sidebar and the page render normally
|
||||
|
||||
Examples:
|
||||
| failure |
|
||||
| answers 500 |
|
||||
| fails (network) |
|
||||
|
||||
Scenario: The Content group is loaded once for the whole session
|
||||
Given the user navigates between several back-office screens
|
||||
Then GET /v1/content-type is called once and the list is shared by the sidebar and the Schema list
|
||||
|
||||
Scenario: Populated list
|
||||
Given an owner or admin is signed in
|
||||
And GET /v1/content-type returns three types
|
||||
And GET /v1/builtin-type returns articles, authors, sites, media and users
|
||||
When they open /schema
|
||||
Then the page shows the title "Schema" and the text "Content types and the fields they are made of."
|
||||
And a "New content type" action is enabled
|
||||
And a table has the columns "Name", "Key", "Fields", "Last updated"
|
||||
And each custom row shows name, key, the number of fields and the updated date as an absolute date, using the board's sample data
|
||||
And after the custom rows come the five built-in rows, each with a lock icon and a "Built-in" badge
|
||||
And a built-in row shows its field count from the length of fields and "Managed by RenewCMS" as Last updated on desktop (no Updated text on mobile)
|
||||
And the text "Built-in types are managed by RenewCMS. You can read their fields, but not change them." is shown
|
||||
And the summary "3 content types · 5 built-in" is shown
|
||||
And below 640 px the table is a list of cards with the same content
|
||||
|
||||
Scenario: Loading
|
||||
Given GET /v1/content-type has not answered
|
||||
When an owner opens /schema
|
||||
Then no skeleton is shown during the first 150 ms
|
||||
And after 150 ms skeleton rows are shown
|
||||
And "New content type" is disabled
|
||||
And the 403 page and the empty state are not shown
|
||||
|
||||
Scenario: Empty, no custom type yet
|
||||
Given GET /v1/content-type returns []
|
||||
When an owner opens /schema
|
||||
Then the empty state "No content types yet" is shown with the text "Create a content type to manage your own kind of content, like events or recipes. The built-in types stay as they are."
|
||||
And a "New content type" action is shown and enabled
|
||||
And the five built-in types are still listed below
|
||||
|
||||
Scenario Outline: Error
|
||||
Given GET /v1/content-type <failure>
|
||||
When an owner opens /schema
|
||||
Then an alert shows "Couldn't load content types"
|
||||
And it shows "GET /v1/content-type failed. Check your connection and try again."
|
||||
And a "Try again" action is shown
|
||||
And no table is shown
|
||||
|
||||
Examples:
|
||||
| failure |
|
||||
| answers 500 |
|
||||
| fails (network) |
|
||||
|
||||
Scenario: Retry recovers
|
||||
Given the list is in the Error state
|
||||
When the user activates "Try again"
|
||||
Then the skeleton rows show after 150 ms and GET /v1/content-type is called again
|
||||
And when it answers 200 the Populated state replaces the alert
|
||||
|
||||
Scenario: Forbidden for a user who is not owner or admin
|
||||
Given a verified user whose role is neither owner nor admin is signed in
|
||||
When they open /schema directly
|
||||
Then the URL stays /schema and nothing redirects
|
||||
And the page shows "You don't have access to Schema"
|
||||
And it shows "Only owners and admins can change content types. You can still add and edit entries from the Content menu."
|
||||
And a "Go to Home" action navigates to /home
|
||||
And GET /v1/builtin-type is never called
|
||||
|
||||
Scenario: The API answers 403 for the list
|
||||
Given the session says owner or admin but GET /v1/builtin-type answers 403
|
||||
When they open /schema
|
||||
Then the same "You don't have access to Schema" page is shown
|
||||
|
||||
Scenario: Built-in types fail to load while custom types load
|
||||
Given GET /v1/content-type answers 200 and GET /v1/builtin-type answers 500
|
||||
When an owner opens /schema
|
||||
Then the Error state is shown
|
||||
|
||||
Scenario: An unverified or signed-out user keeps the existing redirects
|
||||
Given the user is not verified or not signed in
|
||||
When they open /schema
|
||||
Then they are redirected to /register/pending or /login as for any other "verified" route
|
||||
|
||||
Scenario: New content type
|
||||
Given the list is Populated or Empty
|
||||
When an owner activates "New content type"
|
||||
Then the router navigates to /schema/new (the builder is a later slice)
|
||||
|
||||
Scenario: Custom rows are not links in this slice
|
||||
Given the list is Populated
|
||||
Then custom rows do not navigate (the editor is a later slice)
|
||||
And built-in rows are links, see schema_builtin_view.feature
|
||||
|
||||
Scenario Outline: The typed client maps responses
|
||||
When the client calls <call>
|
||||
And the API answers <answer>
|
||||
Then it <result>
|
||||
|
||||
Examples:
|
||||
| call | answer | result |
|
||||
| listContentTypes | 200 with icon null | returns the types, icon typed string or null |
|
||||
| listContentTypes | 200 [] | returns an empty array |
|
||||
| listContentTypes | 500 plain text | rejects with an error carrying status 500 |
|
||||
| listContentTypes | network failure | rejects with a network error |
|
||||
| listBuiltinTypes | 200 | returns {key, name, fields} items |
|
||||
| listBuiltinTypes | 403 plain text | rejects with an error carrying status 403 |
|
||||
| listBuiltinTypes | 500 plain text | rejects with an error carrying status 500 |
|
||||
@@ -0,0 +1,48 @@
|
||||
# QA: Schema list and content navigation (SPA slice 1)
|
||||
|
||||
Runner: Vitest + Vue Test Utils (already installed, `task test:web`). No Go test: there is no backend change.
|
||||
Mock `/v1` through the existing api composable pattern used by the other view specs. Mount the shell (DashboardShell) with a test router and a resolved session whose role varies. Only owner and admin exist, so the forbidden cases use a session with an unknown role.
|
||||
|
||||
## Automated
|
||||
|
||||
Fixtures: three custom types (events, recipes, press-mentions) with the board's sample data for names, field counts and dates, at least one with icon "chef-hat" and one with icon null; five built-in types (articles, authors, sites, media, users) with fields arrays.
|
||||
|
||||
Schema list, one test per design state (screens/schema.md section 1):
|
||||
1. Populated: both calls 200, role owner and role admin. Assert the title, subtitle, columns, custom rows before built-in rows, lock + "Built-in" badge on 5 rows, the built-in note, the summary "3 content types · 5 built-in", enabled "New content type". Assert the card layout below 640 px.
|
||||
2. Loading: unresolved promise with fake timers. No skeleton at 149 ms, skeleton at 150 ms, "New content type" disabled. A fast response (under 150 ms) never shows skeletons.
|
||||
3. Empty: content-type returns []. Assert the empty state copy, action, and the 5 built-in rows still listed.
|
||||
4. Error: 500 and network failure. Assert the alert copy, the "Try again" action, no table. Then retry returns 200 and the Populated state replaces the alert (the second call is made).
|
||||
5. Forbidden: unknown role. Assert the 403 page copy, "Go to Home" navigates to /home, URL stays /schema, `GET /v1/builtin-type` never called. Add a case where builtin-type answers 403 for an owner.
|
||||
6. builtin-type 500 with content-type 200: Error state.
|
||||
7. "New content type" pushes /schema/new.
|
||||
|
||||
Sidebar:
|
||||
8. Schema entry visibility for owner, admin and unknown role; position after Users.
|
||||
9. Content group: three links with the right hrefs, current row marked, hidden on empty, hidden on 500 and on network failure, no second request across route changes.
|
||||
10. Icons: "chef-hat" in the bundle renders it, null and an unbundled name render the default "files" icon.
|
||||
11. Truncation: label has the truncate classes, full name in tooltip and accessible name.
|
||||
12. More than 5 types: 14 types and a selected type beyond the fifth. Assert 5 + the selected row + "Show all 14"; after activating it all 14 show. With 5 types, no "Show all".
|
||||
13. Mobile (viewport helper in `components/__tests__/viewport.ts`): drawer shows one collapsed row "All content types" with count 14, expands to 14 rows.
|
||||
|
||||
Router and guard:
|
||||
14. `/schema` is registered with auth "verified" and title "Schema"; unverified and signed-out users get the existing redirects (extend routerGuard.spec).
|
||||
|
||||
Client and store:
|
||||
15. Typed client calls (the Examples table in the feature) incl. icon string|null typing, 403, 500, network failure.
|
||||
16. Store loads once, shares state between the sidebar and the Schema list, retry reloads.
|
||||
|
||||
## Visual (task visual:check -- schema)
|
||||
|
||||
Run `task visual:check -- schema`, every capture within 10 % at desktop and mobile, light and dark. States to set up in `web/visual/states.ts`, reusing the board's sample data (names, keys, field counts, dates, counts "3 content types · 5 built-in" taken from SchemaFrame.dc.html):
|
||||
- 1 Populated, 2 Loading, 3 Empty, 4 Error, 5 Forbidden (403).
|
||||
- State 6 (built-in read-only view) is covered by schema_builtin_view.qa.md.
|
||||
- None of these is clock-sensitive; if the Last updated cell turns out to be relative on the board, mark it `skip: 'clock-sensitive'`.
|
||||
- Mock every `/v1` call the screen makes, including the sidebar's GET /v1/content-type.
|
||||
- The sidebar group and drawer frames belong to the later `content` group.
|
||||
|
||||
## Manual
|
||||
|
||||
- Keyboard: tab order through sidebar, "Show all", table and "New content type"; visible focus rings.
|
||||
- Tooltip on a truncated name on hover and on focus.
|
||||
- Hover and motion of the drawer expand/collapse row.
|
||||
- With a real backend: log in as owner and admin and confirm the sidebar and /schema; create a type with icon "chef-hat" via the API and see it appear.
|
||||
@@ -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
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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) == ""
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -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())
|
||||
}
|
||||
}
|
||||
@@ -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}`)
|
||||
})
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
|
||||
@@ -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
|
||||
|
||||
+24
-2
@@ -15,6 +15,7 @@
|
||||
"@tiptap/pm": "3.31.3",
|
||||
"@tiptap/vue-3": "3.31.3",
|
||||
"@vueuse/core": "14.4.0",
|
||||
"markdown-it": "^15.0.3",
|
||||
"pinia": "^3.0.4",
|
||||
"tailwindcss": "^4.1.18",
|
||||
"vue": "^3.5.25",
|
||||
@@ -24,6 +25,7 @@
|
||||
"@iconify-json/lucide": "^1.2.136",
|
||||
"@iconify/utils": "^3.1.7",
|
||||
"@tsconfig/node24": "^24.0.3",
|
||||
"@types/markdown-it": "^14.2.0",
|
||||
"@types/node": "^24.10.1",
|
||||
"@vitejs/plugin-vue": "^6.0.2",
|
||||
"@vue/eslint-config-prettier": "^10.2.0",
|
||||
@@ -438,6 +440,12 @@
|
||||
|
||||
"@types/json-schema": ["@types/json-schema@7.0.15", "", {}, "sha512-5+fP8P8MFNC+AyZCDxrB2pkZFPGzqQWUzpSeuuVLvm8VMcorNYavBqoFcxK8bQz4Qsbn4oUEEem4wDLfcysGHA=="],
|
||||
|
||||
"@types/linkify-it": ["@types/linkify-it@5.0.0", "", {}, "sha512-sVDA58zAw4eWAffKOaQH5/5j3XeayukzDk+ewSsnv3p4yJEZHCCzMDiZM8e0OUrRvmpGZ85jf4yDHkHsgBNr9Q=="],
|
||||
|
||||
"@types/markdown-it": ["@types/markdown-it@14.2.0", "", { "dependencies": { "@types/linkify-it": "^5", "@types/mdurl": "^2" } }, "sha512-NoQ2yGlLWj4wpxMs+TYmRKk3thDrQ97agr7sFqfLsAlvoS8SNQuTrlObhFqG9iugdTtgOE9jpJ6FNM4ZGsa5xQ=="],
|
||||
|
||||
"@types/mdurl": ["@types/mdurl@2.0.0", "", {}, "sha512-RGdgjQUZba5p6QEFAVx2OGb8rQDL/cPRG7GiedRzMcJ1tYnUANBncjbSB1NRGwbvjcPeikRABz2nshyPk1bhWg=="],
|
||||
|
||||
"@types/node": ["@types/node@24.10.4", "", { "dependencies": { "undici-types": "~7.16.0" } }, "sha512-vnDVpYPMzs4wunl27jHrfmwojOGKya0xyM3sH+UE5iv5uPS6vX7UIoh6m+vQc5LGBq52HBKPIn/zcSZVzeDEZg=="],
|
||||
|
||||
"@types/web-bluetooth": ["@types/web-bluetooth@0.0.21", "", {}, "sha512-oIQLCGWtcFZy2JW77j9k8nHzAOpqMHLQejDA48XXMWH6tjCQHz5RCFz1bzsmROyL6PUm+LLnUiI4BCn221inxA=="],
|
||||
@@ -546,7 +554,7 @@
|
||||
|
||||
"anymatch": ["anymatch@3.1.3", "", { "dependencies": { "normalize-path": "^3.0.0", "picomatch": "^2.0.4" } }, "sha512-KMReFUr0B4t+D+OBkjR3KYqvocp2XaSzO55UcB6mgQMd3KbcE+mWTyvVV7D/zsdEbNnV6acZUutkiHQXvTr1Rw=="],
|
||||
|
||||
"argparse": ["argparse@2.0.1", "", {}, "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q=="],
|
||||
"argparse": ["argparse@3.0.3", "", {}, "sha512-Sn98ftV3KfsO8xfLPHG6oT8y+b0yvbrLgZjgPDXsharNY15tTAjqIsIju4S32nl6/iEUNNE4v+yL2Zhm8ooP3w=="],
|
||||
|
||||
"aria-hidden": ["aria-hidden@1.2.6", "", { "dependencies": { "tslib": "^2.0.0" } }, "sha512-ik3ZgC9dY/lYVVM++OISsaYDeg1tb0VtP5uL3ouh1koGOaUMDPpbFIei4JkFimWUFPn90sbMNMXQAIVOlnYKJA=="],
|
||||
|
||||
@@ -672,7 +680,7 @@
|
||||
|
||||
"enhanced-resolve": ["enhanced-resolve@5.18.4", "", { "dependencies": { "graceful-fs": "^4.2.4", "tapable": "^2.2.0" } }, "sha512-LgQMM4WXU3QI+SYgEc2liRgznaD5ojbmY3sb8LxyguVkIg5FxdpTkvk72te2R38/TGKxH634oLxXRGY6d7AP+Q=="],
|
||||
|
||||
"entities": ["entities@6.0.1", "", {}, "sha512-aN97NXWF6AWBTahfVOIrB/NShkzi5H7F9r1s9mD3cDj4Ko5f2qhhVoYMibXF7GlLveb/D2ioWay8lxI97Ven3g=="],
|
||||
"entities": ["entities@8.1.0", "", {}, "sha512-kxL7msIffSuh9aaFAMD7rxAIuTRMAHMeBtgHW2yUdWw732ZNh4MehkF2gdjvtdmikkaIP9bFDDJOPlsvm7avrA=="],
|
||||
|
||||
"error-stack-parser-es": ["error-stack-parser-es@1.0.5", "", {}, "sha512-5qucVt2XcuGMcEGgWI7i+yZpmpByQ8J1lHhcL7PwqCwu9FPP3VUXzT4ltHe5i2z9dePwEHcDVOAfSnHsOlCXRA=="],
|
||||
|
||||
@@ -902,6 +910,8 @@
|
||||
|
||||
"lightningcss-win32-x64-msvc": ["lightningcss-win32-x64-msvc@1.30.2", "", { "os": "win32", "cpu": "x64" }, "sha512-5g1yc73p+iAkid5phb4oVFMB45417DkRevRbt/El/gKXJk4jid+vPFF/AXbxn05Aky8PapwzZrdJShv5C0avjw=="],
|
||||
|
||||
"linkify-it": ["linkify-it@6.1.0", "", { "dependencies": { "uc.micro": "^3.0.0" } }, "sha512-wJ/TwpSDTLepCrQoYWYIExIKg5Zchex2Nn5yk2mFnB+6PtdkHtyLx742md9csRjjOnGkKIS/RrbY7l8D6gT9Vw=="],
|
||||
|
||||
"linkifyjs": ["linkifyjs@4.3.3", "", {}, "sha512-P8aEP5U/D1/IlTY2OeYsErdwh9bGuLE30NcXtKEjgdHcahveQoQwM2yZNsioQHsWFz0P7KKudisbrzCgR0sDHg=="],
|
||||
|
||||
"local-pkg": ["local-pkg@1.2.1", "", { "dependencies": { "mlly": "^1.7.4", "pkg-types": "^2.3.0", "quansync": "^0.2.11" } }, "sha512-++gUqRDEvcnN6Zhqrr+y/CkVEHhlrR96vZn3nZZPYzMcBUyBtTKzB9NadClFIsIVSsu+3i9tfk/erqy9kAmt7Q=="],
|
||||
@@ -916,12 +926,16 @@
|
||||
|
||||
"magic-string": ["magic-string@1.4.2", "", { "dependencies": { "@jridgewell/sourcemap-codec": "^1.6.0" } }, "sha512-vG+rjFRj1PqdIBozIxAGMjPlOhaVe+GXpbttY/iSK7rGcJRMlwNJO7dcUwmUqkymsFLJiNGI06t4D7Fr7yRC9g=="],
|
||||
|
||||
"markdown-it": ["markdown-it@15.0.3", "", { "dependencies": { "argparse": "^3.0.3", "entities": "^8.1.0", "linkify-it": "^6.1.0", "mdurl": "^2.1.0", "punycode.js": "^2.3.1", "uc.micro": "^3.0.0" }, "bin": { "markdown-it": "bin/markdown-it.mjs" } }, "sha512-+Az7Ojz3iRGu8KYMvJ6xVhvrxP3eE+vEtJX75Ow88XBpcQNV/0lGX5ZynIIBftREo4DC2jsveAMDaeltmm8QvQ=="],
|
||||
|
||||
"marked": ["marked@17.0.6", "", { "bin": { "marked": "bin/marked.js" } }, "sha512-gB0gkNafnonOw0obSTEGZTT86IuhILt2Wfx0mWH/1Au83kybTayroZ/V6nS25mN7u8ASy+5fMhgB3XPNrOZdmA=="],
|
||||
|
||||
"math-intrinsics": ["math-intrinsics@1.1.0", "", {}, "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g=="],
|
||||
|
||||
"mdn-data": ["mdn-data@2.27.1", "", {}, "sha512-9Yubnt3e8A0OKwxYSXyhLymGW4sCufcLG6VdiDdUGVkPhpqLxlvP5vl1983gQjJl3tqbrM731mjaZaP68AgosQ=="],
|
||||
|
||||
"mdurl": ["mdurl@2.1.0", "", {}, "sha512-1+HBaOx0zi/dQWht8rNv9MYf9qqpqL/kxI0hXImU6Y547zM6Sni8BQibt7ifgMcYtQg41ao3Ivd6cnSM86inpg=="],
|
||||
|
||||
"memorystream": ["memorystream@0.3.1", "", {}, "sha512-S3UwM3yj5mtUSEfP41UZmt/0SCoVYUcU1rkXv+BQ5Ig8ndL4sPoJNBUJERafdPb5jjHJGuMgytgKvKIf58XNBw=="],
|
||||
|
||||
"merge-stream": ["merge-stream@2.0.0", "", {}, "sha512-abv/qOcuPfk3URPfDzmZU1LKmuw8kT+0nIHvKrKgFrwifol/doWcdA4ZqsWQ8ENrFKkd67Mfpo/LovbIUsbt3w=="],
|
||||
@@ -1074,6 +1088,8 @@
|
||||
|
||||
"punycode": ["punycode@2.3.1", "", {}, "sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg=="],
|
||||
|
||||
"punycode.js": ["punycode.js@2.3.1", "", {}, "sha512-uxFIHU0YlHYhDQtV4R9J6a52SLx28BCjT+4ieh7IGbgwVJWO+km431c4yRlREUAsAmt/uMjQUyQHNEPf0M39CA=="],
|
||||
|
||||
"quansync": ["quansync@0.2.11", "", {}, "sha512-AifT7QEbW9Nri4tAwR5M/uzpBuqfZf+zwaEM/QkzEjj7NBuFD2rBuy0K3dE+8wltbezDV7JMA0WfnCPYRSYbXA=="],
|
||||
|
||||
"queue-microtask": ["queue-microtask@1.2.3", "", {}, "sha512-NuaNSa6flKT5JaSYQzJok04JzTL1CA6aGhv5rfLW3PgqA+M2ChpZQnAC8h8i4ZFkBS8X5RqkDBHA7r4hej3K9A=="],
|
||||
@@ -1184,6 +1200,8 @@
|
||||
|
||||
"typescript-eslint": ["typescript-eslint@8.50.0", "", { "dependencies": { "@typescript-eslint/eslint-plugin": "8.50.0", "@typescript-eslint/parser": "8.50.0", "@typescript-eslint/typescript-estree": "8.50.0", "@typescript-eslint/utils": "8.50.0" }, "peerDependencies": { "eslint": "^8.57.0 || ^9.0.0", "typescript": ">=4.8.4 <6.0.0" } }, "sha512-Q1/6yNUmCpH94fbgMUMg2/BSAr/6U7GBk61kZTv1/asghQOWOjTlp9K8mixS5NcJmm2creY+UFfGeW/+OcA64A=="],
|
||||
|
||||
"uc.micro": ["uc.micro@3.0.0", "", {}, "sha512-U3PppEkleoTnIfi8BozMx3yju3qc/L6SwqWo2Sw+54PX+PX0q9I+r1Um5HCmqD7n9VDX5/v3vQH/AjA6deDdtw=="],
|
||||
|
||||
"ufo": ["ufo@1.6.4", "", {}, "sha512-JFNbkD1Svwe0KvGi8GOeLcP4kAWQ609twvCdcHxq1oSL8svv39ZuSvajcD8B+5D0eL4+s1Is2D/O6KN3qcTeRA=="],
|
||||
|
||||
"uncrypto": ["uncrypto@0.1.3", "", {}, "sha512-Ql87qFHB3s/De2ClA9e0gsnS6zXG27SkTiSJwjCc9MebbfapQfuPzumMIUMi38ezPZVNFcHI9sUIepeQfw8J8Q=="],
|
||||
@@ -1392,6 +1410,8 @@
|
||||
|
||||
"glob/minimatch": ["minimatch@10.2.6", "", { "dependencies": { "brace-expansion": "^5.0.8" } }, "sha512-vpLQEs+VLCr1nU0BXS07maYoFwlDAH0gngQuuttxIwutDFEMHq2blX+8vpgxDdK3J1PwjCJiep77OitTZ4Ll1A=="],
|
||||
|
||||
"js-yaml/argparse": ["argparse@2.0.1", "", {}, "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q=="],
|
||||
|
||||
"jsdom/xml-name-validator": ["xml-name-validator@5.0.0", "", {}, "sha512-EvGK8EJ3DhaHfbRlETOWAS5pO9MZITeauHKJyb8wyajUfQUenkIg2MvLDTZ4T/TgIcm3HU0TFBgWWboAZ30UHg=="],
|
||||
|
||||
"magic-regexp/magic-string": ["magic-string@0.30.21", "", { "dependencies": { "@jridgewell/sourcemap-codec": "^1.5.5" } }, "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ=="],
|
||||
@@ -1406,6 +1426,8 @@
|
||||
|
||||
"npm-run-path/path-key": ["path-key@4.0.0", "", {}, "sha512-haREypq7xkM7ErfgIyA0z+Bj4AGKlMSdlQE2jvJo6huWD1EdkKYV+G/T4nq0YEF2vgTT8kqMFKo1uHn950r4SQ=="],
|
||||
|
||||
"parse5/entities": ["entities@6.0.1", "", {}, "sha512-aN97NXWF6AWBTahfVOIrB/NShkzi5H7F9r1s9mD3cDj4Ko5f2qhhVoYMibXF7GlLveb/D2ioWay8lxI97Ven3g=="],
|
||||
|
||||
"path-scurry/lru-cache": ["lru-cache@11.5.3", "", {}, "sha512-U4N8FgzmWxc8k1VH8Kr6lQg18U7Fjvby6wXHVRX/ZZ7IwWbRMgrRbP0Wrb5q5NVinryp4SQampHKdvtecItxUg=="],
|
||||
|
||||
"pkg-types/confbox": ["confbox@0.3.1", "", {}, "sha512-cKUSoKa8YxFZZSmraVi7onONx3amu77ngK3kGpsYHDH7drPwCRkQE1RYMPlLRrMtnciRj274XNRxcHxnKmDSnA=="],
|
||||
|
||||
@@ -26,6 +26,7 @@
|
||||
"@tiptap/pm": "3.31.3",
|
||||
"@tiptap/vue-3": "3.31.3",
|
||||
"@vueuse/core": "14.4.0",
|
||||
"markdown-it": "^15.0.3",
|
||||
"pinia": "^3.0.4",
|
||||
"tailwindcss": "^4.1.18",
|
||||
"vue": "^3.5.25",
|
||||
@@ -35,6 +36,7 @@
|
||||
"@iconify-json/lucide": "^1.2.136",
|
||||
"@iconify/utils": "^3.1.7",
|
||||
"@tsconfig/node24": "^24.0.3",
|
||||
"@types/markdown-it": "^14.2.0",
|
||||
"@types/node": "^24.10.1",
|
||||
"@vitejs/plugin-vue": "^6.0.2",
|
||||
"@vue/eslint-config-prettier": "^10.2.0",
|
||||
|
||||
@@ -103,6 +103,8 @@
|
||||
--text-lg--line-height: 24px;
|
||||
--text-xl: 1.25rem;
|
||||
--text-xl--line-height: 28px;
|
||||
--text-title: 1.5rem;
|
||||
--text-title--line-height: 32px;
|
||||
--text-2xl: 1.75rem;
|
||||
--text-2xl--line-height: 36px;
|
||||
--text-3xs: 0.625rem;
|
||||
@@ -171,6 +173,8 @@
|
||||
--ui-warning: var(--ui-color-warning-700);
|
||||
--ui-error: var(--ui-color-error-700);
|
||||
--rc-sand: #e8dfd1;
|
||||
--rc-sel: #e8dfd1;
|
||||
--rc-on-sel: #111111;
|
||||
--rc-on-sand: #111111;
|
||||
--rc-success-soft: #eaefea;
|
||||
--rc-info-soft: #ebeef0;
|
||||
@@ -204,6 +208,8 @@
|
||||
--ui-warning: var(--ui-color-warning-300);
|
||||
--ui-error: var(--ui-color-error-300);
|
||||
--rc-sand: #d4c5b0;
|
||||
--rc-sel: #222222;
|
||||
--rc-on-sel: #fafafa;
|
||||
--rc-on-sand: #111111;
|
||||
--rc-success-soft: #1f241f;
|
||||
--rc-info-soft: #202428;
|
||||
@@ -396,3 +402,13 @@ body {
|
||||
var(--ui-bg-accented) 8px 16px
|
||||
);
|
||||
}
|
||||
|
||||
.no-spin {
|
||||
appearance: textfield;
|
||||
-moz-appearance: textfield;
|
||||
}
|
||||
.no-spin::-webkit-inner-spin-button,
|
||||
.no-spin::-webkit-outer-spin-button {
|
||||
appearance: none;
|
||||
margin: 0;
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
<script setup lang="ts">
|
||||
import { t } from '@/i18n'
|
||||
|
||||
import { computed } from 'vue'
|
||||
import { useJsonCopy } from '@/composables/useJsonCopy'
|
||||
import { previewRoutes } from '@/lib/schemaBuilderSample'
|
||||
|
||||
const PANEL_COLUMNS = '1fr 1.4fr'
|
||||
|
||||
const props = defineProps<{ keyValue: string; json: string }>()
|
||||
|
||||
const open = defineModel<boolean>('open', { default: false })
|
||||
|
||||
const { copied, copy, label: copyLabel, icon: copyIcon } = useJsonCopy()
|
||||
|
||||
const routes = computed(() => previewRoutes(props.keyValue))
|
||||
const summary = computed(() => `${routes.value[0]!.method} ${routes.value[0]!.path}`)
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section
|
||||
:aria-label="t('API preview')"
|
||||
class="flex shrink-0 flex-col"
|
||||
data-testid="api-preview"
|
||||
>
|
||||
<div
|
||||
class="flex h-11 items-center gap-2.5 border-t border-default bg-default px-3 text-highlighted md:px-6"
|
||||
>
|
||||
<UButton
|
||||
color="neutral"
|
||||
variant="ghost"
|
||||
:icon="open ? 'i-lucide-chevron-down' : 'i-lucide-chevron-right'"
|
||||
:aria-expanded="open"
|
||||
data-testid="api-preview-toggle"
|
||||
class="h-11 min-w-0 flex-1 justify-start gap-2.5 px-0 font-semibold hover:bg-transparent"
|
||||
:ui="{ leadingIcon: 'size-3.5' }"
|
||||
@click="open = !open"
|
||||
>
|
||||
<span>{{ t('API preview') }}</span>
|
||||
<span
|
||||
class="min-w-0 flex-1 truncate text-left font-mono text-xs font-normal text-muted"
|
||||
>{{ summary }}</span
|
||||
>
|
||||
</UButton>
|
||||
<UButton
|
||||
:icon="copyIcon"
|
||||
color="neutral"
|
||||
variant="outline"
|
||||
data-testid="api-copy"
|
||||
class="h-7 gap-1.5 border border-accented bg-default px-2.5 text-xs text-highlighted ring-0"
|
||||
:class="copied ? 'text-success' : ''"
|
||||
:ui="{ leadingIcon: 'size-4' }"
|
||||
@click="copy(json)"
|
||||
>
|
||||
<span aria-live="polite">{{ copyLabel }}</span>
|
||||
</UButton>
|
||||
</div>
|
||||
<UCollapsible :open="open" :ui="{ content: 'overflow-hidden' }">
|
||||
<template #content>
|
||||
<div
|
||||
class="grid h-62 grid-rows-1 gap-4 bg-default px-6 pb-4"
|
||||
:style="{ gridTemplateColumns: PANEL_COLUMNS }"
|
||||
>
|
||||
<div class="flex min-h-0 min-w-0 flex-col gap-1.5">
|
||||
<span class="text-xs/4.5 text-muted">{{
|
||||
t('Where entries of this type live')
|
||||
}}</span>
|
||||
<ul
|
||||
class="m-0 flex list-none flex-col gap-0.5 border border-default bg-elevated px-3 py-2.5"
|
||||
>
|
||||
<li
|
||||
v-for="(route, index) in routes"
|
||||
:key="index"
|
||||
data-testid="api-route"
|
||||
class="truncate font-mono text-xs/4.75 text-highlighted"
|
||||
>
|
||||
<span class="inline-block w-14 text-muted">{{ route.method }}</span
|
||||
>{{ route.path }}
|
||||
</li>
|
||||
</ul>
|
||||
<span class="text-xs/4.5 text-pretty text-muted">{{
|
||||
t(
|
||||
'Updates as you edit. Fields you add or remove here appear after you save.',
|
||||
)
|
||||
}}</span>
|
||||
</div>
|
||||
<div class="flex min-h-0 min-w-0 flex-col gap-1.5">
|
||||
<span class="text-xs/4.5 text-muted">{{
|
||||
t("A sample entry. Values come from each field's type and default.")
|
||||
}}</span>
|
||||
<pre
|
||||
tabindex="0"
|
||||
data-testid="api-json"
|
||||
class="m-0 min-h-0 flex-1 overflow-auto border border-default bg-elevated px-3 py-2.5 font-mono text-xs/4.75 whitespace-pre text-highlighted"
|
||||
>{{ json }}</pre
|
||||
>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
</UCollapsible>
|
||||
</section>
|
||||
</template>
|
||||
@@ -0,0 +1,48 @@
|
||||
<script setup lang="ts">
|
||||
import { t } from '@/i18n'
|
||||
|
||||
import { computed } from 'vue'
|
||||
import { useJsonCopy } from '@/composables/useJsonCopy'
|
||||
import { previewRoutes } from '@/lib/schemaBuilderSample'
|
||||
import { BOTTOM_SHEET_UI } from '@/lib/sheetUi'
|
||||
|
||||
const props = defineProps<{ keyValue: string; json: string }>()
|
||||
|
||||
const open = defineModel<boolean>('open', { default: false })
|
||||
|
||||
const { copy, label: copyLabel, icon: copyIcon } = useJsonCopy()
|
||||
|
||||
const first = computed(() => previewRoutes(props.keyValue)[0]!)
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<USlideover
|
||||
v-model:open="open"
|
||||
side="bottom"
|
||||
:title="t('API preview')"
|
||||
:description="t('Where entries of this type live')"
|
||||
:ui="BOTTOM_SHEET_UI"
|
||||
>
|
||||
<template #body>
|
||||
<span class="text-xs text-muted" data-testid="api-sheet-route">{{
|
||||
`${first.method} ${first.path}`
|
||||
}}</span>
|
||||
<pre
|
||||
tabindex="0"
|
||||
data-testid="api-sheet-json"
|
||||
class="m-0 min-h-0 flex-1 overflow-auto border border-default bg-elevated px-3 py-2.5 font-mono text-xs/5 whitespace-pre text-highlighted"
|
||||
>{{ json }}</pre
|
||||
>
|
||||
</template>
|
||||
<template #footer>
|
||||
<UButton
|
||||
:icon="copyIcon"
|
||||
data-testid="api-sheet-copy"
|
||||
class="h-11 flex-1 justify-center"
|
||||
@click="copy(json)"
|
||||
>
|
||||
<span aria-live="polite">{{ copyLabel }}</span>
|
||||
</UButton>
|
||||
</template>
|
||||
</USlideover>
|
||||
</template>
|
||||
@@ -5,7 +5,8 @@ import { computed, nextTick, ref, useId } from 'vue'
|
||||
import { useMediaQuery } from '@vueuse/core'
|
||||
import AuthorAvatar from '@/components/AuthorAvatar.vue'
|
||||
import type { Byline } from '@/composables/useArticles'
|
||||
import { insertionTarget, moveItem } from '@/lib/articleMeta'
|
||||
import { moveItem } from '@/lib/arrayMove'
|
||||
import { insertionTarget } from '@/lib/articleMeta'
|
||||
|
||||
const DESKTOP_QUERY = '(min-width: 64rem)'
|
||||
const DESKTOP_AVATAR = 22
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
<script setup lang="ts">
|
||||
import { t } from '@/i18n'
|
||||
|
||||
import BuilderStatusChip from '@/components/BuilderStatusChip.vue'
|
||||
import type { BuilderStatus } from '@/lib/schemaBuilderModel'
|
||||
|
||||
defineProps<{
|
||||
status: BuilderStatus
|
||||
problems: number
|
||||
canSave: boolean
|
||||
canReveal: boolean
|
||||
canDiscard: boolean
|
||||
saving: boolean
|
||||
savedAt?: string
|
||||
}>()
|
||||
|
||||
defineEmits<{ save: []; discard: [] }>()
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="flex shrink-0 items-center gap-2 md:gap-3">
|
||||
<BuilderStatusChip :status="status" :problems="problems" :saved-at="savedAt" />
|
||||
<span class="flex-1 md:hidden" />
|
||||
<UButton
|
||||
color="neutral"
|
||||
variant="outline"
|
||||
:disabled="!canDiscard"
|
||||
class="h-11 border border-accented bg-default px-3 text-highlighted ring-0 md:h-8"
|
||||
@click="$emit('discard')"
|
||||
>
|
||||
{{ t('Discard') }}
|
||||
</UButton>
|
||||
<UButton
|
||||
:disabled="!canSave && !canReveal"
|
||||
:aria-disabled="canReveal ? 'true' : undefined"
|
||||
:loading="saving"
|
||||
class="h-11 px-4 md:h-8"
|
||||
:class="saving ? 'disabled:opacity-40' : ''"
|
||||
@click="$emit('save')"
|
||||
>
|
||||
{{ saving ? t('Saving…') : t('Save') }}
|
||||
</UButton>
|
||||
<slot />
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,71 @@
|
||||
<script setup lang="ts">
|
||||
import { t } from '@/i18n'
|
||||
|
||||
import { computed } from 'vue'
|
||||
|
||||
const props = defineProps<{
|
||||
kind: 'new' | 'changed' | 'cause' | 'required' | 'unique' | 'default'
|
||||
compact?: boolean
|
||||
}>()
|
||||
|
||||
const badges = {
|
||||
new: {
|
||||
get label() {
|
||||
return t('New')
|
||||
},
|
||||
class: 'border border-(--rc-sand) bg-(--rc-sand) text-(--rc-on-sand)',
|
||||
},
|
||||
changed: {
|
||||
get label() {
|
||||
return t('Changed')
|
||||
},
|
||||
class: 'border border-(--rc-info-soft) bg-(--rc-info-soft) text-info',
|
||||
},
|
||||
cause: {
|
||||
get label() {
|
||||
return t('Possible cause')
|
||||
},
|
||||
icon: 'i-lucide-triangle-alert',
|
||||
class: 'border border-(--rc-warning-soft) bg-(--rc-warning-soft) text-warning',
|
||||
},
|
||||
required: {
|
||||
get label() {
|
||||
return t('Required')
|
||||
},
|
||||
class: 'border border-accented bg-transparent text-toned',
|
||||
},
|
||||
default: {
|
||||
get label() {
|
||||
return t('Default')
|
||||
},
|
||||
class: 'border border-accented bg-transparent text-toned',
|
||||
},
|
||||
unique: {
|
||||
get label() {
|
||||
return t('Unique')
|
||||
},
|
||||
class: 'border border-accented bg-transparent text-toned',
|
||||
},
|
||||
} as const
|
||||
|
||||
const badge = computed(() => badges[props.kind])
|
||||
const badgeIcon = computed(() => ('icon' in badge.value ? badge.value.icon : undefined))
|
||||
const badgeLabel = computed(() =>
|
||||
props.compact ? badge.value.label.charAt(0).toUpperCase() : badge.value.label,
|
||||
)
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<UBadge
|
||||
color="neutral"
|
||||
variant="soft"
|
||||
:icon="badgeIcon"
|
||||
:class="badge.class"
|
||||
:ui="{
|
||||
base: 'h-5 shrink-0 gap-1 px-1.5 py-0 text-xs font-medium whitespace-nowrap',
|
||||
leadingIcon: 'size-3',
|
||||
}"
|
||||
>
|
||||
{{ badgeLabel }}
|
||||
</UBadge>
|
||||
</template>
|
||||
@@ -0,0 +1,59 @@
|
||||
<script setup lang="ts">
|
||||
import FieldInspector from '@/components/FieldInspector.vue'
|
||||
import type { useSchemaBuilder } from '@/composables/useSchemaBuilder'
|
||||
import type { BuilderField } from '@/lib/schemaBuilderModel'
|
||||
import type { FieldErrors } from '@/lib/schemaBuilderValidation'
|
||||
|
||||
type Builder = ReturnType<typeof useSchemaBuilder>
|
||||
|
||||
type InspectorActions = Pick<
|
||||
Builder,
|
||||
| 'setLabel'
|
||||
| 'setFieldKey'
|
||||
| 'unlockFieldKey'
|
||||
| 'resetFieldKey'
|
||||
| 'setFieldType'
|
||||
| 'patchField'
|
||||
| 'setLimit'
|
||||
| 'setDefault'
|
||||
| 'addChoice'
|
||||
| 'removeChoice'
|
||||
| 'renameChoice'
|
||||
| 'reorderChoices'
|
||||
>
|
||||
|
||||
const props = defineProps<{
|
||||
actions: InspectorActions
|
||||
saving: boolean
|
||||
focusToken: number
|
||||
field: BuilderField
|
||||
errors: FieldErrors
|
||||
compact: boolean
|
||||
}>()
|
||||
|
||||
const uid = () => props.field.uid
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<FieldInspector
|
||||
:field="field"
|
||||
:errors="errors"
|
||||
:disabled="saving"
|
||||
:compact="compact"
|
||||
:focus-token="focusToken"
|
||||
@label="actions.setLabel(uid(), $event)"
|
||||
@key="actions.setFieldKey(uid(), $event)"
|
||||
@unlock="actions.unlockFieldKey(uid())"
|
||||
@reset="actions.resetFieldKey(uid())"
|
||||
@type="actions.setFieldType(uid(), $event)"
|
||||
@required="actions.patchField(uid(), { required: $event })"
|
||||
@unique="actions.patchField(uid(), { unique: $event })"
|
||||
@limit="(which, value) => actions.setLimit(uid(), which, value)"
|
||||
@default="actions.setDefault(uid(), $event)"
|
||||
@default-on="actions.patchField(uid(), { defaultOn: $event })"
|
||||
@add-choice="actions.addChoice(uid(), $event)"
|
||||
@remove-choice="actions.removeChoice(uid(), $event)"
|
||||
@rename-choice="(index, text) => actions.renameChoice(uid(), index, text)"
|
||||
@reorder-choices="actions.reorderChoices(uid(), $event)"
|
||||
/>
|
||||
</template>
|
||||
@@ -0,0 +1,51 @@
|
||||
<script setup lang="ts">
|
||||
import { t } from '@/i18n'
|
||||
|
||||
import { computed, ref } from 'vue'
|
||||
|
||||
defineProps<{ disabled: boolean }>()
|
||||
|
||||
const emit = defineEmits<{ delete: [] }>()
|
||||
|
||||
const trigger = ref<{ $el: HTMLElement } | null>(null)
|
||||
|
||||
const items = computed(() => [
|
||||
[
|
||||
{
|
||||
label: t('Delete content type'),
|
||||
icon: 'i-lucide-trash-2',
|
||||
color: 'error' as const,
|
||||
onSelect: () => emit('delete'),
|
||||
},
|
||||
],
|
||||
])
|
||||
|
||||
function focus() {
|
||||
trigger.value?.$el.focus()
|
||||
}
|
||||
|
||||
defineExpose({ focus })
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<UDropdownMenu
|
||||
:items="items"
|
||||
:content="{ align: 'end' }"
|
||||
:ui="{
|
||||
content: 'w-55 p-1',
|
||||
group: 'p-0',
|
||||
item: 'h-8 gap-2 px-2 text-sm max-md:h-11',
|
||||
itemLeadingIcon: 'size-4',
|
||||
}"
|
||||
>
|
||||
<UButton
|
||||
ref="trigger"
|
||||
icon="i-lucide-ellipsis"
|
||||
color="neutral"
|
||||
variant="ghost"
|
||||
:disabled="disabled"
|
||||
:aria-label="t('More actions')"
|
||||
class="size-8 shrink-0 justify-center text-muted data-[state=open]:outline-2 data-[state=open]:outline-offset-2 data-[state=open]:outline-primary max-md:size-11"
|
||||
/>
|
||||
</UDropdownMenu>
|
||||
</template>
|
||||
@@ -0,0 +1,73 @@
|
||||
<script setup lang="ts">
|
||||
import { t } from '@/i18n'
|
||||
|
||||
import { computed } from 'vue'
|
||||
import type { BuilderStatus } from '@/lib/schemaBuilderModel'
|
||||
|
||||
const props = withDefaults(
|
||||
defineProps<{
|
||||
status: BuilderStatus | 'new' | 'unsaved'
|
||||
problems?: number
|
||||
savedAt?: string
|
||||
}>(),
|
||||
{ problems: 0, savedAt: undefined },
|
||||
)
|
||||
|
||||
function chipText(
|
||||
status: BuilderStatus | 'new' | 'unsaved',
|
||||
problems: number,
|
||||
savedAt: string | undefined,
|
||||
): string {
|
||||
switch (status) {
|
||||
case 'saving':
|
||||
return t('Saving…')
|
||||
case 'offline':
|
||||
return t('Waiting for connection')
|
||||
case 'saved':
|
||||
return savedAt ? t('Saved at {0}', [savedAt]) : t('Saved')
|
||||
case 'failed':
|
||||
return t('Save failed')
|
||||
case 'new':
|
||||
return t('New entry')
|
||||
case 'unsaved':
|
||||
return t('Not saved')
|
||||
case 'problems':
|
||||
return problems === 1 ? t('1 problem to fix') : t('{0} problems to fix', [problems])
|
||||
case 'dirty':
|
||||
return t('Unsaved changes')
|
||||
case 'none':
|
||||
return ''
|
||||
}
|
||||
}
|
||||
|
||||
const text = computed(() => chipText(props.status, props.problems, props.savedAt))
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<span
|
||||
v-if="status !== 'none'"
|
||||
role="status"
|
||||
data-testid="builder-chip"
|
||||
class="inline-flex shrink-0 items-center gap-1.5 text-xs whitespace-nowrap"
|
||||
:class="{
|
||||
'text-warning': status === 'dirty',
|
||||
'text-error': status === 'failed' || status === 'problems' || status === 'unsaved',
|
||||
'text-muted':
|
||||
status === 'saving' ||
|
||||
status === 'offline' ||
|
||||
status === 'saved' ||
|
||||
status === 'new',
|
||||
}"
|
||||
>
|
||||
<UIcon
|
||||
v-if="status === 'saving'"
|
||||
name="i-lucide-loader-circle"
|
||||
class="size-3.5 animate-spin"
|
||||
/>
|
||||
<UIcon v-else-if="status === 'offline'" name="i-lucide-wifi-off" class="size-3.5" />
|
||||
<UIcon v-else-if="status === 'dirty'" name="i-lucide-circle-dot" class="size-3.5" />
|
||||
<UIcon v-else-if="status === 'saved'" name="i-lucide-check" class="size-3.5" />
|
||||
<UIcon v-else-if="status !== 'new'" name="i-lucide-circle-alert" class="size-3.5" />
|
||||
<span>{{ text }}</span>
|
||||
</span>
|
||||
</template>
|
||||
@@ -0,0 +1,123 @@
|
||||
<script setup lang="ts">
|
||||
import { t } from '@/i18n'
|
||||
|
||||
import { computed, nextTick, ref, watch } from 'vue'
|
||||
import DirectoryField from '@/components/DirectoryField.vue'
|
||||
import SlugField from '@/components/SlugField.vue'
|
||||
import {
|
||||
BUILDER_LIMITS,
|
||||
PREVIEW_KEY_FALLBACK,
|
||||
keyDisplayMode,
|
||||
type KeyMode,
|
||||
} from '@/lib/schemaBuilderModel'
|
||||
|
||||
const props = defineProps<{
|
||||
name: string
|
||||
keyValue: string
|
||||
keyMode: KeyMode
|
||||
nameError?: string
|
||||
keyError?: string
|
||||
disabled: boolean
|
||||
keyFocusToken: number
|
||||
keyLocked?: boolean
|
||||
}>()
|
||||
|
||||
const emit = defineEmits<{
|
||||
'update:name': [value: string]
|
||||
'update:key': [value: string]
|
||||
unlock: []
|
||||
reset: []
|
||||
}>()
|
||||
|
||||
const root = ref<HTMLElement | null>(null)
|
||||
const tipOpen = ref(false)
|
||||
const slugMode = computed(() => keyDisplayMode(props.keyMode, props.keyValue))
|
||||
|
||||
watch(
|
||||
() => props.keyFocusToken,
|
||||
async () => {
|
||||
await nextTick()
|
||||
root.value?.querySelector<HTMLInputElement>('input[name="key"]')?.focus()
|
||||
},
|
||||
)
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div
|
||||
ref="root"
|
||||
class="flex min-w-0 flex-col gap-3 transition-opacity md:flex-row md:gap-4"
|
||||
:class="[disabled ? 'opacity-60' : '', 'md:items-start']"
|
||||
>
|
||||
<div class="md:w-80">
|
||||
<DirectoryField :label="t('Name')" name="name" required :error="nameError">
|
||||
<UInput
|
||||
:model-value="name"
|
||||
:placeholder="t('For example, Events')"
|
||||
:maxlength="BUILDER_LIMITS.nameMax"
|
||||
:disabled="disabled"
|
||||
:color="nameError ? 'error' : undefined"
|
||||
required
|
||||
class="w-full"
|
||||
:ui="{ base: 'h-11 text-lg md:h-8 md:text-sm' }"
|
||||
@update:model-value="emit('update:name', String($event))"
|
||||
/>
|
||||
</DirectoryField>
|
||||
</div>
|
||||
<div v-if="keyLocked" class="md:w-80">
|
||||
<UTooltip
|
||||
v-model:open="tipOpen"
|
||||
:text="
|
||||
t(
|
||||
'The key is used in URLs and the API, so it can\'t change after the type is created.',
|
||||
)
|
||||
"
|
||||
:content="{ side: 'bottom', align: 'start' }"
|
||||
:ui="{
|
||||
content:
|
||||
'h-auto w-65 items-start bg-inverted px-2.5 py-2 text-xs/4.5 text-inverted shadow-(--shadow-popover) ring-0',
|
||||
text: 'whitespace-normal',
|
||||
}"
|
||||
>
|
||||
<div @focusin="tipOpen = true" @focusout="tipOpen = false">
|
||||
<SlugField
|
||||
:label="t('Key')"
|
||||
name="key"
|
||||
mode="manual"
|
||||
:value="keyValue"
|
||||
:disabled="disabled"
|
||||
dense
|
||||
locked
|
||||
:maxlength="BUILDER_LIMITS.typeKeyMax"
|
||||
/>
|
||||
</div>
|
||||
</UTooltip>
|
||||
</div>
|
||||
<div v-else class="md:w-80">
|
||||
<SlugField
|
||||
:label="t('Key')"
|
||||
name="key"
|
||||
:mode="slugMode"
|
||||
:value="keyValue"
|
||||
:error="keyError"
|
||||
:disabled="disabled"
|
||||
dense
|
||||
reset-in-label
|
||||
:help="
|
||||
t(
|
||||
'Used in URLs and the API. Lowercase letters, digits and hyphens. It can\'t change after you save.',
|
||||
)
|
||||
"
|
||||
:edit-label="t('Edit key')"
|
||||
:placeholder="PREVIEW_KEY_FALLBACK"
|
||||
:maxlength="BUILDER_LIMITS.typeKeyMax"
|
||||
@update:value="emit('update:key', $event)"
|
||||
@unlock="emit('unlock')"
|
||||
@reset="emit('reset')"
|
||||
/>
|
||||
</div>
|
||||
<span class="hidden flex-1 md:block" />
|
||||
<div v-if="$slots.actions" class="flex md:mt-6.5 md:h-8 md:items-center">
|
||||
<slot name="actions" />
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,175 @@
|
||||
<script setup lang="ts">
|
||||
import { t } from '@/i18n'
|
||||
|
||||
import { computed, nextTick, ref } from 'vue'
|
||||
import { useKeyboardReorder } from '@/composables/useKeyboardReorder'
|
||||
import { BUILDER_LIMITS } from '@/lib/schemaBuilderModel'
|
||||
|
||||
const props = defineProps<{
|
||||
options: string[]
|
||||
rowErrors?: Record<number, string>
|
||||
listError?: string
|
||||
disabled: boolean
|
||||
}>()
|
||||
|
||||
const emit = defineEmits<{
|
||||
add: [text: string]
|
||||
remove: [index: number]
|
||||
rename: [index: number, text: string]
|
||||
reorder: [options: string[]]
|
||||
}>()
|
||||
|
||||
const root = ref<HTMLElement | null>(null)
|
||||
const draft = ref('')
|
||||
const addInput = ref<{ inputRef?: HTMLInputElement | null } | null>(null)
|
||||
|
||||
interface ChoiceRow {
|
||||
index: number
|
||||
text: string
|
||||
}
|
||||
|
||||
const reorder = useKeyboardReorder<ChoiceRow>({
|
||||
items: () => props.options.map((text, index) => ({ index, text })),
|
||||
name: (row) => row.text.trim() || t('Choice'),
|
||||
commit: (next) =>
|
||||
emit(
|
||||
'reorder',
|
||||
next.map((row) => row.text),
|
||||
),
|
||||
root: () => root.value,
|
||||
})
|
||||
|
||||
const rows = computed(() => reorder.shown.value)
|
||||
const full = computed(() => props.options.length >= BUILDER_LIMITS.choicesMax)
|
||||
const countText = computed(() => t('{0} of {1}', [props.options.length, BUILDER_LIMITS.choicesMax]))
|
||||
const canAdd = computed(() => !props.disabled && !full.value && draft.value.trim() !== '')
|
||||
|
||||
async function add() {
|
||||
if (!canAdd.value) {
|
||||
return
|
||||
}
|
||||
emit('add', draft.value)
|
||||
draft.value = ''
|
||||
await nextTick()
|
||||
addInput.value?.inputRef?.focus()
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div ref="root" class="flex flex-col gap-2" data-testid="choice-list">
|
||||
<div class="flex justify-between">
|
||||
<span class="font-medium text-highlighted"
|
||||
>{{ t('Choices') }}<span aria-hidden="true"> *</span></span
|
||||
>
|
||||
<span class="font-mono text-xs text-muted" data-testid="choice-count">{{
|
||||
countText
|
||||
}}</span>
|
||||
</div>
|
||||
|
||||
<div
|
||||
role="status"
|
||||
aria-live="polite"
|
||||
data-testid="choice-live"
|
||||
:class="
|
||||
reorder.active.value
|
||||
? 'bg-inverted px-2.5 py-2 text-xs/4.5 text-inverted'
|
||||
: 'sr-only'
|
||||
"
|
||||
>
|
||||
{{ reorder.announcement.value }}
|
||||
</div>
|
||||
|
||||
<ul class="m-0 flex list-none flex-col gap-2 p-0">
|
||||
<li
|
||||
v-for="(row, index) in rows"
|
||||
:key="row.index"
|
||||
data-testid="choice-row"
|
||||
class="flex flex-col gap-1"
|
||||
>
|
||||
<div
|
||||
class="flex items-center gap-1"
|
||||
:class="reorder.grabbed.value === index ? 'outline-2 outline-primary' : ''"
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
:data-handle="index"
|
||||
:aria-label="t('Move {0}', [row.text.trim() || t('Choice')])"
|
||||
:aria-pressed="reorder.grabbed.value === index"
|
||||
:disabled="disabled"
|
||||
class="flex size-7 shrink-0 items-center justify-center text-muted focus-visible:outline-2 focus-visible:outline-primary max-md:size-11"
|
||||
@keydown="reorder.onKeydown($event, index)"
|
||||
>
|
||||
<UIcon name="i-lucide-grip-vertical" class="size-4" />
|
||||
</button>
|
||||
<UInput
|
||||
:model-value="row.text"
|
||||
:placeholder="t('Choice')"
|
||||
:disabled="disabled"
|
||||
:color="rowErrors?.[row.index] ? 'error' : undefined"
|
||||
:aria-label="t('Choice {0}', [index + 1])"
|
||||
:aria-invalid="rowErrors?.[row.index] ? 'true' : undefined"
|
||||
:aria-describedby="
|
||||
rowErrors?.[row.index] ? `choice-error-${row.index}` : undefined
|
||||
"
|
||||
class="min-w-0 flex-1"
|
||||
:ui="{ base: 'h-11 text-lg md:h-8 md:text-sm' }"
|
||||
@update:model-value="emit('rename', row.index, String($event))"
|
||||
/>
|
||||
<UButton
|
||||
icon="i-lucide-x"
|
||||
color="neutral"
|
||||
variant="ghost"
|
||||
:disabled="disabled"
|
||||
:aria-label="t('Remove {0}', [row.text.trim() || t('Choice')])"
|
||||
class="size-7 justify-center max-md:size-11"
|
||||
@click="emit('remove', row.index)"
|
||||
/>
|
||||
</div>
|
||||
<span
|
||||
v-if="rowErrors?.[row.index]"
|
||||
:id="`choice-error-${row.index}`"
|
||||
role="alert"
|
||||
class="ml-8 flex items-start gap-1.5 text-xs/4.5 text-error max-md:ml-12"
|
||||
>
|
||||
<UIcon name="i-lucide-circle-alert" class="mt-0.5 size-3.5 shrink-0" />
|
||||
<span>{{ rowErrors[row.index] }}</span>
|
||||
</span>
|
||||
</li>
|
||||
</ul>
|
||||
|
||||
<p v-if="listError" role="alert" class="flex items-start gap-1.5 text-xs/4.5 text-error">
|
||||
<UIcon name="i-lucide-circle-alert" class="mt-0.5 size-3.5 shrink-0" />
|
||||
<span>{{ listError }}</span>
|
||||
</p>
|
||||
|
||||
<div class="flex gap-2 pl-8 max-md:pl-12">
|
||||
<UInput
|
||||
ref="addInput"
|
||||
v-model="draft"
|
||||
:placeholder="t('Add a choice')"
|
||||
:aria-label="t('Add a choice')"
|
||||
:disabled="disabled || full"
|
||||
class="min-w-0 flex-1"
|
||||
:ui="{ base: 'h-11 border-dashed text-lg md:h-8 md:text-sm' }"
|
||||
@keydown.enter.prevent="add"
|
||||
/>
|
||||
<UButton
|
||||
icon="i-lucide-plus"
|
||||
color="neutral"
|
||||
variant="outline"
|
||||
:disabled="!canAdd"
|
||||
class="h-11 border border-accented bg-default px-3 text-highlighted ring-0 md:h-8"
|
||||
@click="add"
|
||||
>
|
||||
{{ t('Add') }}
|
||||
</UButton>
|
||||
</div>
|
||||
<p class="text-xs/4.5 text-pretty text-muted">
|
||||
{{
|
||||
t(
|
||||
'Add 1 to 50 choices. Each one needs a different name. Removing a choice that entries use will be refused when you save.',
|
||||
)
|
||||
}}
|
||||
</p>
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,119 @@
|
||||
<script setup lang="ts">
|
||||
import { t } from '@/i18n'
|
||||
|
||||
import { ref } from 'vue'
|
||||
import { useMediaQuery } from '@vueuse/core'
|
||||
import ColumnPickerList from '@/components/ColumnPickerList.vue'
|
||||
import type { BuiltinField } from '@/lib/contentTypes'
|
||||
import { COLUMN_CAP } from '@/lib/entryColumns'
|
||||
import { BOTTOM_SHEET_UI } from '@/lib/sheetUi'
|
||||
|
||||
const DESKTOP_QUERY = '(min-width: 48rem)'
|
||||
const FOCUS_RING =
|
||||
'focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary'
|
||||
const TRIGGER = `h-11 w-11 justify-center rounded-none border border-accented bg-default p-0 text-highlighted ring-0 md:h-8 md:w-auto md:px-3 ${FOCUS_RING}`
|
||||
|
||||
defineProps<{ fields: BuiltinField[]; keys: string[]; atCap: boolean; disabled?: boolean }>()
|
||||
|
||||
const emit = defineEmits<{ toggle: [key: string, on: boolean]; reset: [] }>()
|
||||
|
||||
const isDesktop = useMediaQuery(DESKTOP_QUERY)
|
||||
const open = ref(false)
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<UPopover
|
||||
v-if="isDesktop"
|
||||
v-model:open="open"
|
||||
:content="{ align: 'start', side: 'bottom', sideOffset: 4 }"
|
||||
:ui="{
|
||||
content:
|
||||
'w-75 rounded-none bg-default p-2 shadow-(--shadow-popover) ring-0 border border-default',
|
||||
}"
|
||||
>
|
||||
<UButton
|
||||
color="neutral"
|
||||
variant="outline"
|
||||
icon="i-lucide-columns-3"
|
||||
:disabled="disabled"
|
||||
:class="TRIGGER"
|
||||
>
|
||||
{{ t('Columns') }}
|
||||
</UButton>
|
||||
<template #content>
|
||||
<div class="flex flex-col gap-2" data-testid="column-picker">
|
||||
<div class="flex items-center justify-between px-2 py-1">
|
||||
<span class="font-semibold text-highlighted">{{ t('Columns') }}</span>
|
||||
<span class="text-xs text-muted">{{
|
||||
t('{0} of {1}', [keys.length, COLUMN_CAP])
|
||||
}}</span>
|
||||
</div>
|
||||
<ColumnPickerList
|
||||
:fields="fields"
|
||||
:keys="keys"
|
||||
:at-cap="atCap"
|
||||
@toggle="(key, on) => emit('toggle', key, on)"
|
||||
/>
|
||||
<div class="flex justify-end px-2 py-1">
|
||||
<UButton
|
||||
color="neutral"
|
||||
variant="outline"
|
||||
class="h-7 rounded-none border border-accented bg-default px-2.5 text-xs text-highlighted ring-0"
|
||||
@click="emit('reset')"
|
||||
>
|
||||
{{ t('Reset') }}
|
||||
</UButton>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
</UPopover>
|
||||
|
||||
<USlideover
|
||||
v-else
|
||||
v-model:open="open"
|
||||
side="bottom"
|
||||
:title="t('Columns')"
|
||||
:description="t('Columns')"
|
||||
:ui="BOTTOM_SHEET_UI"
|
||||
>
|
||||
<UButton
|
||||
color="neutral"
|
||||
variant="outline"
|
||||
icon="i-lucide-columns-3"
|
||||
:aria-label="t('Columns')"
|
||||
:disabled="disabled"
|
||||
:class="TRIGGER"
|
||||
/>
|
||||
<template #title>
|
||||
<span>{{ t('Columns') }}</span>
|
||||
<span class="ms-2 text-xs font-normal text-muted">{{
|
||||
t('{0} of {1}', [keys.length, COLUMN_CAP])
|
||||
}}</span>
|
||||
</template>
|
||||
<template #body>
|
||||
<p class="text-muted">
|
||||
{{ t('Choose up to {0} fields to show. {1} selected.', [COLUMN_CAP, keys.length]) }}
|
||||
</p>
|
||||
<ColumnPickerList
|
||||
touch
|
||||
:fields="fields"
|
||||
:keys="keys"
|
||||
:at-cap="atCap"
|
||||
@toggle="(key, on) => emit('toggle', key, on)"
|
||||
/>
|
||||
</template>
|
||||
<template #footer>
|
||||
<UButton
|
||||
color="neutral"
|
||||
variant="outline"
|
||||
class="h-11 flex-1 justify-center rounded-none border border-accented bg-default text-highlighted ring-0"
|
||||
@click="emit('reset')"
|
||||
>
|
||||
{{ t('Reset') }}
|
||||
</UButton>
|
||||
<UButton class="h-11 flex-1 justify-center" @click="open = false">
|
||||
{{ t('Done') }}
|
||||
</UButton>
|
||||
</template>
|
||||
</USlideover>
|
||||
</template>
|
||||
@@ -0,0 +1,77 @@
|
||||
<script setup lang="ts">
|
||||
import { t } from '@/i18n'
|
||||
|
||||
import { fieldTypeSpec } from '@/lib/fieldTypes'
|
||||
import { COLUMN_CAP } from '@/lib/entryColumns'
|
||||
import type { BuiltinField } from '@/lib/contentTypes'
|
||||
|
||||
const props = defineProps<{
|
||||
fields: BuiltinField[]
|
||||
keys: string[]
|
||||
atCap: boolean
|
||||
touch?: boolean
|
||||
}>()
|
||||
|
||||
const emit = defineEmits<{ toggle: [key: string, on: boolean] }>()
|
||||
|
||||
function isLocked(key: string) {
|
||||
const checked = props.keys.includes(key)
|
||||
return checked ? props.keys.length === 1 : props.atCap
|
||||
}
|
||||
|
||||
const ROW = 'flex items-center gap-2.5 px-2'
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="flex flex-col">
|
||||
<div
|
||||
v-for="field in fields"
|
||||
:key="field.key"
|
||||
data-testid="column-row"
|
||||
:class="[ROW, touch ? 'min-h-12' : 'min-h-9']"
|
||||
>
|
||||
<UCheckbox
|
||||
:model-value="keys.includes(field.key)"
|
||||
:disabled="isLocked(field.key)"
|
||||
:ui="{
|
||||
root: 'w-full items-center',
|
||||
base: 'rounded-none',
|
||||
container: 'h-auto',
|
||||
wrapper: 'ms-2.5 min-w-0 flex-1',
|
||||
label: 'flex w-full items-center gap-2.5 font-normal text-default',
|
||||
}"
|
||||
@update:model-value="emit('toggle', field.key, $event === true)"
|
||||
>
|
||||
<template #label>
|
||||
<UIcon
|
||||
:name="fieldTypeSpec(field.type).icon"
|
||||
class="size-3.5 shrink-0 text-muted"
|
||||
/>
|
||||
<span class="min-w-0 flex-1 truncate">{{ field.label }}</span>
|
||||
<span class="font-mono text-xs text-muted">{{ field.key }}</span>
|
||||
</template>
|
||||
</UCheckbox>
|
||||
</div>
|
||||
<div data-testid="column-fixed-row" :class="[ROW, touch ? 'min-h-12' : 'min-h-9']">
|
||||
<UCheckbox
|
||||
:model-value="false"
|
||||
disabled
|
||||
:ui="{
|
||||
root: 'w-full items-center',
|
||||
base: 'rounded-none',
|
||||
container: 'h-auto',
|
||||
wrapper: 'ms-2.5 min-w-0 flex-1',
|
||||
label: 'flex w-full items-center gap-2.5 font-normal text-muted',
|
||||
}"
|
||||
>
|
||||
<template #label>
|
||||
<UIcon name="i-lucide-clock" class="size-3.5 shrink-0" />
|
||||
<span>{{ t('Created and updated dates always show') }}</span>
|
||||
</template>
|
||||
</UCheckbox>
|
||||
</div>
|
||||
<p v-if="atCap" role="status" class="px-2 pt-1 text-xs text-muted">
|
||||
{{ t('You can show up to {0} fields.', [COLUMN_CAP]) }}
|
||||
</p>
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,30 @@
|
||||
<script setup lang="ts">
|
||||
import { t } from '@/i18n'
|
||||
|
||||
const emit = defineEmits<{ create: [] }>()
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<UEmpty
|
||||
variant="naked"
|
||||
icon="i-lucide-file-plus"
|
||||
:title="t('No entries yet')"
|
||||
:description="
|
||||
t(
|
||||
'Use New entry to add the first entry. Each entry follows the fields of this content type.',
|
||||
)
|
||||
"
|
||||
:ui="{
|
||||
root: 'gap-3 border border-default bg-default px-6 py-10 sm:px-6 sm:py-10 lg:px-6 lg:py-10',
|
||||
avatar: 'mb-0 size-11 rounded-none bg-elevated text-toned',
|
||||
title: 'text-md/7 font-semibold',
|
||||
description: 'max-w-90 text-muted text-pretty',
|
||||
}"
|
||||
>
|
||||
<template #actions>
|
||||
<UButton icon="i-lucide-plus" class="h-8 px-4 max-md:h-11" @click="emit('create')">
|
||||
{{ t('New entry') }}
|
||||
</UButton>
|
||||
</template>
|
||||
</UEmpty>
|
||||
</template>
|
||||
Loaded 100 of 303 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user