Compare commits

..
233 changed files with 15727 additions and 1372 deletions

No files matched your search

+1
View File
@@ -28,3 +28,4 @@ CLAUDE.md
.agents/ .agents/
AGENTS.md AGENTS.md
codex-workflow.md codex-workflow.md
CODING_STANDARDS.md
-100
View File
@@ -1,100 +0,0 @@
# Coding Standards
These rules apply to every file in this repo , for humans and agents alike.
## General rules
1. Follow standard conventions.
2. Keep it simple stupid. Simpler is always better. Reduce complexity as much as possible.
3. Boy scout rule. Leave the campground cleaner than you found it.
4. Always find root cause. Always look for the root cause of a problem.
## Design rules
1. Keep configurable data at high levels.
2. Prefer polymorphism to if/else or switch/case.
3. Separate multi-threading code.
4. Prevent over-configurability.
5. Use dependency injection.
6. Follow Law of Demeter. A class should know only its direct dependencies.
## Understandability tips
1. Be consistent. If you do something a certain way, do all similar things in the same way.
2. Use explanatory variables.
3. Encapsulate boundary conditions. Boundary conditions are hard to keep track of. Put the processing for them in one place.
4. Prefer dedicated value objects to primitive types.
5. Avoid logical dependency. Don't write methods which work correctly only depending on something else in the same class.
6. Avoid negative conditionals.
## Names rules
1. Choose descriptive and unambiguous names.
2. Make meaningful distinctions.
3. Use pronounceable names.
4. Use searchable names.
5. Replace magic numbers with named constants.
6. Avoid encodings. Don't append prefixes or type information.
## Functions rules
1. Small.
2. Do one thing.
3. Use descriptive names.
4. Prefer fewer arguments.
5. Have no side effects.
6. Don't use flag arguments. Split the method into several independent methods that can be called from the client without the flag.
## Comments rules
1. No comments in the codebase. This covers Go, TypeScript/Vue, HTML templates and config files (YAML, TOML, `.env.example`, `.gitattributes`, …).
2. Explain yourself in code instead: descriptive names, small functions, named constants, explanatory variables.
3. The only exceptions are tool directives the code needs to work, such as `//go:build` and `//go:embed`.
4. Don't comment out code; just remove it.
5. Prose belongs in `docs/` and `README.md`, not in source files.
## Source code structure
1. Separate concepts vertically.
2. Related code should appear vertically dense.
3. Declare variables close to their usage.
4. Dependent functions should be close.
5. Similar functions should be close.
6. Place functions in the downward direction (caller above callee).
7. Keep lines short.
8. Don't use horizontal alignment.
9. Use white space to associate related things and disassociate weakly related ones.
10. Don't break indentation.
## Objects and data structures
1. Hide internal structure.
2. Prefer data structures when there's no behavior to attach.
3. Avoid hybrid structures (half object, half data).
4. Keep classes small.
5. Each class should do one thing.
6. Keep the number of instance variables small.
7. Base classes should know nothing about their derivatives.
8. Prefer many small functions over one function with a parameter that selects behavior.
9. Prefer non-static methods to static methods.
## Tests
1. One assert per test.
2. Readable.
3. Fast.
4. Independent.
5. Repeatable.
## Code smells to watch for
1. **Rigidity** — the software is difficult to change; a small change causes a cascade of subsequent changes.
2. **Fragility** — the software breaks in many places due to a single change.
3. **Immobility** — you cannot reuse parts of the code in other projects because of the risk and effort involved.
4. **Needless complexity**.
5. **Needless repetition**.
6. **Opacity** — the code is hard to understand.
## Credits
Thanks to [@wojtekluwojteklu/clean_code.md](https://gist.github.com/wojteklu/73c6914cc446146b8b533c0988cf8d29)
+1 -1
View File
@@ -5,7 +5,7 @@ RUN bun install --frozen-lockfile
COPY web/ ./ COPY web/ ./
RUN bun run build-only RUN bun run build-only
FROM golang:1.27.1-alpine AS server FROM golang:1.27.3-alpine AS server
ARG VERSION=dev ARG VERSION=dev
ENV CGO_ENABLED=0 ENV CGO_ENABLED=0
WORKDIR /src WORKDIR /src
+14 -12
View File
@@ -1,6 +1,7 @@
package api package api
import ( import (
"RenewCMS/api/pkg/authtoken"
domainAPIKey "RenewCMS/internal/domain/apikey" domainAPIKey "RenewCMS/internal/domain/apikey"
domainArticle "RenewCMS/internal/domain/article" domainArticle "RenewCMS/internal/domain/article"
domainAudit "RenewCMS/internal/domain/audit" domainAudit "RenewCMS/internal/domain/audit"
@@ -12,6 +13,7 @@ import (
domainMail "RenewCMS/internal/domain/mail" domainMail "RenewCMS/internal/domain/mail"
domainPurge "RenewCMS/internal/domain/purge" domainPurge "RenewCMS/internal/domain/purge"
domainSite "RenewCMS/internal/domain/site" domainSite "RenewCMS/internal/domain/site"
domainTransaction "RenewCMS/internal/domain/transaction"
domainUpdate "RenewCMS/internal/domain/update" domainUpdate "RenewCMS/internal/domain/update"
domainUser "RenewCMS/internal/domain/user" domainUser "RenewCMS/internal/domain/user"
"RenewCMS/internal/infrastructure/auditing" "RenewCMS/internal/infrastructure/auditing"
@@ -36,14 +38,12 @@ import (
"runtime" "runtime"
"sync" "sync"
"time" "time"
"github.com/go-chi/jwtauth/v5"
) )
type UseCases struct { type UseCases struct {
apiKeyAuthOnce sync.Once apiKeyAuthOnce sync.Once
apiKeyAuthMiddleware func(http.Handler) http.Handler apiKeyAuthMiddleware func(http.Handler) http.Handler
Token *jwtauth.JWTAuth Token *authtoken.Auth
PurgeScheduler *scheduler.Runner PurgeScheduler *scheduler.Runner
ActivityCleanupScheduler *scheduler.Runner ActivityCleanupScheduler *scheduler.Runner
CreateArticleUseCase *useCases.CreateArticleUseCase CreateArticleUseCase *useCases.CreateArticleUseCase
@@ -160,6 +160,7 @@ type Repositories struct {
AuthorRepo domainAuthor.Repository AuthorRepo domainAuthor.Repository
UserRepo domainUser.Repository UserRepo domainUser.Repository
ImageRepo domainImage.Repository ImageRepo domainImage.Repository
Transactor domainTransaction.Transactor
VariantRepo domainImage.VariantRepository VariantRepo domainImage.VariantRepository
VariantFileRepo domainImage.VariantFileRepository VariantFileRepo domainImage.VariantFileRepository
VariantCacheRepo domainImage.VariantCacheRepository VariantCacheRepo domainImage.VariantCacheRepository
@@ -302,6 +303,7 @@ func getRepositories(connection *database.Connection, settings config.Settings)
AuthorRepo: persistence.NewAuthorRepository(db), AuthorRepo: persistence.NewAuthorRepository(db),
UserRepo: persistence.NewUserRepository(db), UserRepo: persistence.NewUserRepository(db),
ImageRepo: persistence.NewImageRepository(db), ImageRepo: persistence.NewImageRepository(db),
Transactor: persistence.NewTransactor(db),
VariantRepo: persistence.NewVariantRepository(db), VariantRepo: persistence.NewVariantRepository(db),
VariantFileRepo: variantFiles, VariantFileRepo: variantFiles,
VariantCacheRepo: variantFiles, VariantCacheRepo: variantFiles,
@@ -332,7 +334,7 @@ func getUseCases(repos *Repositories, imageStorage domainImage.Storage, settings
renderer := markdown.NewConverter() renderer := markdown.NewConverter()
keyGenerator := hashing.NewSHA256KeyGenerator() keyGenerator := hashing.NewSHA256KeyGenerator()
recorder := auditing.NewRecorder(repos.AuditRepo, time.Now, log.Default()) recorder := auditing.NewRecorder(repos.AuditRepo, time.Now, log.Default())
mergeMedia := useCases.NewMergeMediaUseCase(repos.ImageRepo, repos.ArticleRepo, imageStorage, repos.VariantFileRepo, recorder, repos.SiteRepo, repos.AuthorRepo) mergeMedia := useCases.NewMergeMediaUseCase(repos.ImageRepo, repos.ArticleRepo, imageStorage, repos.VariantFileRepo, recorder, repos.ContentTypeRepo, repos.EntryRepo, repos.Transactor, log.Default())
runPurge := useCases.NewRunPurgeUseCase(repos.ImageRepo, repos.ArticleRepo, mergeMedia, repos.PurgeSettingsRepo, time.Now, log.Default(), recorder, repos.SiteRepo, repos.AuthorRepo) runPurge := useCases.NewRunPurgeUseCase(repos.ImageRepo, repos.ArticleRepo, mergeMedia, repos.PurgeSettingsRepo, time.Now, log.Default(), recorder, repos.SiteRepo, repos.AuthorRepo)
purgeScheduler := useCases.NewPurgeSchedulerUseCase(repos.PurgeSettingsRepo, runPurge, recorder) purgeScheduler := useCases.NewPurgeSchedulerUseCase(repos.PurgeSettingsRepo, runPurge, recorder)
@@ -344,7 +346,7 @@ func getUseCases(repos *Repositories, imageStorage domainImage.Storage, settings
return &UseCases{ return &UseCases{
PurgeScheduler: scheduler.NewSystemRunner(purgeScheduler, log.Default()), PurgeScheduler: scheduler.NewSystemRunner(purgeScheduler, log.Default()),
ActivityCleanupScheduler: scheduler.NewSystemCleanupRunner(activityCleanup, log.Default()), ActivityCleanupScheduler: scheduler.NewSystemCleanupRunner(activityCleanup, log.Default()),
Token: jwtauth.New("HS256", []byte(settings.JWTSecret), nil), Token: authtoken.New([]byte(settings.JWTSecret)),
CreateArticleUseCase: useCases.NewCreateArticleUseCase(repos.ArticleRepo, renderer, recorder, repos.SiteRepo, repos.AuthorRepo), CreateArticleUseCase: useCases.NewCreateArticleUseCase(repos.ArticleRepo, renderer, recorder, repos.SiteRepo, repos.AuthorRepo),
GetArticleUseCase: useCases.NewGetArticleUseCase(repos.ArticleRepo, renderer), GetArticleUseCase: useCases.NewGetArticleUseCase(repos.ArticleRepo, renderer),
ListArticlesUseCase: useCases.NewListArticlesUseCase(repos.ArticleRepo, renderer, repos.SiteRepo), ListArticlesUseCase: useCases.NewListArticlesUseCase(repos.ArticleRepo, renderer, repos.SiteRepo),
@@ -372,10 +374,10 @@ func getUseCases(repos *Repositories, imageStorage domainImage.Storage, settings
ListBuiltinTypesUseCase: useCases.NewListBuiltinTypesUseCase(), ListBuiltinTypesUseCase: useCases.NewListBuiltinTypesUseCase(),
GetBuiltinTypeUseCase: useCases.NewGetBuiltinTypeUseCase(), GetBuiltinTypeUseCase: useCases.NewGetBuiltinTypeUseCase(),
LookupUserNamesUseCase: useCases.NewLookupUserNamesUseCase(repos.UserRepo), LookupUserNamesUseCase: useCases.NewLookupUserNamesUseCase(repos.UserRepo),
CreateEntryUseCase: useCases.NewCreateEntryUseCase(repos.ContentTypeRepo, repos.EntryRepo, time.Now), CreateEntryUseCase: useCases.NewCreateEntryUseCase(repos.ContentTypeRepo, repos.EntryRepo, repos.ImageRepo, time.Now),
GetEntryUseCase: useCases.NewGetEntryUseCase(repos.ContentTypeRepo, repos.EntryRepo), GetEntryUseCase: useCases.NewGetEntryUseCase(repos.ContentTypeRepo, repos.EntryRepo, repos.ImageRepo),
ListEntriesUseCase: useCases.NewListEntriesUseCase(repos.ContentTypeRepo, repos.EntryRepo), ListEntriesUseCase: useCases.NewListEntriesUseCase(repos.ContentTypeRepo, repos.EntryRepo, repos.ImageRepo),
UpdateEntryUseCase: useCases.NewUpdateEntryUseCase(repos.ContentTypeRepo, repos.EntryRepo, time.Now), UpdateEntryUseCase: useCases.NewUpdateEntryUseCase(repos.ContentTypeRepo, repos.EntryRepo, repos.ImageRepo, time.Now),
DeleteEntryUseCase: useCases.NewDeleteEntryUseCase(repos.ContentTypeRepo, repos.EntryRepo), DeleteEntryUseCase: useCases.NewDeleteEntryUseCase(repos.ContentTypeRepo, repos.EntryRepo),
GetUserUseCase: useCases.NewGetUserUseCase(repos.UserRepo), GetUserUseCase: useCases.NewGetUserUseCase(repos.UserRepo),
CreateUserUseCase: useCases.NewCreateUserUseCase(repos.UserRepo, hasher, repos.MailRepo, settings.PublicURL, recorder), CreateUserUseCase: useCases.NewCreateUserUseCase(repos.UserRepo, hasher, repos.MailRepo, settings.PublicURL, recorder),
@@ -395,14 +397,14 @@ func getUseCases(repos *Repositories, imageStorage domainImage.Storage, settings
SendMailUseCase: useCases.NewSendMailUseCase(repos.MailRepo), SendMailUseCase: useCases.NewSendMailUseCase(repos.MailRepo),
CreateImageUseCase: useCases.NewCreateImageUseCase(repos.ImageRepo, imageStorage, recorder), CreateImageUseCase: useCases.NewCreateImageUseCase(repos.ImageRepo, imageStorage, recorder),
OpenMediaUseCase: useCases.NewOpenMediaUseCase(imageStorage), OpenMediaUseCase: useCases.NewOpenMediaUseCase(imageStorage),
ListMediaUseCase: useCases.NewListMediaUseCase(repos.ImageRepo, repos.ArticleRepo, repos.UserRepo, repos.VariantFileRepo, repos.SiteRepo, repos.AuthorRepo), ListMediaUseCase: useCases.NewListMediaUseCase(repos.ImageRepo, repos.ArticleRepo, repos.UserRepo, repos.VariantFileRepo, repos.SiteRepo, repos.AuthorRepo, repos.ContentTypeRepo, repos.EntryRepo),
RenameMediaUseCase: useCases.NewRenameMediaUseCase(repos.ImageRepo, recorder), RenameMediaUseCase: useCases.NewRenameMediaUseCase(repos.ImageRepo, recorder),
DeleteMediaUseCase: useCases.NewDeleteMediaUseCase(repos.ImageRepo, imageStorage, repos.VariantFileRepo, recorder, repos.SiteRepo, repos.AuthorRepo, repos.ArticleRepo), DeleteMediaUseCase: useCases.NewDeleteMediaUseCase(repos.ImageRepo, imageStorage, repos.VariantFileRepo, recorder, repos.SiteRepo, repos.AuthorRepo, repos.ArticleRepo),
MergeMediaUseCase: mergeMedia, MergeMediaUseCase: mergeMedia,
GetMediaUsageUseCase: useCases.NewGetMediaUsageUseCase(repos.ImageRepo, repos.ArticleRepo, repos.SiteRepo, repos.AuthorRepo), GetMediaUsageUseCase: useCases.NewGetMediaUsageUseCase(repos.ImageRepo, repos.ArticleRepo, repos.SiteRepo, repos.AuthorRepo, repos.ContentTypeRepo, repos.EntryRepo),
GetPurgeSettingsUseCase: useCases.NewGetPurgeSettingsUseCase(repos.PurgeSettingsRepo), GetPurgeSettingsUseCase: useCases.NewGetPurgeSettingsUseCase(repos.PurgeSettingsRepo),
UpdatePurgeSettingsUseCase: useCases.NewUpdatePurgeSettingsUseCase(repos.PurgeSettingsRepo, time.Now), UpdatePurgeSettingsUseCase: useCases.NewUpdatePurgeSettingsUseCase(repos.PurgeSettingsRepo, time.Now),
PreviewPurgeUseCase: useCases.NewPreviewPurgeUseCase(repos.ImageRepo, repos.ArticleRepo, repos.SiteRepo, repos.AuthorRepo), PreviewPurgeUseCase: useCases.NewPreviewPurgeUseCase(repos.ImageRepo, repos.ArticleRepo, repos.SiteRepo, repos.AuthorRepo, repos.ContentTypeRepo, repos.EntryRepo),
RunPurgeUseCase: runPurge, RunPurgeUseCase: runPurge,
GetSettingsUseCase: useCases.NewGetSettingsUseCase(settings.Version), GetSettingsUseCase: useCases.NewGetSettingsUseCase(settings.Version),
GetUpdateStatusUseCase: useCases.NewGetUpdateStatusUseCase(repos.UpdateStore, repos.UpdateJobs, repos.UpdateHelper, repos.UpdateResults, repos.RestartRequests, settings.Version, settings.Container, time.Now), GetUpdateStatusUseCase: useCases.NewGetUpdateStatusUseCase(repos.UpdateStore, repos.UpdateJobs, repos.UpdateHelper, repos.UpdateResults, repos.RestartRequests, settings.Version, settings.Container, time.Now),
+3 -4
View File
@@ -2,6 +2,7 @@ package auth
import ( import (
"RenewCMS/api/pkg/apperr" "RenewCMS/api/pkg/apperr"
"RenewCMS/api/pkg/authtoken"
validator "RenewCMS/api/pkg/validator" validator "RenewCMS/api/pkg/validator"
"RenewCMS/internal/domain/invite" "RenewCMS/internal/domain/invite"
"RenewCMS/internal/domain/user" "RenewCMS/internal/domain/user"
@@ -9,12 +10,10 @@ import (
"encoding/json" "encoding/json"
"errors" "errors"
"net/http" "net/http"
"github.com/go-chi/jwtauth/v5"
) )
type AcceptInviteHandler struct { type AcceptInviteHandler struct {
Token *jwtauth.JWTAuth Token *authtoken.Auth
GetInviteUseCase *useCases.GetInviteUseCase GetInviteUseCase *useCases.GetInviteUseCase
AcceptInviteUseCase *useCases.AcceptInviteUseCase AcceptInviteUseCase *useCases.AcceptInviteUseCase
IsProduction bool IsProduction bool
@@ -30,7 +29,7 @@ type inviteEmailResponse struct {
Email string `json:"email"` Email string `json:"email"`
} }
func NewAcceptInviteHandler(getInvite *useCases.GetInviteUseCase, acceptInvite *useCases.AcceptInviteUseCase, token *jwtauth.JWTAuth, isProduction bool) *AcceptInviteHandler { func NewAcceptInviteHandler(getInvite *useCases.GetInviteUseCase, acceptInvite *useCases.AcceptInviteUseCase, token *authtoken.Auth, isProduction bool) *AcceptInviteHandler {
return &AcceptInviteHandler{ return &AcceptInviteHandler{
Token: token, Token: token,
GetInviteUseCase: getInvite, GetInviteUseCase: getInvite,
+6 -7
View File
@@ -2,6 +2,7 @@ package auth
import ( import (
"RenewCMS/api/pkg/apperr" "RenewCMS/api/pkg/apperr"
"RenewCMS/api/pkg/authtoken"
validator "RenewCMS/api/pkg/validator" validator "RenewCMS/api/pkg/validator"
"RenewCMS/internal/domain/user" "RenewCMS/internal/domain/user"
"RenewCMS/internal/infrastructure/useCases" "RenewCMS/internal/infrastructure/useCases"
@@ -9,12 +10,10 @@ import (
"errors" "errors"
"net/http" "net/http"
"time" "time"
"github.com/go-chi/jwtauth/v5"
) )
type LoginHandler struct { type LoginHandler struct {
Token *jwtauth.JWTAuth Token *authtoken.Auth
CreateUseCase *useCases.CreateUserUseCase CreateUseCase *useCases.CreateUserUseCase
AuthenticateUseCase *useCases.AuthenticateUserUseCase AuthenticateUseCase *useCases.AuthenticateUserUseCase
IsProduction bool IsProduction bool
@@ -31,7 +30,7 @@ type LoginCredentials struct {
Password string `json:"password" validate:"required,min=8"` Password string `json:"password" validate:"required,min=8"`
} }
func NewLoginHandler(token *jwtauth.JWTAuth, create *useCases.CreateUserUseCase, authenticate *useCases.AuthenticateUserUseCase, isProduction bool) *LoginHandler { func NewLoginHandler(token *authtoken.Auth, create *useCases.CreateUserUseCase, authenticate *useCases.AuthenticateUserUseCase, isProduction bool) *LoginHandler {
return &LoginHandler{ return &LoginHandler{
Token: token, Token: token,
CreateUseCase: create, CreateUseCase: create,
@@ -52,15 +51,15 @@ func removeJwtCookie(w http.ResponseWriter, isProduction bool) {
}) })
} }
func setJwtCookie(w http.ResponseWriter, token *jwtauth.JWTAuth, isProduction bool, u user.User) error { func setJwtCookie(w http.ResponseWriter, token *authtoken.Auth, isProduction bool, u user.User) error {
_, tokenString, err := token.Encode(map[string]any{"user_id": u.ID, "token_version": u.TokenVersion}) tokenString, err := token.Encode(map[string]any{"user_id": u.ID, "token_version": u.TokenVersion})
if err != nil { if err != nil {
return err return err
} }
http.SetCookie(w, &http.Cookie{ http.SetCookie(w, &http.Cookie{
Name: "jwt", Name: "jwt",
Value: tokenString, Value: tokenString,
Expires: time.Now().Add(24 * time.Hour), Expires: time.Now().Add(authtoken.SessionLifetime),
Secure: isProduction, Secure: isProduction,
HttpOnly: true, HttpOnly: true,
Path: "/", Path: "/",
+28
View File
@@ -42,6 +42,33 @@ type entryResponse struct {
UpdatedBy uint32 `json:"updated_by"` UpdatedBy uint32 `json:"updated_by"`
CreatedAt time.Time `json:"created_at"` CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"` UpdatedAt time.Time `json:"updated_at"`
Media map[string]any `json:"media"`
}
type mediaBody struct {
ID uint32 `json:"id"`
Filename string `json:"filename"`
Width *int `json:"width"`
Height *int `json:"height"`
Size int64 `json:"size"`
ThumbnailURL string `json:"thumbnail_url"`
}
type missingMediaBody struct {
ID uint32 `json:"id"`
Missing bool `json:"missing"`
}
func toMediaResponse(media map[string]useCases.EntryMedia) map[string]any {
body := make(map[string]any, len(media))
for key, item := range media {
if item.Missing {
body[key] = missingMediaBody{ID: item.ID, Missing: true}
continue
}
body[key] = mediaBody{ID: item.ID, Filename: item.Filename, Width: item.Width, Height: item.Height, Size: item.Size, ThumbnailURL: item.ThumbnailURL}
}
return body
} }
func toResponse(typed useCases.TypedEntry) entryResponse { func toResponse(typed useCases.TypedEntry) entryResponse {
@@ -53,6 +80,7 @@ func toResponse(typed useCases.TypedEntry) entryResponse {
UpdatedBy: typed.UpdatedBy, UpdatedBy: typed.UpdatedBy,
CreatedAt: typed.CreatedAt, CreatedAt: typed.CreatedAt,
UpdatedAt: typed.UpdatedAt, UpdatedAt: typed.UpdatedAt,
Media: toMediaResponse(typed.Media),
} }
} }
+20 -2
View File
@@ -92,9 +92,27 @@ func intQueryParam(values url.Values, name string, fallback int) (int, error) {
type usageResponse struct { type usageResponse struct {
Type string `json:"type"` Type string `json:"type"`
ID uint32 `json:"id"` ID uint32 `json:"id"`
Title string `json:"title"` Title string `json:"title,omitempty"`
Published *bool `json:"published,omitempty"` Published *bool `json:"published,omitempty"`
Fields []string `json:"fields"` Fields []string `json:"fields"`
ContentTypeKey string `json:"content_type_key,omitempty"`
ContentTypeName string `json:"content_type_name,omitempty"`
FirstField *usageFirstFieldBody `json:"first_field,omitempty"`
}
type usageFirstFieldBody struct {
Key string `json:"key"`
Type string `json:"type"`
Value any `json:"value"`
}
func toUsageResponse(usage useCases.MediaUsage) usageResponse {
body := usageResponse{Type: usage.Type, ID: usage.ID, Title: usage.Title, Published: usage.Published, Fields: usage.Fields, ContentTypeKey: usage.ContentTypeKey, ContentTypeName: usage.ContentTypeName}
if usage.FirstField != nil {
body.FirstField = &usageFirstFieldBody{Key: usage.FirstField.Key, Type: string(usage.FirstField.Type), Value: usage.FirstField.Value}
}
return body
} }
type mergeResponse struct { type mergeResponse struct {
@@ -347,7 +365,7 @@ func (h *Handler) Usage(w http.ResponseWriter, r *http.Request) {
response := make([]usageResponse, 0, len(usages)) response := make([]usageResponse, 0, len(usages))
for _, usage := range usages { for _, usage := range usages {
response = append(response, usageResponse{Type: usage.Type, ID: usage.ID, Title: usage.Title, Published: usage.Published, Fields: usage.Fields}) response = append(response, toUsageResponse(usage))
} }
writeJSON(w, http.StatusOK, response) writeJSON(w, http.StatusOK, response)
} }
+6 -18
View File
@@ -2,6 +2,7 @@ package middleware
import ( import (
"RenewCMS/api/pkg/apperr" "RenewCMS/api/pkg/apperr"
"RenewCMS/api/pkg/authtoken"
"RenewCMS/internal/domain/apikey" "RenewCMS/internal/domain/apikey"
"RenewCMS/internal/infrastructure/useCases" "RenewCMS/internal/infrastructure/useCases"
"context" "context"
@@ -10,9 +11,6 @@ import (
"strconv" "strconv"
"strings" "strings"
"time" "time"
"github.com/go-chi/jwtauth/v5"
"github.com/lestrrat-go/jwx/v3/jwt"
) )
const bearerScheme = "bearer " const bearerScheme = "bearer "
@@ -79,13 +77,7 @@ func APIKeyAuth(authenticate *useCases.AuthenticateAPIKeyUseCase, maxRequests in
return return
} }
token, err := sessionTokenFor(authenticated) ctx := authtoken.NewContext(r.Context(), sessionClaimsFor(authenticated), nil)
if err != nil {
http.Error(w, "Internal server error", http.StatusInternalServerError)
return
}
ctx := jwtauth.NewContext(r.Context(), token, nil)
ctx = context.WithValue(ctx, apiKeyIdContextKey{}, authenticated.Key.ID) ctx = context.WithValue(ctx, apiKeyIdContextKey{}, authenticated.Key.ID)
ctx = context.WithValue(ctx, apiKeyNameContextKey{}, authenticated.Key.Name) ctx = context.WithValue(ctx, apiKeyNameContextKey{}, authenticated.Key.Name)
limited.ServeHTTP(w, r.WithContext(ctx)) limited.ServeHTTP(w, r.WithContext(ctx))
@@ -101,15 +93,11 @@ func writeAPIKeyError(w http.ResponseWriter, err error) {
http.Error(w, "Internal server error", http.StatusInternalServerError) http.Error(w, "Internal server error", http.StatusInternalServerError)
} }
func sessionTokenFor(authenticated useCases.AuthenticatedAPIKey) (jwt.Token, error) { func sessionClaimsFor(authenticated useCases.AuthenticatedAPIKey) authtoken.Claims {
token := jwt.New() return authtoken.Claims{
if err := token.Set("user_id", float64(authenticated.User.ID)); err != nil { "user_id": float64(authenticated.User.ID),
return nil, err "token_version": float64(authenticated.User.TokenVersion),
} }
if err := token.Set("token_version", float64(authenticated.User.TokenVersion)); err != nil {
return nil, err
}
return token, nil
} }
func apiKeyRateLimitKey(r *http.Request) string { func apiKeyRateLimitKey(r *http.Request) string {
+138
View File
@@ -0,0 +1,138 @@
package middleware
import (
"net/http"
"strconv"
"strings"
)
const (
corsAllowAnyOrigin = "*"
corsWildcardMarker = "*"
corsPreflightMaxAge = 300
corsPreflightSuccess = http.StatusNoContent
)
var (
corsAllowedMethods = []string{http.MethodGet, http.MethodPost, http.MethodPut, http.MethodPatch, http.MethodDelete, http.MethodOptions}
corsAllowedHeaders = []string{"Accept", "Authorization", "Content-Type", "X-CSRF-Token"}
corsExposedHeaders = []string{"Link", "X-Total-Count"}
)
type originWildcard struct {
prefix string
suffix string
}
func (w originWildcard) matches(origin string) bool {
return len(origin) >= len(w.prefix)+len(w.suffix) && strings.HasPrefix(origin, w.prefix) && strings.HasSuffix(origin, w.suffix)
}
type originPolicy struct {
anyOrigin bool
exact map[string]struct{}
wildcards []originWildcard
}
func newOriginPolicy(origins []string) originPolicy {
policy := originPolicy{exact: map[string]struct{}{}}
for _, origin := range origins {
origin = strings.ToLower(strings.TrimSpace(origin))
prefix, suffix, hasWildcard := strings.Cut(origin, corsWildcardMarker)
switch {
case origin == "":
case origin == corsAllowAnyOrigin:
policy.anyOrigin = true
case hasWildcard:
policy.wildcards = append(policy.wildcards, originWildcard{prefix: prefix, suffix: suffix})
default:
policy.exact[origin] = struct{}{}
}
}
return policy
}
func (p originPolicy) allows(origin string) bool {
if p.anyOrigin {
return true
}
origin = strings.ToLower(origin)
if _, ok := p.exact[origin]; ok {
return true
}
for _, wildcard := range p.wildcards {
if wildcard.matches(origin) {
return true
}
}
return false
}
func isPreflight(r *http.Request) bool {
return r.Method == http.MethodOptions && r.Header.Get("Access-Control-Request-Method") != ""
}
func containsFold(allowed []string, value string) bool {
for _, candidate := range allowed {
if strings.EqualFold(candidate, value) {
return true
}
}
return false
}
func requestedHeadersAllowed(r *http.Request) bool {
requested := r.Header.Get("Access-Control-Request-Headers")
if requested == "" {
return true
}
for _, header := range strings.Split(requested, ",") {
if header = strings.TrimSpace(header); header != "" && !containsFold(corsAllowedHeaders, header) {
return false
}
}
return true
}
func CORS(allowedOrigins []string) func(http.Handler) http.Handler {
policy := newOriginPolicy(allowedOrigins)
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
origin := r.Header.Get("Origin")
if origin == "" {
next.ServeHTTP(w, r)
return
}
w.Header().Add("Vary", "Origin")
if isPreflight(r) {
answerPreflight(w, r, origin, policy)
return
}
if policy.allows(origin) {
w.Header().Set("Access-Control-Allow-Origin", origin)
w.Header().Set("Access-Control-Expose-Headers", strings.Join(corsExposedHeaders, ", "))
}
next.ServeHTTP(w, r)
})
}
}
func answerPreflight(w http.ResponseWriter, r *http.Request, origin string, policy originPolicy) {
w.Header().Add("Vary", "Access-Control-Request-Method")
w.Header().Add("Vary", "Access-Control-Request-Headers")
method := r.Header.Get("Access-Control-Request-Method")
if !policy.allows(origin) || !containsFold(corsAllowedMethods, method) || !requestedHeadersAllowed(r) {
w.WriteHeader(http.StatusOK)
return
}
w.Header().Set("Access-Control-Allow-Origin", origin)
w.Header().Set("Access-Control-Allow-Methods", strings.ToUpper(method))
w.Header().Set("Access-Control-Allow-Headers", strings.Join(corsAllowedHeaders, ", "))
w.Header().Set("Access-Control-Max-Age", strconv.Itoa(corsPreflightMaxAge))
w.WriteHeader(corsPreflightSuccess)
}
+2 -5
View File
@@ -2,16 +2,13 @@ package middleware
import ( import (
"RenewCMS/api/pkg/apperr" "RenewCMS/api/pkg/apperr"
"RenewCMS/api/pkg/authtoken"
"net/http" "net/http"
"github.com/go-chi/jwtauth/v5"
"github.com/lestrrat-go/jwx/v3/jwt"
) )
func RequireSignedIn(next http.Handler) http.Handler { func RequireSignedIn(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
token, _, err := jwtauth.FromContext(r.Context()) if _, err := authtoken.FromContext(r.Context()); err != nil {
if err != nil || token == nil || jwt.Validate(token) != nil {
http.Error(w, apperr.UnauthorizedErrorMessage, http.StatusUnauthorized) http.Error(w, apperr.UnauthorizedErrorMessage, http.StatusUnauthorized)
return return
} }
+170
View File
@@ -0,0 +1,170 @@
package authtoken
import (
"crypto/hmac"
"crypto/sha256"
"encoding/base64"
"encoding/json"
"errors"
"maps"
"strings"
"time"
)
const (
SessionLifetime = 24 * time.Hour
algorithmHS256 = "HS256"
tokenType = "JWT"
maxTokenBytes = 4096
segmentCount = 3
segmentSep = "."
)
var (
ErrNoToken = errors.New("no token found")
ErrInvalid = errors.New("token is invalid")
ErrExpired = errors.New("token is expired")
ErrNotYetValid = errors.New("token is not yet valid")
)
type Claims map[string]any
type header struct {
Algorithm string `json:"alg"`
Type string `json:"typ,omitempty"`
}
type Auth struct {
secret []byte
clock func() time.Time
}
type Option func(*Auth)
func WithClock(clock func() time.Time) Option {
return func(a *Auth) { a.clock = clock }
}
func New(secret []byte, options ...Option) *Auth {
auth := &Auth{secret: secret, clock: time.Now}
for _, option := range options {
option(auth)
}
return auth
}
func (a *Auth) Encode(claims map[string]any) (string, error) {
payload := maps.Clone(claims)
if payload == nil {
payload = map[string]any{}
}
now := a.clock()
if _, ok := payload["iat"]; !ok {
payload["iat"] = now.Unix()
}
if _, ok := payload["exp"]; !ok {
payload["exp"] = now.Add(SessionLifetime).Unix()
}
headerSegment, err := encodeSegment(header{Algorithm: algorithmHS256, Type: tokenType})
if err != nil {
return "", err
}
payloadSegment, err := encodeSegment(payload)
if err != nil {
return "", err
}
signingInput := headerSegment + segmentSep + payloadSegment
return signingInput + segmentSep + a.sign(signingInput), nil
}
func (a *Auth) Decode(token string) (Claims, error) {
if token == "" {
return nil, ErrNoToken
}
if len(token) > maxTokenBytes {
return nil, ErrInvalid
}
segments := strings.Split(token, segmentSep)
if len(segments) != segmentCount {
return nil, ErrInvalid
}
var tokenHeader header
if err := decodeSegment(segments[0], &tokenHeader); err != nil || tokenHeader.Algorithm != algorithmHS256 {
return nil, ErrInvalid
}
signingInput := segments[0] + segmentSep + segments[1]
if !hmac.Equal([]byte(a.sign(signingInput)), []byte(segments[2])) {
return nil, ErrInvalid
}
var claims Claims
if err := decodeSegment(segments[1], &claims); err != nil || claims == nil {
return nil, ErrInvalid
}
if err := a.validateTimes(claims); err != nil {
return nil, err
}
return claims, nil
}
func (a *Auth) validateTimes(claims Claims) error {
now := a.clock()
expiry, present, err := numericDate(claims, "exp")
if err != nil {
return err
}
if present && !now.Before(expiry) {
return ErrExpired
}
notBefore, present, err := numericDate(claims, "nbf")
if err != nil {
return err
}
if present && now.Before(notBefore) {
return ErrNotYetValid
}
return nil
}
func numericDate(claims Claims, name string) (time.Time, bool, error) {
raw, present := claims[name]
if !present {
return time.Time{}, false, nil
}
seconds, ok := raw.(float64)
if !ok {
return time.Time{}, false, ErrInvalid
}
return time.Unix(int64(seconds), 0), true, nil
}
func (a *Auth) sign(signingInput string) string {
mac := hmac.New(sha256.New, a.secret)
mac.Write([]byte(signingInput))
return base64.RawURLEncoding.EncodeToString(mac.Sum(nil))
}
func encodeSegment(value any) (string, error) {
encoded, err := json.Marshal(value)
if err != nil {
return "", err
}
return base64.RawURLEncoding.EncodeToString(encoded), nil
}
func decodeSegment(segment string, into any) error {
decoded, err := base64.RawURLEncoding.DecodeString(segment)
if err != nil {
return err
}
return json.Unmarshal(decoded, into)
}
+79
View File
@@ -0,0 +1,79 @@
package authtoken
import (
"RenewCMS/api/pkg/apperr"
"context"
"net/http"
"strings"
)
const (
cookieName = "jwt"
bearerPrefix = "bearer "
)
type contextKey struct{}
type verdict struct {
claims Claims
err error
}
func Verifier(auth *Auth) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
claims, err := auth.Decode(tokenFromRequest(r))
next.ServeHTTP(w, r.WithContext(NewContext(r.Context(), claims, err)))
})
}
}
func Authenticator(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if _, err := FromContext(r.Context()); err != nil {
http.Error(w, apperr.UnauthorizedErrorMessage, http.StatusUnauthorized)
return
}
next.ServeHTTP(w, r)
})
}
func NewContext(ctx context.Context, claims Claims, err error) context.Context {
return context.WithValue(ctx, contextKey{}, verdict{claims: claims, err: err})
}
func FromContext(ctx context.Context) (Claims, error) {
stored, ok := ctx.Value(contextKey{}).(verdict)
switch {
case !ok:
return nil, ErrNoToken
case stored.err != nil:
return nil, stored.err
case stored.claims == nil:
return nil, ErrNoToken
}
return stored.claims, nil
}
func tokenFromRequest(r *http.Request) string {
if token := tokenFromHeader(r); token != "" {
return token
}
return tokenFromCookie(r)
}
func tokenFromHeader(r *http.Request) string {
header := r.Header.Get("Authorization")
if len(header) <= len(bearerPrefix) || !strings.EqualFold(header[:len(bearerPrefix)], bearerPrefix) {
return ""
}
return header[len(bearerPrefix):]
}
func tokenFromCookie(r *http.Request) string {
cookie, err := r.Cookie(cookieName)
if err != nil {
return ""
}
return cookie.Value
}
+3 -4
View File
@@ -1,14 +1,13 @@
package claims package claims
import ( import (
"RenewCMS/api/pkg/authtoken"
"math" "math"
"net/http" "net/http"
"github.com/go-chi/jwtauth/v5"
) )
func UserId(r *http.Request) (uint32, bool) { func UserId(r *http.Request) (uint32, bool) {
_, claims, err := jwtauth.FromContext(r.Context()) claims, err := authtoken.FromContext(r.Context())
if err != nil { if err != nil {
return 0, false return 0, false
} }
@@ -31,7 +30,7 @@ func UserId(r *http.Request) (uint32, bool) {
} }
func TokenVersion(r *http.Request) (uint32, bool) { func TokenVersion(r *http.Request) (uint32, bool) {
_, claims, err := jwtauth.FromContext(r.Context()) claims, err := authtoken.FromContext(r.Context())
if err != nil { if err != nil {
return 0, false return 0, false
} }
+42 -47
View File
@@ -18,21 +18,23 @@ import (
"RenewCMS/api/handlers/update" "RenewCMS/api/handlers/update"
"RenewCMS/api/handlers/user" "RenewCMS/api/handlers/user"
"RenewCMS/api/middleware" "RenewCMS/api/middleware"
"RenewCMS/api/pkg/authtoken"
"RenewCMS/internal/infrastructure/config" "RenewCMS/internal/infrastructure/config"
"encoding/json" "encoding/json"
"log"
"net/http" "net/http"
"os"
"time" "time"
"github.com/MadAppGang/httplog"
"github.com/go-chi/chi/v5" "github.com/go-chi/chi/v5"
chimiddleware "github.com/go-chi/chi/v5/middleware" chimiddleware "github.com/go-chi/chi/v5/middleware"
"github.com/go-chi/cors"
"github.com/go-chi/jwtauth/v5"
) )
func enableLoggingIfDev(r *chi.Mux, routerName string, environment string) { func enableLoggingIfDev(r *chi.Mux, routerName string, environment string) {
if environment == "development" { if environment == "development" {
r.Use(httplog.LoggerWithName(routerName)) r.Use(chimiddleware.RequestLogger(&chimiddleware.DefaultLogFormatter{
Logger: log.New(os.Stdout, "["+routerName+"] ", log.LstdFlags),
}))
} }
} }
@@ -68,7 +70,7 @@ func NewArticleRouter(container *UseCases, trustedProxies []string) http.Handler
r.Get("/{id}/seo", seoHandler.Resolve) r.Get("/{id}/seo", seoHandler.Resolve)
}) })
r.Group(func(r chi.Router) { r.Group(func(r chi.Router) {
r.Use(jwtauth.Authenticator(container.Token)) r.Use(authtoken.Authenticator)
r.Use(middleware.RequireCurrentToken(container.GetUserUseCase)) r.Use(middleware.RequireCurrentToken(container.GetUserUseCase))
r.Use(middleware.RequireVerifiedUser(container.GetUserUseCase)) r.Use(middleware.RequireVerifiedUser(container.GetUserUseCase))
r.Post("/", articleHandler.PostArticle) r.Post("/", articleHandler.PostArticle)
@@ -83,7 +85,7 @@ func NewArticleRouter(container *UseCases, trustedProxies []string) http.Handler
func NewAuthRouter(container *UseCases, isProduction bool, rateLimit config.AuthRateLimitSettings, trustedProxies []string) http.Handler { func NewAuthRouter(container *UseCases, isProduction bool, rateLimit config.AuthRateLimitSettings, trustedProxies []string) http.Handler {
r := chi.NewRouter() r := chi.NewRouter()
r.Use(jwtauth.Verifier(container.Token)) r.Use(authtoken.Verifier(container.Token))
r.Use(middleware.AuditContext(container.GetUserUseCase, trustedProxies)) r.Use(middleware.AuditContext(container.GetUserUseCase, trustedProxies))
loginHandler := auth.NewLoginHandler(container.Token, container.CreateUserUseCase, container.AuthenticateUserUseCase, isProduction) loginHandler := auth.NewLoginHandler(container.Token, container.CreateUserUseCase, container.AuthenticateUserUseCase, isProduction)
@@ -114,16 +116,16 @@ func NewAuthRouter(container *UseCases, isProduction bool, rateLimit config.Auth
}) })
r.Group(func(r chi.Router) { r.Group(func(r chi.Router) {
r.Use(middleware.RequireSession) r.Use(middleware.RequireSession)
r.Use(jwtauth.Verifier(container.Token)) r.Use(authtoken.Verifier(container.Token))
r.Use(jwtauth.Authenticator(container.Token)) r.Use(authtoken.Authenticator)
r.Use(middleware.RequireCurrentToken(container.GetUserUseCase)) r.Use(middleware.RequireCurrentToken(container.GetUserUseCase))
r.Post("/verify", verificationHandler.Verify) r.Post("/verify", verificationHandler.Verify)
r.Delete("/register", verificationHandler.CancelRegistration) r.Delete("/register", verificationHandler.CancelRegistration)
}) })
r.Group(func(r chi.Router) { r.Group(func(r chi.Router) {
r.Use(jwtauth.Verifier(container.Token)) r.Use(authtoken.Verifier(container.Token))
r.Use(container.apiKeyAuth()) r.Use(container.apiKeyAuth())
r.Use(jwtauth.Authenticator(container.Token)) r.Use(authtoken.Authenticator)
r.Use(middleware.RequireCurrentToken(container.GetUserUseCase)) r.Use(middleware.RequireCurrentToken(container.GetUserUseCase))
r.Get("/me", meHandler.Me) r.Get("/me", meHandler.Me)
}) })
@@ -137,10 +139,10 @@ func NewUserRouter(container *UseCases, rateLimit config.AuthRateLimitSettings,
lookupHandler := user.NewLookupHandler(container.LookupUserNamesUseCase) lookupHandler := user.NewLookupHandler(container.LookupUserNamesUseCase)
inviteHandler := user.NewInviteHandler(container.CreateInviteUseCase, container.CancelInviteUseCase, container.RenewInviteUseCase, container.ListUsersAndInvitesUseCase) inviteHandler := user.NewInviteHandler(container.CreateInviteUseCase, container.CancelInviteUseCase, container.RenewInviteUseCase, container.ListUsersAndInvitesUseCase)
r.Use(jwtauth.Verifier(container.Token)) r.Use(authtoken.Verifier(container.Token))
r.Use(container.apiKeyAuth()) r.Use(container.apiKeyAuth())
r.Use(middleware.AuditContext(container.GetUserUseCase, trustedProxies)) r.Use(middleware.AuditContext(container.GetUserUseCase, trustedProxies))
r.Use(jwtauth.Authenticator(container.Token)) r.Use(authtoken.Authenticator)
r.Use(middleware.RequireCurrentToken(container.GetUserUseCase)) r.Use(middleware.RequireCurrentToken(container.GetUserUseCase))
r.Use(middleware.RequireVerifiedUser(container.GetUserUseCase)) r.Use(middleware.RequireVerifiedUser(container.GetUserUseCase))
r.Patch("/me", userHandler.UpdateMe) r.Patch("/me", userHandler.UpdateMe)
@@ -163,19 +165,19 @@ func NewSettingsRouter(container *UseCases, trustedProxies []string) http.Handle
settingsHandler := settings.NewHandler(container.GetSettingsUseCase, container.GetActivityRetentionUseCase, container.UpdateActivityRetentionUseCase) settingsHandler := settings.NewHandler(container.GetSettingsUseCase, container.GetActivityRetentionUseCase, container.UpdateActivityRetentionUseCase)
r.Group(func(r chi.Router) { r.Group(func(r chi.Router) {
r.Use(jwtauth.Verifier(container.Token)) r.Use(authtoken.Verifier(container.Token))
r.Use(container.apiKeyAuth()) r.Use(container.apiKeyAuth())
r.Use(jwtauth.Authenticator(container.Token)) r.Use(authtoken.Authenticator)
r.Use(middleware.RequireCurrentToken(container.GetUserUseCase)) r.Use(middleware.RequireCurrentToken(container.GetUserUseCase))
r.Use(middleware.RequireVerifiedUser(container.GetUserUseCase)) r.Use(middleware.RequireVerifiedUser(container.GetUserUseCase))
r.Get("/", settingsHandler.GetSettings) r.Get("/", settingsHandler.GetSettings)
}) })
r.Group(func(r chi.Router) { r.Group(func(r chi.Router) {
r.Use(middleware.RequireSession) r.Use(middleware.RequireSession)
r.Use(jwtauth.Verifier(container.Token)) r.Use(authtoken.Verifier(container.Token))
r.Use(middleware.AuditContext(container.GetUserUseCase, trustedProxies)) r.Use(middleware.AuditContext(container.GetUserUseCase, trustedProxies))
r.Use(middleware.RequireSignedIn) r.Use(middleware.RequireSignedIn)
r.Use(jwtauth.Authenticator(container.Token)) r.Use(authtoken.Authenticator)
r.Use(middleware.RequireCurrentToken(container.GetUserUseCase)) r.Use(middleware.RequireCurrentToken(container.GetUserUseCase))
r.Use(middleware.RequireVerifiedUser(container.GetUserUseCase)) r.Use(middleware.RequireVerifiedUser(container.GetUserUseCase))
r.Use(middleware.RequireOwner(container.GetUserUseCase)) r.Use(middleware.RequireOwner(container.GetUserUseCase))
@@ -193,19 +195,19 @@ func NewSiteRouter(container *UseCases, trustedProxies []string) http.Handler {
r.Get("/{key}/sitemap", sitemapHandler.Sitemap) r.Get("/{key}/sitemap", sitemapHandler.Sitemap)
r.Group(func(r chi.Router) { r.Group(func(r chi.Router) {
r.Use(jwtauth.Verifier(container.Token)) r.Use(authtoken.Verifier(container.Token))
r.Use(container.apiKeyAuth()) r.Use(container.apiKeyAuth())
r.Use(jwtauth.Authenticator(container.Token)) r.Use(authtoken.Authenticator)
r.Use(middleware.RequireCurrentToken(container.GetUserUseCase)) r.Use(middleware.RequireCurrentToken(container.GetUserUseCase))
r.Use(middleware.RequireVerifiedUser(container.GetUserUseCase)) r.Use(middleware.RequireVerifiedUser(container.GetUserUseCase))
r.Get("/", siteHandler.List) r.Get("/", siteHandler.List)
}) })
r.Group(func(r chi.Router) { r.Group(func(r chi.Router) {
r.Use(middleware.RequireSession) r.Use(middleware.RequireSession)
r.Use(jwtauth.Verifier(container.Token)) r.Use(authtoken.Verifier(container.Token))
r.Use(middleware.AuditContext(container.GetUserUseCase, trustedProxies)) r.Use(middleware.AuditContext(container.GetUserUseCase, trustedProxies))
r.Use(middleware.RequireSignedIn) r.Use(middleware.RequireSignedIn)
r.Use(jwtauth.Authenticator(container.Token)) r.Use(authtoken.Authenticator)
r.Use(middleware.RequireCurrentToken(container.GetUserUseCase)) r.Use(middleware.RequireCurrentToken(container.GetUserUseCase))
r.Use(middleware.RequireVerifiedUser(container.GetUserUseCase)) r.Use(middleware.RequireVerifiedUser(container.GetUserUseCase))
r.Use(middleware.RequireOwner(container.GetUserUseCase)) r.Use(middleware.RequireOwner(container.GetUserUseCase))
@@ -223,19 +225,19 @@ func NewAuthorRouter(container *UseCases, trustedProxies []string) http.Handler
authorHandler := author.NewHandler(container.ListAuthorsUseCase, container.CreateAuthorUseCase, container.CreateMyAuthorUseCase, container.UpdateAuthorUseCase, container.DeleteAuthorUseCase, container.GetUserUseCase) authorHandler := author.NewHandler(container.ListAuthorsUseCase, container.CreateAuthorUseCase, container.CreateMyAuthorUseCase, container.UpdateAuthorUseCase, container.DeleteAuthorUseCase, container.GetUserUseCase)
r.Group(func(r chi.Router) { r.Group(func(r chi.Router) {
r.Use(jwtauth.Verifier(container.Token)) r.Use(authtoken.Verifier(container.Token))
r.Use(container.apiKeyAuth()) r.Use(container.apiKeyAuth())
r.Use(jwtauth.Authenticator(container.Token)) r.Use(authtoken.Authenticator)
r.Use(middleware.RequireCurrentToken(container.GetUserUseCase)) r.Use(middleware.RequireCurrentToken(container.GetUserUseCase))
r.Use(middleware.RequireVerifiedUser(container.GetUserUseCase)) r.Use(middleware.RequireVerifiedUser(container.GetUserUseCase))
r.Get("/", authorHandler.List) r.Get("/", authorHandler.List)
}) })
r.Group(func(r chi.Router) { r.Group(func(r chi.Router) {
r.Use(middleware.RequireSession) r.Use(middleware.RequireSession)
r.Use(jwtauth.Verifier(container.Token)) r.Use(authtoken.Verifier(container.Token))
r.Use(middleware.AuditContext(container.GetUserUseCase, trustedProxies)) r.Use(middleware.AuditContext(container.GetUserUseCase, trustedProxies))
r.Use(middleware.RequireSignedIn) r.Use(middleware.RequireSignedIn)
r.Use(jwtauth.Authenticator(container.Token)) r.Use(authtoken.Authenticator)
r.Use(middleware.RequireCurrentToken(container.GetUserUseCase)) r.Use(middleware.RequireCurrentToken(container.GetUserUseCase))
r.Use(middleware.RequireVerifiedUser(container.GetUserUseCase)) r.Use(middleware.RequireVerifiedUser(container.GetUserUseCase))
r.Post("/me", authorHandler.CreateMine) r.Post("/me", authorHandler.CreateMine)
@@ -256,11 +258,11 @@ func NewContentTypeRouter(container *UseCases, trustedProxies []string) http.Han
entryHandler := entry.NewHandler(container.CreateEntryUseCase, container.GetEntryUseCase, container.ListEntriesUseCase, container.UpdateEntryUseCase, container.DeleteEntryUseCase) entryHandler := entry.NewHandler(container.CreateEntryUseCase, container.GetEntryUseCase, container.ListEntriesUseCase, container.UpdateEntryUseCase, container.DeleteEntryUseCase)
r.Use(jwtauth.Verifier(container.Token)) r.Use(authtoken.Verifier(container.Token))
r.Use(container.apiKeyAuth()) r.Use(container.apiKeyAuth())
r.Use(middleware.AuditContext(container.GetUserUseCase, trustedProxies)) r.Use(middleware.AuditContext(container.GetUserUseCase, trustedProxies))
r.Use(middleware.RequireSignedIn) r.Use(middleware.RequireSignedIn)
r.Use(jwtauth.Authenticator(container.Token)) r.Use(authtoken.Authenticator)
r.Use(middleware.RequireCurrentToken(container.GetUserUseCase)) r.Use(middleware.RequireCurrentToken(container.GetUserUseCase))
r.Use(middleware.RequireVerifiedUser(container.GetUserUseCase)) r.Use(middleware.RequireVerifiedUser(container.GetUserUseCase))
r.Get("/", contentTypeHandler.List) r.Get("/", contentTypeHandler.List)
@@ -284,11 +286,11 @@ func NewBuiltinTypeRouter(container *UseCases, trustedProxies []string) http.Han
builtinTypeHandler := builtintype.NewHandler(container.ListBuiltinTypesUseCase, container.GetBuiltinTypeUseCase) builtinTypeHandler := builtintype.NewHandler(container.ListBuiltinTypesUseCase, container.GetBuiltinTypeUseCase)
r.Use(jwtauth.Verifier(container.Token)) r.Use(authtoken.Verifier(container.Token))
r.Use(container.apiKeyAuth()) r.Use(container.apiKeyAuth())
r.Use(middleware.AuditContext(container.GetUserUseCase, trustedProxies)) r.Use(middleware.AuditContext(container.GetUserUseCase, trustedProxies))
r.Use(middleware.RequireSignedIn) r.Use(middleware.RequireSignedIn)
r.Use(jwtauth.Authenticator(container.Token)) r.Use(authtoken.Authenticator)
r.Use(middleware.RequireCurrentToken(container.GetUserUseCase)) r.Use(middleware.RequireCurrentToken(container.GetUserUseCase))
r.Use(middleware.RequireVerifiedUser(container.GetUserUseCase)) r.Use(middleware.RequireVerifiedUser(container.GetUserUseCase))
r.Use(middleware.RequireOwnerOrAdmin(container.GetUserUseCase)) r.Use(middleware.RequireOwnerOrAdmin(container.GetUserUseCase))
@@ -303,10 +305,10 @@ func NewActivityRouter(container *UseCases, trustedProxies []string) http.Handle
activityHandler := activity.NewHandler(container.ListActivityUseCase, container.GetActivitySummaryUseCase, container.ExportActivityUseCase) activityHandler := activity.NewHandler(container.ListActivityUseCase, container.GetActivitySummaryUseCase, container.ExportActivityUseCase)
r.Use(middleware.RequireSession) r.Use(middleware.RequireSession)
r.Use(jwtauth.Verifier(container.Token)) r.Use(authtoken.Verifier(container.Token))
r.Use(middleware.AuditContext(container.GetUserUseCase, trustedProxies)) r.Use(middleware.AuditContext(container.GetUserUseCase, trustedProxies))
r.Use(middleware.RequireSignedIn) r.Use(middleware.RequireSignedIn)
r.Use(jwtauth.Authenticator(container.Token)) r.Use(authtoken.Authenticator)
r.Use(middleware.RequireCurrentToken(container.GetUserUseCase)) r.Use(middleware.RequireCurrentToken(container.GetUserUseCase))
r.Use(middleware.RequireVerifiedUser(container.GetUserUseCase)) r.Use(middleware.RequireVerifiedUser(container.GetUserUseCase))
r.Get("/", activityHandler.List) r.Get("/", activityHandler.List)
@@ -331,9 +333,9 @@ func NewSystemRouter(container *UseCases, trustedProxies []string) http.Handler
updateHandler := update.NewHandler(container.GetUpdateStatusUseCase, container.CheckForUpdateUseCase, container.StartUpdateDownloadUseCase, container.RequestRestartUseCase, container.GetUserUseCase) updateHandler := update.NewHandler(container.GetUpdateStatusUseCase, container.CheckForUpdateUseCase, container.StartUpdateDownloadUseCase, container.RequestRestartUseCase, container.GetUserUseCase)
r.Use(middleware.RequireSession) r.Use(middleware.RequireSession)
r.Use(jwtauth.Verifier(container.Token)) r.Use(authtoken.Verifier(container.Token))
r.Use(middleware.AuditContext(container.GetUserUseCase, trustedProxies)) r.Use(middleware.AuditContext(container.GetUserUseCase, trustedProxies))
r.Use(jwtauth.Authenticator(container.Token)) r.Use(authtoken.Authenticator)
r.Use(middleware.RequireCurrentToken(container.GetUserUseCase)) r.Use(middleware.RequireCurrentToken(container.GetUserUseCase))
r.Use(middleware.RequireVerifiedUser(container.GetUserUseCase)) r.Use(middleware.RequireVerifiedUser(container.GetUserUseCase))
r.Get("/update", updateHandler.GetStatus) r.Get("/update", updateHandler.GetStatus)
@@ -360,9 +362,9 @@ func NewAPIKeyRouter(container *UseCases, trustedProxies []string) http.Handler
apiKeyHandler := apikey.NewHandler(container.CreateAPIKeyUseCase, container.ListAPIKeysUseCase, container.RevokeAPIKeyUseCase) apiKeyHandler := apikey.NewHandler(container.CreateAPIKeyUseCase, container.ListAPIKeysUseCase, container.RevokeAPIKeyUseCase)
r.Use(middleware.RequireSession) r.Use(middleware.RequireSession)
r.Use(jwtauth.Verifier(container.Token)) r.Use(authtoken.Verifier(container.Token))
r.Use(middleware.AuditContext(container.GetUserUseCase, trustedProxies)) r.Use(middleware.AuditContext(container.GetUserUseCase, trustedProxies))
r.Use(jwtauth.Authenticator(container.Token)) r.Use(authtoken.Authenticator)
r.Use(middleware.RequireCurrentToken(container.GetUserUseCase)) r.Use(middleware.RequireCurrentToken(container.GetUserUseCase))
r.Use(middleware.RequireVerifiedUser(container.GetUserUseCase)) r.Use(middleware.RequireVerifiedUser(container.GetUserUseCase))
r.Post("/", apiKeyHandler.Create) r.Post("/", apiKeyHandler.Create)
@@ -376,11 +378,11 @@ func NewMediaRouter(container *UseCases, trustedProxies []string) http.Handler {
mediaHandler := media.NewHandler(container.CreateImageUseCase, container.ListMediaUseCase, container.RenameMediaUseCase, container.DeleteMediaUseCase, container.MergeMediaUseCase, container.GetMediaUsageUseCase, container.GetPurgeSettingsUseCase, container.UpdatePurgeSettingsUseCase, container.PreviewPurgeUseCase, container.RunPurgeUseCase, container.ListImageVariantsUseCase, container.GenerateImageVariantUseCase, container.GenerateAllImageVariantsUseCase, container.PurgeImageVariantUseCase, container.GenerateVariantsOnUploadUseCase) mediaHandler := media.NewHandler(container.CreateImageUseCase, container.ListMediaUseCase, container.RenameMediaUseCase, container.DeleteMediaUseCase, container.MergeMediaUseCase, container.GetMediaUsageUseCase, container.GetPurgeSettingsUseCase, container.UpdatePurgeSettingsUseCase, container.PreviewPurgeUseCase, container.RunPurgeUseCase, container.ListImageVariantsUseCase, container.GenerateImageVariantUseCase, container.GenerateAllImageVariantsUseCase, container.PurgeImageVariantUseCase, container.GenerateVariantsOnUploadUseCase)
r.Use(jwtauth.Verifier(container.Token)) r.Use(authtoken.Verifier(container.Token))
r.Use(container.apiKeyAuth()) r.Use(container.apiKeyAuth())
r.Use(middleware.AuditContext(container.GetUserUseCase, trustedProxies)) r.Use(middleware.AuditContext(container.GetUserUseCase, trustedProxies))
r.Use(middleware.RequireSignedIn) r.Use(middleware.RequireSignedIn)
r.Use(jwtauth.Authenticator(container.Token)) r.Use(authtoken.Authenticator)
r.Use(middleware.RequireCurrentToken(container.GetUserUseCase)) r.Use(middleware.RequireCurrentToken(container.GetUserUseCase))
r.Use(middleware.RequireVerifiedUser(container.GetUserUseCase)) r.Use(middleware.RequireVerifiedUser(container.GetUserUseCase))
r.Group(func(r chi.Router) { r.Group(func(r chi.Router) {
@@ -413,10 +415,10 @@ func NewImageVariantRouter(container *UseCases, trustedProxies []string) http.Ha
variantHandler := imagevariant.NewHandler(container.ListVariantsUseCase, container.CreateVariantUseCase, container.UpdateVariantUseCase, container.SetVariantEnabledUseCase, container.DeleteVariantUseCase, container.PurgeVariantUseCase, container.GetVariantCacheStatsUseCase, container.PurgeVariantCacheUseCase) variantHandler := imagevariant.NewHandler(container.ListVariantsUseCase, container.CreateVariantUseCase, container.UpdateVariantUseCase, container.SetVariantEnabledUseCase, container.DeleteVariantUseCase, container.PurgeVariantUseCase, container.GetVariantCacheStatsUseCase, container.PurgeVariantCacheUseCase)
r.Use(jwtauth.Verifier(container.Token)) r.Use(authtoken.Verifier(container.Token))
r.Use(middleware.AuditContext(container.GetUserUseCase, trustedProxies)) r.Use(middleware.AuditContext(container.GetUserUseCase, trustedProxies))
r.Use(middleware.RequireSignedIn) r.Use(middleware.RequireSignedIn)
r.Use(jwtauth.Authenticator(container.Token)) r.Use(authtoken.Authenticator)
r.Use(middleware.RequireCurrentToken(container.GetUserUseCase)) r.Use(middleware.RequireCurrentToken(container.GetUserUseCase))
r.Use(middleware.RequireVerifiedUser(container.GetUserUseCase)) r.Use(middleware.RequireVerifiedUser(container.GetUserUseCase))
r.Use(middleware.RequireOwnerOrAdmin(container.GetUserUseCase)) r.Use(middleware.RequireOwnerOrAdmin(container.GetUserUseCase))
@@ -440,7 +442,7 @@ func InitBackendRoutes(container *UseCases, settings config.Settings) *chi.Mux {
r.Use(middleware.JsonContentTypeMiddleware) r.Use(middleware.JsonContentTypeMiddleware)
r.Get("/", GetHelloWorld) r.Get("/", GetHelloWorld)
r.Group(func(r chi.Router) { r.Group(func(r chi.Router) {
r.Use(jwtauth.Verifier(container.Token)) r.Use(authtoken.Verifier(container.Token))
r.Mount("/article", NewArticleRouter(container, settings.TrustedProxies)) r.Mount("/article", NewArticleRouter(container, settings.TrustedProxies))
}) })
r.Mount("/user", NewUserRouter(container, settings.AuthRateLimit, settings.TrustedProxies)) r.Mount("/user", NewUserRouter(container, settings.AuthRateLimit, settings.TrustedProxies))
@@ -478,14 +480,7 @@ func enableCorsIfConfigured(r *chi.Mux, origins []string) {
if len(origins) == 0 { if len(origins) == 0 {
return return
} }
r.Use(cors.Handler(cors.Options{ r.Use(middleware.CORS(origins))
AllowedOrigins: origins,
AllowedMethods: []string{"GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"},
AllowedHeaders: []string{"Accept", "Authorization", "Content-Type", "X-CSRF-Token"},
ExposedHeaders: []string{"Link", "X-Total-Count"},
AllowCredentials: false,
MaxAge: 300,
}))
} }
func InitRoutes(container *UseCases, settings config.Settings) *chi.Mux { func InitRoutes(container *UseCases, settings config.Settings) *chi.Mux {
+6 -3
View File
@@ -7,6 +7,7 @@ import (
"context" "context"
"errors" "errors"
"fmt" "fmt"
"io/fs"
"log" "log"
"net" "net"
"net/http" "net/http"
@@ -15,8 +16,6 @@ import (
"slices" "slices"
"syscall" "syscall"
"time" "time"
"github.com/joho/godotenv"
) )
var version = "dev" var version = "dev"
@@ -106,9 +105,13 @@ func initEnvVariables() {
func loadEnvFile() { func loadEnvFile() {
for _, envLocation := range possibleEnvFileLocations { for _, envLocation := range possibleEnvFileLocations {
if godotenv.Load(envLocation) == nil { err := config.LoadDotenv(envLocation)
if err == nil {
return return
} }
if !errors.Is(err, fs.ErrNotExist) {
log.Println("WARNING: Could not parse env file:", err)
}
} }
log.Println("WARNING: Could not load any .env file") log.Println("WARNING: Could not load any .env file")
} }
+1 -1
View File
@@ -95,7 +95,7 @@ Media usage has more sources than article bodies: `Article.CoverImageID` and `So
`internal/domain/image` holds the `Variant` entity and its rules (`VariantSettings.Normalized`, the settings `Fingerprint`, `VariantETag`, `ETagMatches`, `IsAnimatedGIF`), the sentinels (`ErrVariantNotFound`, `ErrVariantExists`, `ErrVariantInvalid`, `ErrVariantFormatUnavailable`, `ErrUnknownVariant`, `ErrUnsupportedParameter`, `ErrSourceTooLarge`) and three ports: `VariantRepository` (definitions), `VariantFileRepository` (the index of generated files: variant name, source stored name, cached stored name, content type, size and the settings fingerprint, needed because `Storage.Put` chooses the stored name itself) and `VariantRenderer` (decode a source, encode a variant, report the formats it can encode). `internal/infrastructure/imaging` is the renderer adapter, free of GORM and HTTP; the persistence adapters are `VariantRepository` and `VariantFileRepository` over `models.ImageVariant` and `models.ImageVariantFile`. `internal/domain/image` holds the `Variant` entity and its rules (`VariantSettings.Normalized`, the settings `Fingerprint`, `VariantETag`, `ETagMatches`, `IsAnimatedGIF`), the sentinels (`ErrVariantNotFound`, `ErrVariantExists`, `ErrVariantInvalid`, `ErrVariantFormatUnavailable`, `ErrUnknownVariant`, `ErrUnsupportedParameter`, `ErrSourceTooLarge`) and three ports: `VariantRepository` (definitions), `VariantFileRepository` (the index of generated files: variant name, source stored name, cached stored name, content type, size and the settings fingerprint, needed because `Storage.Put` chooses the stored name itself) and `VariantRenderer` (decode a source, encode a variant, report the formats it can encode). `internal/infrastructure/imaging` is the renderer adapter, free of GORM and HTTP; the persistence adapters are `VariantRepository` and `VariantFileRepository` over `models.ImageVariant` and `models.ImageVariantFile`.
Generated bytes are stored only through `image.Storage`, so they follow `STORAGE_DRIVER`, and are never rows of `images`. `ServeVariantUseCase` checks, in order: unsupported parameters, the variant (it must exist and be enabled), the source blob, SVG and animated GIF (served as they are), the size cap, the `If-None-Match` ETag, then the cached file, and generates under a `singleflight` keyed by variant, settings and source. A row whose fingerprint no longer matches, or whose blob vanished, is replaced. `UpdateVariantUseCase` purges a variant's files when a rendering setting changes; `DeleteVariantUseCase` and `PurgeVariantUseCase` purge a blob and then its row, so a failed blob delete keeps the row and a retry can finish; `mediaRemover` purges the files of a source before it deletes the source (delete and merge). Generated bytes are stored only through `image.Storage`, so they follow `STORAGE_DRIVER`, and are never rows of `images`. `ServeVariantUseCase` checks, in order: unsupported parameters, the variant (it must exist and be enabled), the source blob, SVG and animated GIF (served as they are), the size cap, the `If-None-Match` ETag, then the cached file, and generates under an in-process single-flight group keyed by variant, settings and source. A row whose fingerprint no longer matches, or whose blob vanished, is replaced. `UpdateVariantUseCase` purges a variant's files when a rendering setting changes; `DeleteVariantUseCase` and `PurgeVariantUseCase` purge a blob and then its row, so a failed blob delete keeps the row and a retry can finish; `mediaRemover` purges the files of a source before it deletes the source (delete and merge).
The cache screen adds three ports in `internal/domain/image`: `VariantCacheRepository` (unused totals, top sources by bytes and cursor-paged row listing, implemented by the same persistence type as `VariantFileRepository`), `VariantUsageRepository` (one batched write of request times and per-day rejection counts, and the rejection total of a window) and `VariantUsageTracker` (in-memory hits and rejections). `internal/infrastructure/usage.Tracker` implements the tracker; `GetVariantCacheStatsUseCase` and `PurgeVariantCacheUseCase` use the ports only. See [image-variants.md](image-variants.md). The cache screen adds three ports in `internal/domain/image`: `VariantCacheRepository` (unused totals, top sources by bytes and cursor-paged row listing, implemented by the same persistence type as `VariantFileRepository`), `VariantUsageRepository` (one batched write of request times and per-day rejection counts, and the rejection total of a window) and `VariantUsageTracker` (in-memory hits and rejections). `internal/infrastructure/usage.Tracker` implements the tracker; `GetVariantCacheStatsUseCase` and `PurgeVariantCacheUseCase` use the ports only. See [image-variants.md](image-variants.md).
-108
View File
@@ -1,108 +0,0 @@
# 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.
+2 -2
View File
@@ -1,6 +1,6 @@
# Configuration # Configuration
RenewCMS reads its configuration from environment variables. On startup it also loads a `.env` file from the working directory (or its parent) if one exists. Real environment variables take precedence over `.env`. RenewCMS reads its configuration from environment variables. On startup it also loads a `.env` file from the working directory (or its parent) if one exists. Real environment variables take precedence over `.env`. The parser reads `NAME=value` lines, an optional `export ` prefix, `#` comments (inline ones need a space before the `#`), and single- or double-quoted values (`\n`, `\t`, `\"` and `\\` are unescaped in double quotes). It does not expand `$VARIABLES` and does not support multi-line values. A malformed line makes the whole file ignored, and the server logs the line number.
Copy [`.env.example`](../.env.example) to `.env` to get started. When a required variable is missing, the server refuses to start and names the variable. Copy [`.env.example`](../.env.example) to `.env` to get started. When a required variable is missing, the server refuses to start and names the variable.
@@ -29,7 +29,7 @@ Copy [`.env.example`](../.env.example) to `.env` to get started. When a required
| `DATA_DIR` | directory of `DB_FILE` | Directory for update state, staged updates and database backups (`backups/`). Set it with `DB_DRIVER=mysql` or `postgres`, where there is no database file to sit beside (the default still follows `DB_FILE`). With SQLite, leave it unset to keep everything beside the database. | | `DATA_DIR` | directory of `DB_FILE` | Directory for update state, staged updates and database backups (`backups/`). Set it with `DB_DRIVER=mysql` or `postgres`, where there is no database file to sit beside (the default still follows `DB_FILE`). With SQLite, leave it unset to keep everything beside the database. |
| `STORAGE_DRIVER` | `local` | `local` (files in `UPLOAD_DIR`) or `s3` (an S3-compatible bucket). Any other value stops the server with `unsupported storage driver "<value>"`. See [Image storage](#image-storage). | | `STORAGE_DRIVER` | `local` | `local` (files in `UPLOAD_DIR`) or `s3` (an S3-compatible bucket). Any other value stops the server with `unsupported storage driver "<value>"`. See [Image storage](#image-storage). |
| `UPLOAD_DIR` | `./data/uploads` | Directory where uploaded images are stored. Ignored, without error, when `STORAGE_DRIVER=s3`. | | `UPLOAD_DIR` | `./data/uploads` | Directory where uploaded images are stored. Ignored, without error, when `STORAGE_DRIVER=s3`. |
| `CORS_ALLOWED_ORIGINS` | *(empty)* | Semicolon-separated list of origins allowed to call the API. When empty, no CORS headers are sent. That is the right setting whenever the SPA is served by RenewCMS itself (production) or through the Vite proxy (development). | | `CORS_ALLOWED_ORIGINS` | *(empty)* | Semicolon-separated list of origins allowed to call the API. Matching is case-insensitive. An entry may contain one `*` (`https://*.preview.example.com`), and a lone `*` allows every origin. Credentials are never allowed cross-origin. When empty, no CORS headers are sent. That is the right setting whenever the SPA is served by RenewCMS itself (production) or through the Vite proxy (development). |
| `AUTH_RATE_LIMIT_MAX_ATTEMPTS` | `5` | Maximum number of requests a single client IP may send to `POST /v1/auth/login`, `POST /v1/auth/password-reset` or the invite-accept pair (`GET /v1/auth/invite` and `POST /v1/auth/invite/accept`, sharing one counter) within the window, tracked independently per route. | | `AUTH_RATE_LIMIT_MAX_ATTEMPTS` | `5` | Maximum number of requests a single client IP may send to `POST /v1/auth/login`, `POST /v1/auth/password-reset` or the invite-accept pair (`GET /v1/auth/invite` and `POST /v1/auth/invite/accept`, sharing one counter) within the window, tracked independently per route. |
| `AUTH_RATE_LIMIT_WINDOW_SECONDS` | `60` | Length, in seconds, of the fixed rate-limit window for the routes above. | | `AUTH_RATE_LIMIT_WINDOW_SECONDS` | `60` | Length, in seconds, of the fixed rate-limit window for the routes above. |
| `TRUSTED_PROXIES` | *(empty)* | Semicolon-separated list of exact IP addresses (no CIDR) of reverse proxies allowed to supply the client IP via `X-Real-IP` for the rate limiting of the routes above. When a request's connection address is not in this list, any `X-Real-IP` or `X-Forwarded-For` header it sends is ignored and the connection address is used instead. See [deployment.md](deployment.md). | | `TRUSTED_PROXIES` | *(empty)* | Semicolon-separated list of exact IP addresses (no CIDR) of reverse proxies allowed to supply the client IP via `X-Real-IP` for the rate limiting of the routes above. When a request's connection address is not in this list, any `X-Real-IP` or `X-Forwarded-For` header it sends is ignored and the connection address is used instead. See [deployment.md](deployment.md). |
+1 -1
View File
@@ -21,7 +21,7 @@ Back-office board groups: Sites, Sites: form, Sites: delete, Authors, Authors: f
- Role-restricted variants drawn: read-only Authors list and detail, hidden Sites entry, Sites 403, own-author edit. - Role-restricted variants drawn: read-only Authors list and detail, hidden Sites entry, Sites 403, own-author edit.
## Pass 4: custom content types ## 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. Board `RenewCMS Screens Schema.dc.html` (frames: `SchemaFrame`, mounted in `AppFrame`): 11 groups, 97 states. 1 Schema list 7, 2 Schema builder 19, 3 Review and delete 9, 4 Field types 7, 5 Content and entry list 12, 6 Entry editor 23, 7 Relations 3, 8 Permissions 2, 9 Export and import 3, 10 Media picker for a field 8, 11 Media library usage 4. The Media field type (pass 5) is specified in `media-field-changes.md`; the exact copy and measurements are there, and the boards are the visual reference. 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, media.md, media-picker.md, and media-field-changes.md for the Media field type.
- AppFrame gains a Schema item (owner and admin) and a Content group (sidebar and mobile drawer). Nothing else in AppFrame changed. - 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. - 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). - Not done: Back-office and Prototype boards were not compared visually after the sidebar change (see Checks below).
+10
View File
@@ -121,3 +121,13 @@ Frames: `SchemaFrame.dc.html` (all schema, content and entry bodies; relation, p
| RelationField (later) | New | UInputMenu multiple | Chips and search | | RelationField (later) | New | UInputMenu multiple | Chips and search |
| PermissionsGrid (later) | New | UTable + UCheckbox; UCard list on mobile | | | PermissionsGrid (later) | New | UTable + UCheckbox; UCard list on mobile | |
| SchemaImportDialog (later) | New | UModal + UFileUpload | | | SchemaImportDialog (later) | New | UModal + UFileUpload | |
## Media field (pass 5)
Frames: `SchemaFrame.dc.html` (`MCtl`) and `MediaFrame.dc.html` (picker in field mode, usage). Full spec: `media-field-changes.md`.
| Component | Status | Nuxt UI | Notes |
|---|---|---|---|
| MediaFieldControl | New | UFormField, UButton outline and ghost, UModal (desktop) or bottom UDrawer (mobile) for the picker, UTooltip, UIcon (image, image-off, unlink, image-plus). The thumbnail is a plain button | Props label, required, modelValue (image id or null), image (filename, width, height, size, or missing), disabled, error. Emits update:modelValue. States: empty, filled, hover, focus, error, missing, saving, read-only |
| FieldCell (media) | Extended | Thumbnail 40 px square, dash when empty, dashed square with unlink when the image is gone | Row height 48 px, mobile card thumbnail 32 px |
| MediaPicker (field mode) | Extended | Existing picker | Title "Choose an image", "Use this image", no alt text, no variant select, "Current" badge, optional "No image" row |
+121
View File
@@ -0,0 +1,121 @@
# Media field type: change list for implementation
Board: `RenewCMS Screens Schema.dc.html`. Frames changed: `SchemaFrame.dc.html`, `MediaFrame.dc.html`. Spec data: `schema-spec.js` (states) and `media-field-tables.js` (tables, appended to the board). No new tokens, no new colors, radius 0.
## 1. Behaviour
- New field type `media`, name "Media", icon `lucide:image`, description "One image from your media library".
- Stored value: id of a library image, or null. The file is never copied. The field always shows the current library image.
- Options: label, key, required. No default, unique, min, max or choices. The inspector hides them.
- Required: the entry can't be saved while the field is empty (422 invalid_entry, rule required).
- A saved field's type never changes. Key and type are locked after the first save (existing rule).
- Adding a required media field to a type with entries is refused, because a media field can't have a default. The review step shows this before the server is asked.
- Image deleted while entries point at it: the entry keeps the id. The control shows the missing state. Saving is refused only if the field is required.
- Entries count as uses of an image in Media. Deleting a used image is allowed after a warning.
- Variants: the editor preview uses the original. No variant select in the field. Nothing about variants in the builder.
- Galleries (several images) are out of scope and not drawn.
## 2. New component: MediaFieldControl
Props: label, required, modelValue (image id or null), image (filename, width, height, size, or `missing: true`), disabled, error. Emits `update:modelValue`. Opens the picker.
Nuxt UI v4: `UFormField` (label, help, error, required), `UButton` outline ("Pick an image", "Change image", "Choose another image"), `UButton` ghost ("Remove", "Clear"), `UModal` on desktop and bottom `UDrawer` on mobile for the picker, `UTooltip` for the list placeholder and the badge, `UIcon` lucide:image, image-off, unlink, image-plus. The thumbnail is a plain `button`.
States and measurements (SchemaFrame `MCtl`):
| State | Drawing |
|---|---|
| Empty | Dashed box (1px dashed `--ui-border-accented`), padding 12, 40 px icon square (`--ui-bg-elevated`), "No image selected.", button "Pick an image" (icon image-plus). Mobile: stacked, 44 px button |
| Filled | Solid 1px `--ui-border-accented` box, padding 12. Thumbnail 160 × 120 (mobile: full width, 16:9). Filename weight 500, then "1600 × 900 · 240 KB" 12/18 muted. Buttons "Change image" (outline, icon image) and "Remove" (ghost, icon x). Help line "One image from your library." |
| Hover (desktop) | Border `--ui-text-muted`. Bottom bar 28 px, `--ui-bg-inverted` with `--ui-text-inverted`, icon image 14 and "Change image". No hover on mobile |
| Focus | 2 px `--ui-primary` outline, offset 2, on the thumbnail button |
| Error | Box border `--ui-error` plus inset 1px `--ui-error`, error line with circle-alert 14: "Pick an image for Thumbnail." Focus ring on the first button (Pick an image, or Choose another image) |
| Missing | Dashed 160 × 120 (mobile 16:9) placeholder with image-off 24. Text "This image is no longer in the library" (weight 500). Help: optional "You can still save. The entry keeps the link until you change it." / required "Thumbnail is required. Choose another image to save." Buttons "Choose another image" (outline) and "Clear" (ghost) |
| Saving | Thumbnail at 60%, buttons at 40%, all form fields disabled, Save reads "Saving…" |
| Read-only (fields changed) | Same as saving, plus warning alert "The fields of Events changed" and button "Reload form" |
Label is the field label, plus " *" when required (existing form rule; "(optional)" is not used).
## 3. Per screen
### 3.1 Schema list (group 1), state "Custom type: read-only view"
Fields table of a custom type (Label, Key, Type, Rules) in the built-in table style. Thumbnail row: image icon, key `thumbnail`, type "Media", rules "One image from the library". Header "Events" with badge "Read only" (lock). Alert: "You can read these fields here" / "Only an owner or admin can change a content type." The built-in Media type in Schema is unchanged. Decision needed: no route shows a custom type read-only today.
### 3.2 Schema builder (group 2), 3 states
- "Media field selected": saved Thumbnail row selected (index 7). Inspector: Label, Key (locked, "Used in the API, so it can't change."), Type tiles (seven, Media selected, others dimmed with "Can't change after saving"), Required switch ("Required" / "An entry can't be saved with this field empty."). Hidden for media: Unique values, Default value, limits, choices. Hint (info-soft block, info icon): "Holds one image from the media library. Entries link to the image instead of keeping a copy, so they always show its current version."
- "New media field, seven types": new row with "New" badge, key editable ("The name used in the API. Starts with a letter. Lowercase letters, digits and underscores."), type tiles all enabled. State chip "Unsaved changes".
- "Media field, required": row shows the existing Required marker.
- Field row: grip, 28 px icon square (image), label, key (mono), badges. Mobile: inspector in the existing 92% sheet (title "Field: Thumbnail", footer "Done").
- Type tile grid now has seven tiles (3 columns desktop inspector, 2 in sheets).
### 3.3 Review (group 3), 2 states
Dialog "Review changes to Events" / "Apply them to save the content type." Summary "Add 1 field" / "Events has 12 entries. Each one is checked against the new fields when you apply." The info bar in the builder behind reads "12 entries use this content type…".
- Refused: row "Add Thumbnail", warning flag "Can't be applied", text "Media, required. A media field can't have a default, so the 12 existing entries would have no image. Make Thumbnail optional to add it." Note "Back to editing keeps your other changes." Buttons "Back to editing", "Apply changes" (disabled). This departs from the existing review (Apply is never disabled): decision.
- Clean: row "Add Thumbnail", "Media, optional. 12 entries are unaffected." Apply enabled.
### 3.4 Field types (group 4), state "Media"
Per-type frame like the others: header icon image, "Media", "One image from your media library", `type: "media"`. Columns: inspector options, entry form control (filled with hover, then empty), list cell (Filled thumbnail, Empty "–", Image missing), errors by rule, filter (later).
Errors by rule: required 422 "Pick an image for Thumbnail."; type 422 "Thumbnail must be an image from the library."; min, max, options, unique: "Not used for media." Filter widget: "Thumbnail: has an image" with Any / Has an image / No image, tagged Later.
### 3.5 Entry list (group 5), 3 states
Columns shown: Title, Thumbnail, Starts on, Category (user choice). Header "Thumbnail", no sort icon, column 80 px. Cell: 40 px square thumbnail; "–" when empty; dashed 40 px square with unlink icon, accessible name "Image no longer in the library", when the image is gone. Row height stays 48 px (thumbnail fits with 4 px above and below). Mobile card: 32 px thumbnail leads the card (empty: "–", missing: dashed square), card min height 68 px. Columns menu lists Thumbnail with the image icon ("4 of 6", "Choose up to 6 fields to show. 4 selected." on mobile). Tooltip on the missing placeholder (desktop): "Image no longer in the library".
### 3.6 Entry editor (group 6), 10 states
Control sits after Description, at the end of the form (schema order; see conflicts). States: empty optional, empty required, filled, hover, focus, validation error (status chip "Not saved"), image no longer in the library, missing + required (error), saving, read-only. The board scrolls the form so the control is visible in the frame; the real form is not scrolled.
### 3.7 Picker (group 10), 8 states, MediaFrame field mode
Existing picker (Upload and Library tabs, single selection, search "Search by filename", "Newest first · 48 images", Load more, 4 columns desktop and 3 on mobile, square tiles). Differences:
- Title "Choose an image".
- Primary "Use this image" (disabled until a tile is chosen). When "No image" is chosen it reads "Remove image".
- No alt text field, no variant select. Selected strip shows thumbnail, filename, "dimensions · size".
- Current image tile badge "Current" (replaces "In this article").
- Optional fields only: row "No image" / "Leave this field empty." at the top of the Library tab. Selected: sand fill, primary border, check.
- Empty: "Your library is empty" / "Images you upload appear here, ready to use in any article or entry." / "Upload an image".
- Failed: "Couldn't load your library" / "Check your connection and try again." / "Try again".
- Loading: skeleton tiles after 150 ms.
- Upload tab: unchanged flow (crop, resize); the new image lands in the library and is selected.
- Desktop dialog 640 wide, mobile bottom sheet.
### 3.8 Media library (group 11), 4 states
- Badge "Used in N" = articles + entries. The tooltip (hover or focus) reads "Used in entries: 3" and, if articles also use it, "Used in articles: 2" on the first line. Example: bathroom-tiles.png, 3 entries, "Used in 3".
- List view: same badge in the list row and mobile card.
- Detail panel (lime-plaster.jpg, 2 articles, 5 entries): preview is shorter when the image has entries; existing "Used in 2 articles" list; new section "Used in entries" with up to 3 rows (type name muted, entry title as link, arrow-up-right) and "and 2 more". When there are entries the empty-articles line reads "No article shows it." (not "safe to delete").
- Delete: title "Delete an image that's in use?" (existing in-use dialog), body `"lime-plaster.jpg" is used in 5 entries and 2 articles. Those entry fields will show "This image is no longer in the library", and the articles will show a broken image. This can't be undone.` with the entries and articles lists; "Cancel" and destructive "Delete image".
## 4. Copy added (exact)
Media · One image from your media library · Holds one image from the media library. Entries link to the image instead of keeping a copy, so they always show its current version. · No image selected. · Pick an image · Change image · Remove · Choose another image · Clear · One image from your library. · This image is no longer in the library · You can still save. The entry keeps the link until you change it. · Thumbnail is required. Choose another image to save. · Pick an image for Thumbnail. · Thumbnail must be an image from the library. · Not used for media. · Image no longer in the library · Choose an image · Use this image · Remove image · Current · No image · Leave this field empty. · Used in entries · and 2 more · Used in entries: 3 · Can't be applied · Media, required. A media field can't have a default, so the 12 existing entries would have no image. Make Thumbnail optional to add it. · Media, optional. 12 entries are unaffected. · The Thumbnail field was changed after you opened this form. Reload the form to continue. What you typed here can't be saved against the old fields.
Sentence case, "image" never "asset", buttons are verbs.
## 5. API and backend
- Schema API accepts type `media` with label, key, required. Value: image id or null.
- 422 invalid_entry: required → "Pick an image for Thumbnail."; type (id not in the library on a changed value) → "Thumbnail must be an image from the library."
- Entry and list responses include, per media field, filename, width, height, size and a thumbnail URL, or `missing: true`.
- GET /v1/media/{id}/usage returns articles and entries (content type name, key, entry id, title), a total and the first few items. GET /v1/media/ list items carry the combined use count.
- DELETE /v1/media/{id} stays allowed for used images. Entries keep the id.
- A new required media field on a type with entries is refused (schema_incompatible). The client shows the refusal first.
HTTP to copy (picker and field), from states.md: 400 "That request wasn't valid. Check the fields and try again."; 401/403 global; 404 "That item no longer exists."; 409 "This changed somewhere else. Reload and try again."; 413 "That file is too large."; 429 "Too many requests. Try again in a few minutes."; 500/network "Something went wrong on our side. Nothing was changed. Try again in a moment."
## 6. Accessibility
- Control is `role="group"` labelled by the field label. Required: `aria-required` on the main button.
- Names: "Pick an image for Thumbnail"; thumbnail "Change image, lime-plaster-workshop.jpg, 1600 by 900, 240 KB"; "Remove image from Thumbnail"; "Clear Thumbnail"; missing placeholder `role="img"` "Image no longer in the library".
- Error: error text has an id. The main button gets `aria-invalid="true"` and `aria-describedby` (error id, then help id). Focus moves to the first invalid control on a refused save.
- Order: label, thumbnail, Change image, Remove, help or error. The thumbnail duplicates Change image; use `tabindex="-1"` on it if one stop is preferred.
- One polite live region: "Image selected: lime-plaster-workshop.jpg", "Image removed from Thumbnail.", "Thumbnail cleared."
- Focus: Use this image → Change image. Remove or Clear → Pick an image. Cancel or Esc → the opener.
- Picker: tiles are buttons with `aria-pressed`, names "stone-steps.jpg, 310 KB, Current". "No image" has `aria-pressed`. "Use this image" uses `aria-disabled`.
- Contrast: Current badge and selected rows use `--rc-on-sand`; hover bar 18.9 (inverted pair). 44 px targets on mobile. No hover on mobile.
## 7. Conflicts to decide
1. Row height: design is 48 px (56 px media rows, 68 px cards), not 32 px. Drawn at 48 and 68.
2. Thumbnail position: existing form has Description last. Drawn after Description (end of form).
3. "Used in N" counted articles. Now articles + entries.
4. Delete title: existing in-use title kept; "Delete this image?" stays for unused images.
5. "Clear" vs glossary "Remove".
6. "1600 × 900 · 240 KB" (design separator) instead of "1600 x 900 - 240 KB".
7. Review step disables Apply for the certain refusal; existing review never does.
8. Picker button "Use this image" vs article picker "Insert image"; "Remove image" when No image is chosen is my addition.
9. "Pick an image" also on optional empty fields.
10. No read-only route for custom types.
11. Two tab stops for the same picker (thumbnail and Change image).
12. Disabled opacity: form 60%, foundations 40%.
13. The picker frame shows a stand-in entry form, not the real editor.
## 8. Not done
README.md, states.md and the screens/*.md files are not updated with the new counts (group 2 +3, 3 +2, 4 +1, 5 +3, 6 +10, 1 +1, new groups 10 (8) and 11 (4): 32 states). Light/dark and mobile frames were checked by reading the DOM, not state by state on screen.
+3
View File
@@ -21,3 +21,6 @@ The sidebar gets a "Content" group, one item per custom type (a default icon: ty
| 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 | | 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 | | 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 | | 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 |
## Media field (pass 5)
Spec, states, exact copy, measurements, backend needs and accessibility: `media-field-changes.md`, section 3.5. Board groups: 5 Content and entry list.
+3
View File
@@ -25,3 +25,6 @@ The form is generated from the schema, one control per field in schema order. Re
| 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 | | 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 | | 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 | | 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 |
## Media field (pass 5)
Spec, states, exact copy, measurements, backend needs and accessibility: `media-field-changes.md`, section 3.6. Board groups: 6 Entry editor.
+3
View File
@@ -45,3 +45,6 @@ The Library tab of the picker gets a Variant select. Options are Original plus t
| 3 | No variants defined | Only Original is offered. | "Articles" / "How we price a bathroom renovation" / "Edit article" | | 3 | No variants defined | Only Original is offered. | "Articles" / "How we price a bathroom renovation" / "Edit article" |
| 4 | Variant deleted | The block keeps its URL. Pick another variant opens the select. | "Articles" / "How we price a bathroom renovation" / "Edit article" / "Variant 'hero' no longer exists." | | 4 | Variant deleted | The block keeps its URL. Pick another variant opens the select. | "Articles" / "How we price a bathroom renovation" / "Edit article" / "Variant 'hero' no longer exists." |
| 5 | Variant disabled | Same block, different cause. Proposed copy. | "Articles" / "How we price a bathroom renovation" / "Edit article" / "Variant 'hero' is disabled." | | 5 | Variant disabled | Same block, different cause. Proposed copy. | "Articles" / "How we price a bathroom renovation" / "Edit article" / "Variant 'hero' is disabled." |
## Media field (pass 5)
Spec, states, exact copy, measurements, backend needs and accessibility: `media-field-changes.md`, section 3.7. Board groups: 10 Media picker for a field.
+3
View File
@@ -113,3 +113,6 @@ A secondary "Purge duplicates" button (icon merge) in the toolbar next to the so
|---|---|---|---| |---|---|---|---|
| 1 | Duplicates tab with the button | Owner or admin. | | | 1 | Duplicates tab with the button | Owner or admin. | |
| 2 | Duplicates tab: offline | The button is disabled with the existing banner. | | | 2 | Duplicates tab: offline | The button is disabled with the existing banner. | |
## Media field (pass 5)
Spec, states, exact copy, measurements, backend needs and accessibility: `media-field-changes.md`, section 3.8. Board groups: 11 Media library usage.
+3
View File
@@ -76,3 +76,6 @@ One frame per type: inspector options, the entry form control (default and open
| 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 | | 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 | | 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 | | 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 |
## Media field (pass 5)
Spec, states, exact copy, measurements, backend needs and accessibility: `media-field-changes.md`, section 3.1 to 3.4. Board groups: 1 Schema list, 2 Schema builder, 3 Review, 4 Field types.
+20 -13
View File
@@ -53,6 +53,8 @@ class Component extends DCLogic {
] ]
const VC = { 1: 4, 2: 5, 3: 5, 4: 0, 5: 3, 6: 0, 7: 2, 8: 0, 9: 1, 10: 3, 11: 4, 12: 5 } const VC = { 1: 4, 2: 5, 3: 5, 4: 0, 5: 3, 6: 0, 7: 2, 8: 0, 9: 1, 10: 3, 11: 4, 12: 5 }
IM.forEach(x => { x.vc = VC[x.id] || 0 }) IM.forEach(x => { x.vc = VC[x.id] || 0 })
const ENT = { 10: 3, 11: 5 }
IM.forEach(x => { x.ent = s.ent ? (ENT[x.id] || 0) : 0 })
const byId = id => IM.find(x => x.id === id) const byId = id => IM.find(x => x.id === id)
const AR = [['How we price a bathroom renovation', 1], ['Winter checklist for timber windows', 0], ['Before and after: the Rue Verte kitchen', 1], ['Why we reuse original floorboards', 1], ['Choosing lime plaster for old stone walls', 0]] const AR = [['How we price a bathroom renovation', 1], ['Winter checklist for timber windows', 0], ['Before and after: the Rue Verte kitchen', 1], ['Why we reuse original floorboards', 1], ['Choosing lime plaster for old stone walls', 0]]
const usedList = n => AR.slice(0, Math.min(n, 5)) const usedList = n => AR.slice(0, Math.min(n, 5))
@@ -60,8 +62,8 @@ class Component extends DCLogic {
const imgs = ids.map(byId) const imgs = ids.map(byId)
const sel = s.sel || [] const sel = s.sel || []
const pl = n => n + (n === 1 ? ' article' : ' articles') const pl = n => n + (n === 1 ? ' article' : ' articles')
const label = im => im.n + ', ' + im.sz + ', ' + (im.used ? 'used in ' + pl(im.used) : 'unused') const label = im => im.n + ', ' + im.sz + ', ' + (im.used + im.ent ? 'used in ' + [im.used && pl(im.used), im.ent && (im.ent + (im.ent === 1 ? ' entry' : ' entries'))].filter(Boolean).join(' and ') : 'unused')
const usedBadge = im => im.used ? Bd('Used in ' + im.used, 'used') : Bd('Unused', 'unused') const usedBadge = im => { const n = im.used + im.ent, b = n ? Bd('Used in ' + n, 'used') : Bd('Unused', 'unused'); return s.tip === im.id ? S('position:relative;display:inline-flex', b, D('position:absolute;left:0;top:26px;z-index:10;padding:6px 8px;background:var(--ui-bg-inverted);color:var(--ui-text-inverted);font-size:12px;line-height:18px;white-space:nowrap;box-shadow:var(--rc-shadow-pop)', im.used > 0 && D('', 'Used in articles: ' + im.used), D('', 'Used in entries: ' + im.ent))) : b }
// ---------- Media page pieces // ---------- Media page pieces
const Card = im => { const Card = im => {
@@ -196,6 +198,8 @@ class Component extends DCLogic {
const BulkBar = () => D('position:absolute;z-index:30;bottom:' + (m ? 16 : 24) + 'px;' + (m ? 'left:16px;right:16px' : 'left:calc(224px + (100% - 224px) / 2);transform:translateX(-50%);width:400px') + ';display:flex;align-items:center;gap:8px;padding:8px 8px 8px 16px;background:var(--ui-bg-inverted);color:var(--ui-text-inverted);box-shadow:var(--rc-shadow-pop)', S('flex:1;font-weight:500', sel.length + ' selected'), B('Delete', { k: 'danger', icon: 'trash-2' }), B('Clear', { k: 'inv' })) const BulkBar = () => D('position:absolute;z-index:30;bottom:' + (m ? 16 : 24) + 'px;' + (m ? 'left:16px;right:16px' : 'left:calc(224px + (100% - 224px) / 2);transform:translateX(-50%);width:400px') + ';display:flex;align-items:center;gap:8px;padding:8px 8px 8px 16px;background:var(--ui-bg-inverted);color:var(--ui-text-inverted);box-shadow:var(--rc-shadow-pop)', S('flex:1;font-weight:500', sel.length + ' selected'), B('Delete', { k: 'danger', icon: 'trash-2' }), B('Clear', { k: 'inv' }))
// ---------- detail panel // ---------- detail panel
const ENTL = [['Events', 'Lime plaster workshop'], ['Events', 'Heritage stone walk'], ['Events', 'Winter open day']]
const EntBox = im => D('display:flex;flex-direction:column;gap:8px', S('font:600 14px/22px \'IBM Plex Sans\',sans-serif;color:var(--ui-text-highlighted)', 'Used in entries'), D('border:1px solid var(--ui-border)', ...ENTL.map(([ty, tt], i) => D('display:flex;align-items:center;gap:8px;min-height:' + (m ? 48 : 36) + 'px;padding:0 12px;border-top:' + (i ? '1px solid var(--ui-border-muted)' : '0'), S('width:52px;flex-shrink:0;font-size:12px;color:var(--ui-text-muted)', ty), S('flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-weight:500;text-decoration:underline;text-underline-offset:3px;color:var(--ui-text-highlighted)', tt), I('arrow-up-right', 14, 'color:var(--ui-text-muted)'))), im.ent > 3 && D('padding:8px 12px;border-top:1px solid var(--ui-border-muted);color:var(--ui-text-muted)', 'and ' + (im.ent - 3) + ' more')))
const Panel = () => { const Panel = () => {
const im = byId(s.panel.id), list = usedList(im.used) const im = byId(s.panel.id), list = usedList(im.used)
const meta = [['Type', im.ty], ['Size', im.sz], ['Dimensions', im.dim], ['Uploaded', im.d], ['Uploaded by', im.by]] const meta = [['Type', im.ty], ['Size', im.sz], ['Dimensions', im.dim], ['Uploaded', im.d], ['Uploaded by', im.by]]
@@ -204,14 +208,14 @@ class Component extends DCLogic {
D('width:' + w + ';height:100%;background:var(--ui-bg);display:flex;flex-direction:column;' + (m ? '' : 'box-shadow:var(--rc-shadow-modal)'), D('width:' + w + ';height:100%;background:var(--ui-bg);display:flex;flex-direction:column;' + (m ? '' : 'box-shadow:var(--rc-shadow-modal)'),
D('height:' + (m ? 56 : 56) + 'px;flex-shrink:0;display:flex;align-items:center;gap:' + (m ? 4 : 12) + 'px;padding:0 ' + (m ? 6 : 20) + 'px;border-bottom:1px solid var(--ui-border)', m && S('width:44px;height:44px;display:flex;align-items:center;justify-content:center', I('arrow-left', 20)), 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', im.n), !m && S('width:28px;height:28px;display:flex;align-items:center;justify-content:center;color:var(--ui-text-muted)', I('x'))), D('height:' + (m ? 56 : 56) + 'px;flex-shrink:0;display:flex;align-items:center;gap:' + (m ? 4 : 12) + 'px;padding:0 ' + (m ? 6 : 20) + 'px;border-bottom:1px solid var(--ui-border)', m && S('width:44px;height:44px;display:flex;align-items:center;justify-content:center', I('arrow-left', 20)), 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', im.n), !m && S('width:28px;height:28px;display:flex;align-items:center;justify-content:center;color:var(--ui-text-muted)', I('x'))),
D('flex:1;min-height:0;overflow:hidden;padding:' + (m ? 16 : 20) + 'px;display:flex;flex-direction:column;gap:20px', D('flex:1;min-height:0;overflow:hidden;padding:' + (m ? 16 : 20) + 'px;display:flex;flex-direction:column;gap:20px',
Th(im, 'aspect-ratio:' + (m ? '4/3' : '16/10') + ';border:1px solid var(--ui-border);flex-shrink:0', 40), Th(im, 'aspect-ratio:' + (im.ent ? (m ? '16/3.6' : '16/6') : m ? '4/3' : '16/10') + ';border:1px solid var(--ui-border);flex-shrink:0', 40),
D('display:flex;gap:8px;' + (m ? 'flex-wrap:wrap' : ''), B('Copy URL', { icon: 'link', full: m }), B('Rename', { icon: 'pencil', full: m }), B('Delete', { k: 'del', icon: 'trash-2', full: m })), D('display:flex;gap:8px;' + (m ? 'flex-wrap:wrap' : ''), B('Copy URL', { icon: 'link', full: m }), B('Rename', { icon: 'pencil', full: m }), B('Delete', { k: 'del', icon: 'trash-2', full: m })),
im.dup && Alert('info', 'copy', 'Identical to 2 other images', 'floorboards-copy.jpg and IMG_2208.jpg have the same content.', 'Review duplicates', { icon: 'arrow-right' }), im.dup && Alert('info', 'copy', 'Identical to 2 other images', 'floorboards-copy.jpg and IMG_2208.jpg have the same content.', 'Review duplicates', { icon: 'arrow-right' }),
D('display:grid;grid-template-columns:110px minmax(0,1fr);gap:8px 12px;color:var(--ui-text-toned)', ...meta.flatMap(([k, v]) => [S('color:var(--ui-text-muted)', k), S('color:var(--ui-text-highlighted)', v)]), S('color:var(--ui-text-muted)', 'URL'), S('font:400 12px/20px \'IBM Plex Mono\',monospace;color:var(--ui-text-highlighted);overflow:hidden;text-overflow:ellipsis;white-space:nowrap', 'cms.renew.example/media/' + im.n)), D('display:grid;grid-template-columns:110px minmax(0,1fr);gap:8px 12px;color:var(--ui-text-toned)', ...meta.flatMap(([k, v]) => [S('color:var(--ui-text-muted)', k), S('color:var(--ui-text-highlighted)', v)]), S('color:var(--ui-text-muted)', 'URL'), S('font:400 12px/20px \'IBM Plex Mono\',monospace;color:var(--ui-text-highlighted);overflow:hidden;text-overflow:ellipsis;white-space:nowrap', 'cms.renew.example/media/' + im.n)),
D('display:flex;flex-direction:column;gap:8px', S('font:600 14px/22px \'IBM Plex Sans\',sans-serif;color:var(--ui-text-highlighted)', im.used ? 'Used in ' + pl(im.used) : 'Not used in any article'), D('display:flex;flex-direction:column;gap:8px', S('font:600 14px/22px \'IBM Plex Sans\',sans-serif;color:var(--ui-text-highlighted)', im.used ? 'Used in ' + pl(im.used) : 'Not used in any article'),
im.used ? D('border:1px solid var(--ui-border)', ...list.map(([t, on], i) => D('display:flex;align-items:center;gap:8px;min-height:' + (m ? 48 : 40) + 'px;padding:0 12px;border-top:' + (i ? '1px solid var(--ui-border-muted)' : '0'), S('flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-weight:500;text-decoration:underline;text-underline-offset:3px;color:var(--ui-text-highlighted)', t), on ? Bd('Online', 'on', 22) : Bd('Draft', 'draft', 22), I('arrow-up-right', 14, 'color:var(--ui-text-muted)')))) im.used ? D('border:1px solid var(--ui-border)', ...list.map(([t, on], i) => D('display:flex;align-items:center;gap:8px;min-height:' + (m ? 48 : 40) + 'px;padding:0 12px;border-top:' + (i ? '1px solid var(--ui-border-muted)' : '0'), S('flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-weight:500;text-decoration:underline;text-underline-offset:3px;color:var(--ui-text-highlighted)', t), on ? Bd('Online', 'on', 22) : Bd('Draft', 'draft', 22), I('arrow-up-right', 14, 'color:var(--ui-text-muted)'))))
: S('color:var(--ui-text-muted)', 'This image is safe to delete. No article shows it.'), : S('color:var(--ui-text-muted)', im.ent ? 'No article shows it.' : 'This image is safe to delete. No article shows it.'),
im.used ? S('color:var(--ui-text-muted);font-size:12px', 'Counted from the text of your articles each time you open this page.') : null)))) im.used ? S('color:var(--ui-text-muted);font-size:12px', 'Counted from the text of your articles each time you open this page.') : null), im.ent > 0 && EntBox(im))))
} }
// ---------- modal // ---------- modal
@@ -221,6 +225,7 @@ class Component extends DCLogic {
const md = s.modal, k = md.k const md = s.modal, k = md.k
if (k === 'rename') return { title: 'Rename image', desc: 'Only the filename changes. The URL stays the same, so articles that use this image keep working.', body: [Field('Filename', md.err ? '' : md.val || 'north-wall', { val: !md.err, suffix: '.jpg', focus: !md.loading, err: md.err, dis: md.loading, help: md.err ? '' : 'Letters, numbers, dashes and underscores. The .jpg ending stays.' })], cancel: 'Cancel', confirm: md.loading ? 'Renaming…' : 'Rename' } if (k === 'rename') return { title: 'Rename image', desc: 'Only the filename changes. The URL stays the same, so articles that use this image keep working.', body: [Field('Filename', md.err ? '' : md.val || 'north-wall', { val: !md.err, suffix: '.jpg', focus: !md.loading, err: md.err, dis: md.loading, help: md.err ? '' : 'Letters, numbers, dashes and underscores. The .jpg ending stays.' })], cancel: 'Cancel', confirm: md.loading ? 'Renaming…' : 'Rename' }
if (k === 'del') return { title: 'Delete this image?', desc: '"window-frame.jpg" will be deleted from your library. No article uses it. This can\'t be undone.', cancel: 'Cancel', confirm: md.loading ? 'Deleting…' : 'Delete image', tone: 'danger' } if (k === 'del') return { title: 'Delete this image?', desc: '"window-frame.jpg" will be deleted from your library. No article uses it. This can\'t be undone.', cancel: 'Cancel', confirm: md.loading ? 'Deleting…' : 'Delete image', tone: 'danger' }
if (k === 'delEnt') return { title: 'Delete an image that\'s in use?', desc: '"lime-plaster.jpg" is used in 5 entries and 2 articles. Those entry fields will show "This image is no longer in the library", and the articles will show a broken image. This can\'t be undone.', body: [EntBox(byId(11)), ArtBox(usedList(2))], cancel: 'Cancel', confirm: 'Delete image', tone: 'danger' }
if (k === 'delUsed') return { title: 'Delete an image that\'s in use?', desc: '"north-wall.jpg" is used in 2 articles. If you delete it, they will show a broken image. This can\'t be undone.', body: [ArtBox(usedList(2))], cancel: 'Cancel', confirm: md.loading ? 'Deleting…' : 'Delete image', tone: 'danger' } if (k === 'delUsed') return { title: 'Delete an image that\'s in use?', desc: '"north-wall.jpg" is used in 2 articles. If you delete it, they will show a broken image. This can\'t be undone.', body: [ArtBox(usedList(2))], cancel: 'Cancel', confirm: md.loading ? 'Deleting…' : 'Delete image', tone: 'danger' }
if (k === 'bulk') return { title: 'Delete 3 images?', desc: '2 of them are used in 5 articles, which will show a broken image. The other one isn\'t used anywhere. This can\'t be undone.', body: [D('display:flex;flex-direction:column;border:1px solid var(--ui-border)', ...[['north-wall.jpg', 'Used in 2'], ['kitchen-after.webp', 'Used in 3'], ['window-frame.jpg', 'Unused']].map(([n, u], i) => D('display:flex;align-items:center;gap:8px;min-height:36px;padding:0 12px;border-top:' + (i ? '1px solid var(--ui-border-muted)' : '0'), S('flex:1;color:var(--ui-text-highlighted);overflow:hidden;text-overflow:ellipsis;white-space:nowrap', n), Bd(u === 'Unused' ? 'Unused' : u, u === 'Unused' ? 'unused' : 'used'))))], cancel: 'Cancel', confirm: md.loading ? 'Deleting…' : 'Delete 3 images', tone: 'danger' } if (k === 'bulk') return { title: 'Delete 3 images?', desc: '2 of them are used in 5 articles, which will show a broken image. The other one isn\'t used anywhere. This can\'t be undone.', body: [D('display:flex;flex-direction:column;border:1px solid var(--ui-border)', ...[['north-wall.jpg', 'Used in 2'], ['kitchen-after.webp', 'Used in 3'], ['window-frame.jpg', 'Unused']].map(([n, u], i) => D('display:flex;align-items:center;gap:8px;min-height:36px;padding:0 12px;border-top:' + (i ? '1px solid var(--ui-border-muted)' : '0'), S('flex:1;color:var(--ui-text-highlighted);overflow:hidden;text-overflow:ellipsis;white-space:nowrap', n), Bd(u === 'Unused' ? 'Unused' : u, u === 'Unused' ? 'unused' : 'used'))))], cancel: 'Cancel', confirm: md.loading ? 'Deleting…' : 'Delete 3 images', tone: 'danger' }
if (k === 'merge') return { title: 'Merge into floorboards.jpg?', desc: 'Articles that use the other 2 copies will be switched to floorboards.jpg, and the other 2 copies will be deleted. 5 articles will be updated. This can\'t be undone.', body: [D('display:flex;gap:12px;align-items:center;border:1px solid var(--ui-border);padding:10px 12px', Th(byId(12), 'width:56px;height:42px;flex-shrink:0;border:1px solid var(--ui-border)', 16), D('display:flex;flex-direction:column;min-width:0', S('font-weight:500;color:var(--ui-text-highlighted)', 'floorboards.jpg'), S('font-size:12px;color:var(--ui-text-muted)', 'Kept · used in 4 articles now')))], cancel: 'Cancel', confirm: md.loading ? 'Merging…' : 'Merge 2 copies', tone: 'danger' } if (k === 'merge') return { title: 'Merge into floorboards.jpg?', desc: 'Articles that use the other 2 copies will be switched to floorboards.jpg, and the other 2 copies will be deleted. 5 articles will be updated. This can\'t be undone.', body: [D('display:flex;gap:12px;align-items:center;border:1px solid var(--ui-border);padding:10px 12px', Th(byId(12), 'width:56px;height:42px;flex-shrink:0;border:1px solid var(--ui-border)', 16), D('display:flex;flex-direction:column;min-width:0', S('font-weight:500;color:var(--ui-text-highlighted)', 'floorboards.jpg'), S('font-size:12px;color:var(--ui-text-muted)', 'Kept · used in 4 articles now')))], cancel: 'Cancel', confirm: md.loading ? 'Merging…' : 'Merge 2 copies', tone: 'danger' }
@@ -245,6 +250,7 @@ class Component extends DCLogic {
S('display:block', 'A bathroom is priced by what has to happen behind the walls before anything gets tiled.'), S('display:block', 'A bathroom is priced by what has to happen behind the walls before anything gets tiled.'),
s.inArticle && D('position:relative;aspect-ratio:16/9;border:1px solid var(--ui-border);overflow:hidden', Th(byId(1), 'position:absolute;inset:0', 40), S('position:absolute;top:8px;right:8px;height:28px;padding:0 10px;display:flex;align-items:center;gap:6px;background:var(--ui-bg);border:1px solid var(--ui-border-accented);color:var(--ui-text-highlighted);font:500 12px \'IBM Plex Sans\',sans-serif', I('trash-2', 14), 'Remove image')), s.inArticle && D('position:relative;aspect-ratio:16/9;border:1px solid var(--ui-border);overflow:hidden', Th(byId(1), 'position:absolute;inset:0', 40), S('position:absolute;top:8px;right:8px;height:28px;padding:0 10px;display:flex;align-items:center;gap:6px;background:var(--ui-bg);border:1px solid var(--ui-border-accented);color:var(--ui-text-highlighted);font:500 12px \'IBM Plex Sans\',sans-serif', I('trash-2', 14), 'Remove image')),
S('display:block', 'We don\'t add a margin on materials you choose yourself.')))) S('display:block', 'We don\'t add a margin on materials you choose yourself.'))))
const FEditor = () => D('flex:1;min-height:0;overflow:hidden;background:var(--ui-bg-muted);display:flex;flex-direction:column', D('background:var(--ui-bg);border-bottom:1px solid var(--ui-border);padding:12px ' + (m ? 16 : 24) + 'px;display:flex;align-items:center;gap:12px', S('flex:1;font:600 ' + (m ? 16 : 20) + 'px/28px \'IBM Plex Sans\',sans-serif;color:var(--ui-text-highlighted)', 'Lime plaster workshop'), !m && B('Cancel'), !m && B('Save', { k: 'primary' })), D('padding:' + (m ? 16 : 24) + 'px;display:flex;flex-direction:column;gap:16px;max-width:760px', D('background:var(--ui-bg);border:1px solid var(--ui-border);padding:16px;display:flex;flex-direction:column;gap:12px', S('font-weight:500', 'Title'), D('height:32px;border:1px solid var(--ui-border-accented);display:flex;align-items:center;padding:0 10px', 'Lime plaster workshop'), S('font-weight:500', 'Thumbnail'), D('height:120px;border:1px solid var(--ui-border-accented);background:var(--ui-bg)'))))
const PT = s.pk || {} const PT = s.pk || {}
const pImgs = (PT.ids || [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]).map(byId) const pImgs = (PT.ids || [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]).map(byId)
const inArt = [1, 4] const inArt = [1, 4]
@@ -252,7 +258,7 @@ class Component extends DCLogic {
const PTile = im => { const PTile = im => {
const on = PT.sel === im.id const on = PT.sel === im.id
return D('display:flex;flex-direction:column;gap:6px;min-width:0', D('position:relative;' + (on ? 'outline:2px solid var(--ui-primary);outline-offset:2px;' : ''), Th(im, 'aspect-ratio:1/1;border:1px solid var(--ui-border)', 20), return D('display:flex;flex-direction:column;gap:6px;min-width:0', D('position:relative;' + (on ? 'outline:2px solid var(--ui-primary);outline-offset:2px;' : ''), Th(im, 'aspect-ratio:1/1;border:1px solid var(--ui-border)', 20),
inArt.includes(im.id) && S('position:absolute;left:4px;bottom:4px;height:18px;padding:0 5px;display:flex;align-items:center;background:var(--rc-sand);color:var(--rc-on-sand);font-size:11px;font-weight:500', 'In this article'), (s.field ? im.id === PT.cur : inArt.includes(im.id)) && S('position:absolute;left:4px;bottom:4px;height:18px;padding:0 5px;display:flex;align-items:center;background:var(--rc-sand);color:var(--rc-on-sand);font-size:11px;font-weight:500', s.field ? 'Current' : 'In this article'),
on && S('position:absolute;top:4px;right:4px;width:20px;height:20px;display:flex;align-items:center;justify-content:center;background:var(--ui-primary);color:var(--ui-bg)', I('check', 14))), on && S('position:absolute;top:4px;right:4px;width:20px;height:20px;display:flex;align-items:center;justify-content:center;background:var(--ui-primary);color:var(--ui-bg)', I('check', 14))),
S('font-size:12px;color:var(--ui-text-toned);overflow:hidden;text-overflow:ellipsis;white-space:nowrap', im.n)) S('font-size:12px;color:var(--ui-text-toned);overflow:hidden;text-overflow:ellipsis;white-space:nowrap', im.n))
} }
@@ -267,35 +273,36 @@ class Component extends DCLogic {
} }
const kids = [] const kids = []
kids.push(D('height:' + (m ? 44 : 32) + 'px;padding:0 4px 0 10px;display:flex;align-items:center;gap:8px;border:1px solid var(--ui-border-accented);background:var(--ui-bg);color:' + (PT.q ? 'var(--ui-text-highlighted)' : 'var(--ui-text-muted)') + (m ? ';font-size:16px' : ''), I('search', 14), S('flex:1', PT.q || 'Search by filename'), PT.q && S('width:24px;height:24px;display:flex;align-items:center;justify-content:center;color:var(--ui-text-muted)', I('x', 14)))) kids.push(D('height:' + (m ? 44 : 32) + 'px;padding:0 4px 0 10px;display:flex;align-items:center;gap:8px;border:1px solid var(--ui-border-accented);background:var(--ui-bg);color:' + (PT.q ? 'var(--ui-text-highlighted)' : 'var(--ui-text-muted)') + (m ? ';font-size:16px' : ''), I('search', 14), S('flex:1', PT.q || 'Search by filename'), PT.q && S('width:24px;height:24px;display:flex;align-items:center;justify-content:center;color:var(--ui-text-muted)', I('x', 14))))
if (s.field && !PT.req && !PT.error && !PT.empty && !PT.loading) { const on = PT.sel === 'none'; kids.push(D('display:flex;align-items:center;gap:10px;min-height:' + (m ? 48 : 40) + 'px;padding:0 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)'), I('image-off', 16), S('font-weight:500', 'No image'), S('flex:1;color:' + (on ? 'var(--rc-on-sand)' : 'var(--ui-text-muted)'), 'Leave this field empty.'), on && I('check', 16))) }
if (PT.error) kids.push(Alert('error', 'circle-x', 'Couldn\'t load your library', 'Check your connection and try again.', 'Try again')) if (PT.error) kids.push(Alert('error', 'circle-x', 'Couldn\'t load your library', 'Check your connection and try again.', 'Try again'))
else if (PT.empty === 'first') kids.push(Empty('images', 'Your library is empty', 'Images you upload appear here, ready to use in any article.', 'Upload an image', true, 32)) else if (PT.empty === 'first') kids.push(Empty('images', 'Your library is empty', s.field ? 'Images you upload appear here, ready to use in any article or entry.' : 'Images you upload appear here, ready to use in any article.', 'Upload an image', true, 32))
else if (PT.empty === 'search') kids.push(Empty('search', 'No images match "wall"', 'Check the spelling, or search for a shorter part of the filename.', 'Clear search', false, 32)) else if (PT.empty === 'search') kids.push(Empty('search', 'No images match "wall"', 'Check the spelling, or search for a shorter part of the filename.', 'Clear search', false, 32))
else if (PT.loading) kids.push(PSkel()) else if (PT.loading) kids.push(PSkel())
else { else {
kids.push(S('color:var(--ui-text-muted);font-size:12px', 'Newest first · 48 images'), D('min-height:0;overflow:hidden;' + (PT.sel ? 'max-height:' + (m ? 120 : 190) + 'px' : 'max-height:' + (m ? 300 : 300) + 'px'), PGrid())) kids.push(S('color:var(--ui-text-muted);font-size:12px', 'Newest first · 48 images'), D('min-height:0;overflow:hidden;' + (PT.sel ? 'max-height:' + (m ? 120 : 190) + 'px' : 'max-height:' + (m ? 300 : 300) + 'px'), PGrid()))
if (!PT.sel) kids.push(D('display:flex;justify-content:center', B(PT.more ? 'Loading…' : 'Load more', { icon: PT.more ? 'loader-circle' : null, dis: !!PT.more }))) if (!PT.sel) kids.push(D('display:flex;justify-content:center', B(PT.more ? 'Loading…' : 'Load more', { icon: PT.more ? 'loader-circle' : null, dis: !!PT.more })))
} }
if (PT.sel) { const im = byId(PT.sel); kids.push(D('display:flex;flex-direction:column;gap:12px;padding-top:12px;border-top:1px solid var(--ui-border)', D('display:flex;gap:12px;align-items:center', Th(im, 'width:56px;height:56px;flex-shrink:0;border:1px solid var(--ui-border)', 16), D('display:flex;flex-direction:column;min-width:0', S('font-weight:500;color:var(--ui-text-highlighted)', im.n), S('font-size:12px;color:var(--ui-text-muted)', im.dim + ' · ' + im.sz))), Field('Alt text (optional)', PT.alt || 'e.g. North wall of the kitchen before plastering', { val: !!PT.alt, focus: !!PT.alt, help: 'Describes the image for people who use a screen reader, and shows if it doesn\'t load. Leave it empty if the image is only decoration.' }))) } if (PT.sel && PT.sel !== 'none') { const im = byId(PT.sel); kids.push(D('display:flex;flex-direction:column;gap:12px;padding-top:12px;border-top:1px solid var(--ui-border)', D('display:flex;gap:12px;align-items:center', Th(im, 'width:56px;height:56px;flex-shrink:0;border:1px solid var(--ui-border)', 16), D('display:flex;flex-direction:column;min-width:0', S('font-weight:500;color:var(--ui-text-highlighted)', im.n), S('font-size:12px;color:var(--ui-text-muted)', im.dim + ' · ' + im.sz))), !s.field && Field('Alt text (optional)', PT.alt || 'e.g. North wall of the kitchen before plastering', { val: !!PT.alt, focus: !!PT.alt, help: 'Describes the image for people who use a screen reader, and shows if it doesn\'t load. Leave it empty if the image is only decoration.' }))) }
return D('display:flex;flex-direction:column;gap:12px', ...kids) return D('display:flex;flex-direction:column;gap:12px', ...kids)
} }
const Picker = () => { const Picker = () => {
const ins = PT.tab === 'Library' const ins = PT.tab === 'Library'
return Shell({ title: 'Add an image', close: true, w: 640, top: 40, cancel: 'Cancel', confirm: ins ? 'Insert image' : null, cdis: ins && !PT.sel }, D('display:flex;flex-direction:column;min-height:0;flex:1', PTabs(), D('padding:16px 24px 0;min-height:0;overflow:hidden;display:flex;flex-direction:column', PBody()))) return Shell({ title: s.field ? 'Choose an image' : 'Add an image', close: true, w: 640, top: 40, cancel: 'Cancel', confirm: ins ? (s.field ? (PT.sel === 'none' ? 'Remove image' : 'Use this image') : 'Insert image') : null, cdis: ins && !PT.sel }, D('display:flex;flex-direction:column;min-height:0;flex:1', PTabs(), D('padding:16px 24px 0;min-height:0;overflow:hidden;display:flex;flex-direction:column', PBody())))
} }
// ---------- shell // ---------- shell
const isPicker = s.kind === 'picker' const isPicker = s.kind === 'picker'
const navKey = isPicker ? 'articles' : 'media' const navKey = isPicker ? (s.field ? 'content' : 'articles') : 'media'
const crumbs = isPicker ? ['Articles', 'How we price a bathroom renovation'] : ['Media'] const crumbs = isPicker ? (s.field ? ['Content', 'Events', 'Lime plaster workshop'] : ['Articles', 'How we price a bathroom renovation']) : ['Media']
const offline = s.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. You can look through the images that are loaded, but uploading, renaming and deleting need a connection.')) const offline = s.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. You can look through the images that are loaded, but uploading, renaming and deleting need a connection.'))
const pad = m ? 16 : 24 const pad = m ? 16 : 24
const content = isPicker ? Editor() : D('flex:1;min-height:0;overflow:hidden;padding:' + pad + 'px;display:flex;flex-direction:column;gap:16px;position:relative', Header(), ...pageBody()) const content = isPicker ? (s.field ? FEditor() : Editor()) : D('flex:1;min-height:0;overflow:hidden;padding:' + pad + 'px;display:flex;flex-direction:column;gap:16px;position:relative', Header(), ...pageBody())
const dragOv = s.drag && D('position:absolute;z-index:35;inset:' + (m ? 8 : 12) + 'px;top:' + (m ? 64 : 60) + 'px;border:2px dashed var(--ui-primary);background:var(--rc-sand);color:var(--rc-on-sand);display:flex;flex-direction:column;align-items:center;justify-content:center;gap:8px;text-align:center', I('upload', 28), S('font-weight:600;font-size:16px', 'Drop images to upload'), S('color:var(--rc-on-sand)', 'PNG, JPEG, WEBP, SVG · max 10 MB each')) const dragOv = s.drag && D('position:absolute;z-index:35;inset:' + (m ? 8 : 12) + 'px;top:' + (m ? 64 : 60) + 'px;border:2px dashed var(--ui-primary);background:var(--rc-sand);color:var(--rc-on-sand);display:flex;flex-direction:column;align-items:center;justify-content:center;gap:8px;text-align:center', I('upload', 28), S('font-weight:600;font-size:16px', 'Drop images to upload'), S('color:var(--rc-on-sand)', 'PNG, JPEG, WEBP, SVG · max 10 MB each'))
const fab = m && !isPicker && !(sel.length) && !s.panel && !s.modal && !s.error && s.empty !== 'first' && !s.drag && D('position:absolute;left:16px;right:16px;bottom:16px;height:48px;display:flex;align-items:center;justify-content:center;gap:8px;background:var(--ui-primary);color:var(--ui-bg);font-weight:500;font-size:15px;box-shadow:var(--rc-shadow-pop);opacity:' + (s.limited || s.offline ? 0.4 : 1), I(s.limited ? 'timer' : 'upload', 18), s.limited ? 'Try again in 0:42' : 'Upload') const fab = m && !isPicker && !(sel.length) && !s.panel && !s.modal && !s.error && s.empty !== 'first' && !s.drag && D('position:absolute;left:16px;right:16px;bottom:16px;height:48px;display:flex;align-items:center;justify-content:center;gap:8px;background:var(--ui-primary);color:var(--ui-bg);font-weight:500;font-size:15px;box-shadow:var(--rc-shadow-pop);opacity:' + (s.limited || s.offline ? 0.4 : 1), I(s.limited ? 'timer' : 'upload', 18), s.limited ? 'Try again in 0:42' : 'Upload')
const ann = s.ann && D('position:absolute;z-index:20;' + (m ? 'left:16px;bottom:24px' : 'left:248px;bottom:20px'), Note(s.ann)) const ann = s.ann && D('position:absolute;z-index:20;' + (m ? 'left:16px;bottom:24px' : 'left:248px;bottom:20px'), Note(s.ann))
const main = D('flex:1;min-width:0;min-height:0;display:flex;flex-direction:column', offline, content) const main = D('flex:1;min-width:0;min-height:0;display:flex;flex-direction:column', offline, content)
const ov = D('display:contents', dragOv, fab, ann, sel.length > 0 && !s.panel && !s.modal && BulkBar(), s.panel && Panel(), isPicker && s.picker && Picker(), s.modal && Modal(), s.toasts && Toasts()) const ov = D('display:contents', dragOv, fab, ann, sel.length > 0 && !s.panel && !s.modal && BulkBar(), s.panel && Panel(), isPicker && s.picker && Picker(), s.modal && Modal(), s.toasts && Toasts())
const shell = { kind: 'slot', display: 'Marta Alves', nav: navKey, crumbs, mTitle: isPicker ? 'Edit article' : 'Media', mLead: isPicker ? 'arrow-left' : undefined, mAction: isPicker ? 'ellipsis' : undefined } const shell = { kind: 'slot', display: 'Marta Alves', nav: navKey, crumbs, mTitle: isPicker ? (s.field ? 'Lime plaster workshop' : 'Edit article') : 'Media', mLead: isPicker ? 'arrow-left' : undefined, mAction: isPicker ? 'ellipsis' : undefined, ...(s.field ? { content: [{ key: 'events', name: 'Events', icon: 'files' }, { key: 'recipes', name: 'Recipes', icon: 'files' }, { key: 'press-mentions', name: 'Press mentions', icon: 'files' }], contentOn: 'events' } : {}) }
return { shell, mob: m, main, ov } return { shell, mob: m, main, ov }
} }
} }
@@ -17,7 +17,7 @@
<div style="display:flex;align-items:flex-end;gap:32px;max-width:1400px"> <div style="display:flex;align-items:flex-end;gap:32px;max-width:1400px">
<div style="flex:1;display:flex;flex-direction:column;gap:10px"> <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> <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> <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>. New field type Media (one library image) is drawn inside groups 1 to 6, plus groups 10 (picker) and 11 (media library usage), and the tables "Media field: …" at the end. Changed in AppFrame: a Schema item and a Content group in the sidebar and the mobile drawer.</p>
</div> </div>
<div role="radiogroup" aria-label="Theme" style="display:flex;border:1px solid var(--ui-border-accented);background:var(--ui-bg)"> <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"> <sc-for list="{{ modes }}" as="m" hint-placeholder-count="3">
@@ -37,8 +37,8 @@
<div style="display:flex;flex-direction:column;gap:12px;width:1037px"> <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;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="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:720px;height:450px;overflow:hidden;border:1px solid var(--ui-border);flex-shrink:0"><div style="width:1440px;height:900px;zoom:0.5"><sc-if value="{{ st.isSchema }}"><dc-import name="SchemaFrame" s="{{ st.s }}" mobile="{{ false }}" hint-size="1440px,900px"></dc-import></sc-if><sc-if value="{{ st.isMedia }}"><dc-import name="MediaFrame" s="{{ st.s }}" mobile="{{ false }}" hint-size="1440px,900px"></dc-import></sc-if></div></div>
<div style="width:293px;height:633px;overflow:hidden;border:1px solid var(--ui-border);flex-shrink:0"><div style="width:390px;height:844px;zoom:0.75"><dc-import name="SchemaFrame" s="{{ st.s }}" mobile="{{ true }}" hint-size="390px,844px"></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"><sc-if value="{{ st.isSchema }}"><dc-import name="SchemaFrame" s="{{ st.s }}" mobile="{{ true }}" hint-size="390px,844px"></dc-import></sc-if><sc-if value="{{ st.isMedia }}"><dc-import name="MediaFrame" s="{{ st.s }}" mobile="{{ true }}" hint-size="390px,844px"></dc-import></sc-if></div></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> <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> </div>
@@ -69,7 +69,7 @@ class Component extends DCLogic {
componentDidUpdate(p) { if (p.theme !== this.props.theme && this.props.theme) this.setState({ mode: this.props.theme }); this.apply() } componentDidUpdate(p) { if (p.theme !== this.props.theme && this.props.theme) this.setState({ mode: this.props.theme }); this.apply() }
renderVals() { 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 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 groups = this.state.spec.groups.map(g => ({ ...g, states: g.states.map(s => ({ ...s, isMedia: !!(s.s && s.s.frame === 'media'), isSchema: !(s.s && s.s.frame === 'media'), 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 })) })) const tables = this.state.spec.tables.map(t => ({ ...t, rows: t.rows.map(r => ({ cells: r })) }))
return { rootRef: this.rootRef, modes, groups, tables } return { rootRef: this.rootRef, modes, groups, tables }
} }
+62 -33
View File
@@ -61,7 +61,7 @@ class Component extends DCLogic {
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 })) 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 // ---------- 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 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'], media: ['image', 'Media', 'One image from your media library'] }
const EV = [ 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: '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 })) { 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 }))
@@ -81,6 +81,7 @@ class Component extends DCLogic {
{ 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: 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: 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' }] { 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' }]
ROWS.forEach((r, i) => { r.thumbnail = ['ok', 'ok', '', 'miss', 'ok', '', 'ok'][i] })
const mdSample = 'Two days of hands-on work with **lime putty** and old stone.\n\n- Bring work clothes\n- Lunch is included' 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 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 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)
@@ -88,6 +89,23 @@ class Component extends DCLogic {
const dot = (t, ic) => S('display:inline-flex;align-items:center;gap:6px', I(ic, 14), t) const dot = (t, ic) => S('display:inline-flex;align-items:center;gap:6px', I(ic, 14), t)
// ---------- inspector // ---------- inspector
const stripe = 'repeating-linear-gradient(135deg,var(--ui-bg-elevated) 0 6px,var(--ui-bg-accented) 6px 7px)'
const THUMB = { key: 'thumbnail', label: 'Thumbnail', type: 'media', saved: true }
const Ph = (w, hh, ex, ...c) => D('width:' + w + ';' + (hh ? 'height:' + hh + ';' : '') + 'flex-shrink:0;box-sizing:border-box;display:flex;align-items:center;justify-content:center;background:' + stripe + ';color:var(--ui-text-toned);' + mono + 'font-size:11px;line-height:16px;' + (ex || ''), ...c)
const Miss = (w, hh, ic = 'image-off', z = 20, ex = '') => h('div', { role: 'img', 'aria-label': 'Image no longer in the library', style: P('width:' + w + ';' + (hh ? 'height:' + hh + ';' : '') + 'flex-shrink:0;display:flex;align-items:center;justify-content:center;border:1px dashed var(--ui-border-accented);color:var(--ui-text-muted);box-sizing:border-box;' + ex) }, I(ic, z))
const cellM = (st, z) => st === 'ok' ? Ph(z + 'px', z + 'px', '') : st === 'miss' ? Miss(z + 'px', z + 'px', 'unlink', z > 32 ? 14 : 12) : S('color:var(--ui-text-muted);width:' + z + 'px;text-align:center;display:inline-block', '–')
const MThumb = o => D('position:relative;flex-shrink:0;box-sizing:border-box;overflow:hidden;width:' + (m ? '100%' : '160px') + ';' + (m ? 'aspect-ratio:16/9;' : 'height:120px;') + 'border:1px solid ' + (o.hover && !m ? 'var(--ui-text-muted)' : 'var(--ui-border-accented)') + ';' + (o.focus ? 'outline:2px solid var(--ui-primary);outline-offset:2px;' : '') + 'opacity:' + (o.dis ? 0.6 : 1), Ph('100%', '100%', '', '1600 × 900'), o.hover && !m && D('position:absolute;left:0;right:0;bottom:0;height:28px;display:flex;align-items:center;justify-content:center;gap:6px;background:var(--ui-bg-inverted);color:var(--ui-text-inverted);font-size:12px;font-weight:500', I('image', 14), 'Change image'))
const MCtl = (f, o = {}) => {
const dis = !!o.dis, st = o.st || 'empty'
const bd = o.err ? 'border:1px solid var(--ui-error);box-shadow:inset 0 0 0 1px var(--ui-error);' : st === 'empty' ? 'border:1px dashed var(--ui-border-accented);' : 'border:1px solid var(--ui-border-accented);'
const row = (...c) => D('display:flex;flex-direction:' + (m ? 'column' : 'row') + ';gap:' + (m ? 12 : 16) + 'px;padding:12px;align-items:' + (m ? 'stretch' : 'flex-start'), ...c)
const col = (...c) => D('flex:1;min-width:0;display:flex;flex-direction:column;gap:12px;' + (m ? '' : 'justify-content:space-between;min-height:120px'), ...c)
let inner
if (st === 'empty') inner = D('display:flex;flex-direction:' + (m ? 'column' : 'row') + ';align-items:' + (m ? 'stretch' : 'center') + ';gap:12px;padding:12px', D('display:flex;align-items:center;gap:12px;flex:1;min-width:0', S('width:40px;height:40px;display:flex;align-items:center;justify-content:center;background:var(--ui-bg-elevated);color:var(--ui-text-toned);flex-shrink:0', I('image', 20)), S('color:var(--ui-text-muted)', 'No image selected.')), B('Pick an image', { icon: 'image-plus', dis, ring: o.ringBtn === 'pick' }))
else if (st === 'filled') inner = row(MThumb(o), col(D('display:flex;flex-direction:column;gap:2px;min-width:0', S('font-weight:500;color:var(--ui-text-highlighted);overflow:hidden;text-overflow:ellipsis;white-space:nowrap', 'lime-plaster-workshop.jpg'), S('color:var(--ui-text-muted);font-size:12px;line-height:18px', '1600 × 900 · 240 KB')), D('display:flex;gap:8px', B('Change image', { icon: 'image', dis, full: m }), B('Remove', { k: 'ghost', icon: 'x', dis, full: m }))))
else inner = row(Miss(m ? '100%' : '160px', m ? null : '120px', 'image-off', 24, (m ? 'aspect-ratio:16/9;' : '') + (dis ? 'opacity:0.6;' : '')), col(D('display:flex;flex-direction:column;gap:4px', S('font-weight:500;color:var(--ui-text-highlighted)', 'This image is no longer in the library'), S('color:var(--ui-text-muted);font-size:12px;line-height:18px;text-wrap:pretty', f.req ? 'Thumbnail is required. Choose another image to save.' : 'You can still save. The entry keeps the link until you change it.')), D('display:flex;gap:8px;flex-wrap:wrap', B('Choose another image', { icon: 'image', dis, ring: o.ringBtn === 'choose', full: m }), B('Clear', { k: 'ghost', dis, full: m }))))
return D('display:flex;flex-direction:column;gap:6px;min-width:0', S('font-weight:500;color:var(--ui-text-highlighted)', f.label, f.req && ' *'), D(bd + 'background:var(--ui-bg);box-sizing:border-box', inner), 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) : st === 'missing' ? null : S('color:var(--ui-text-muted);font-size:12px;line-height:18px', 'One image from your library.'))
}
const Insp = (f, o = {}) => { const Insp = (f, o = {}) => {
const t = f.type, e = f.err || {}, one = m || o.one, locked = !!f.saved 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 [mnL, mxL, suf] = MM(t), canU = ['text', 'number', 'date', 'select'].includes(t), hasMM = ['text', 'richtext', 'number', 'date'].includes(t)
@@ -96,15 +114,15 @@ class Component extends DCLogic {
const mmErr = e.min || '' const mmErr = e.min || ''
const minV = f.min != null ? String(f.min) : '', maxV = f.max != null ? String(f.max) : '' 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 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 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.'), t !== 'media' && 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 right = t === 'media' ? [] : 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 const ch = t === 'select' ? Choices(f) : t === 'media' ? D('display:flex;gap:8px;padding:10px 12px;background:var(--rc-info-soft);color:var(--ui-info)', S('padding-top:2px;display:flex', I('info', 16)), S('color:var(--ui-text-toned);text-wrap:pretty', 'Holds one image from the media library. Entries link to the image instead of keeping a copy, so they always show its current version.')) : null
return D('display:flex;flex-direction:column;gap:' + (m ? 16 : 14) + 'px;min-width:0', 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: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;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))), 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, left,
D('display:grid;grid-template-columns:' + g2 + ';gap:14px;align-items:start', ...right.filter(Boolean)), right.length > 0 && D('display:grid;grid-template-columns:' + g2 + ';gap:14px;align-items:start', ...right.filter(Boolean)),
ch) ch)
} }
const Choices = f => { const Choices = f => {
@@ -141,6 +159,7 @@ class Component extends DCLogic {
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 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 Ctl = (f, o = {}) => {
const t = f.type, v = o.v == null ? '' : String(o.v) const t = f.type, v = o.v == null ? '' : String(o.v)
if (t === 'media') return MCtl(f, o)
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 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 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 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)
@@ -157,6 +176,7 @@ class Component extends DCLogic {
} }
const Cell = (f, v) => { const Cell = (f, v) => {
if (v === undefined || v === null || v === '') return S('color:var(--ui-text-muted)', '–') if (v === undefined || v === null || v === '') return S('color:var(--ui-text-muted)', '–')
if (f.type === 'media') return cellM(v, 40)
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 === '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 === '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) if (f.type === 'number') return S('justify-self:end;font-variant-numeric:tabular-nums', v)
@@ -183,12 +203,13 @@ class Component extends DCLogic {
const newBtn = B('New content type', { k: 'primary', icon: 'plus', px: 14, dis: k === 'loading' }) 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' })] : [] 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 })) } 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') { else if (k === 'builtin' || k === 'customro') {
shell.crumbs = ['Schema', 'Articles']; shell.mTitle = 'Articles'; shell.mLead = 'arrow-left' const cr = k === 'customro'
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', '']] shell.crumbs = ['Schema', cr ? 'Events' : 'Articles']; shell.mTitle = cr ? 'Events' : 'Articles'; shell.mLead = 'arrow-left'
const AF = cr ? [['Title', 'title', 'text', 'Required · unique · up to 80 characters'], ['Starts on', 'starts_on', 'date', 'Required'], ['Category', 'category', 'select', 'Talk, Workshop, Meetup'], ['Description', 'description', 'richtext', ''], ['Thumbnail', 'thumbnail', 'media', 'One image from the library']] : [['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)' 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')), 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)', cr ? 'Events' : 'Articles'), cr ? Bd('Read only', 'built', 'lock') : 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.'), cr ? Alert('info', 'info', 'You can read these fields here', 'Only an owner or admin can change a content type.') : 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] : ''))))) : 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.')) 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 { } else {
@@ -203,12 +224,15 @@ class Component extends DCLogic {
} }
// 2 builder // 2 builder
const entN = v === 'review' && (k === 'mrefuse' || k === 'mclean') ? 12 : 37
const bld = () => { 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 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 === 'review') { const rk = k; if (rk === 'confirm' || rk === 'fallback') { fl = RC; name = 'Recipes'; key = 'recipes'; info = false } else if (rk === 'blocked') { sel = 0 } else if (rk === 'mrefuse' || rk === 'mclean') { fl = [...EV, { key: 'thumbnail', label: 'Thumbnail', type: 'media', isNew: true, req: rk === 'mrefuse' }]; sel = 7; st = 'dirty' } else { fl = DIRTY; sel = 4; st = 'dirty'; removed = EV[6] } }
if (v === 'rel') { } if (v === 'rel') { }
if (v === 'builder') { if (v === 'builder') {
if (k === 'locked') { sel = 1; tip = true } if (k === 'locked') { sel = 1; tip = true }
if (k === 'media' || k === 'mreq') { fl = [...EV, k === 'mreq' ? { ...THUMB, req: true } : THUMB]; sel = 7 }
if (k === 'mnew') { fl = [...EV, { key: 'thumbnail', label: 'Thumbnail', type: 'media', isNew: true }]; sel = 7; st = 'dirty' }
if (['dirty', 'saving', 'saved', 'fail', 'incompat', 'offline'].includes(k)) { fl = DIRTY; sel = 4; st = k === 'incompat' ? 'dirty' : k; removed = EV[6] } 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 === '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 === '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')
@@ -227,7 +251,7 @@ class Component extends DCLogic {
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 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 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 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 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)', entN + ' 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 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 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 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.'))]
@@ -240,7 +264,7 @@ class Component extends DCLogic {
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.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 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)) 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 && f && (s.sheet || (v === 'builder' && ['edit-sheet', 'choices', 'media', 'mreq', 'mnew'].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 (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 (toast) ov.push(toast)
} }
@@ -258,28 +282,29 @@ class Component extends DCLogic {
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 === '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 === '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 === '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 === 'mrefuse' || k === 'mclean') { const rf = k === 'mrefuse'; 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: 'Apply changes', cdis: rf }, [D('display:flex;flex-direction:column;gap:2px', S('font-weight:600;font-size:15px;color:var(--ui-text-highlighted)', 'Add 1 field'), S('color:var(--ui-text-muted)', 'Events has 12 entries. Each one is checked against the new fields when you apply.')), chg('plus', 'n', 'Add Thumbnail', rf ? 'Media, required. A media field can\'t have a default, so the 12 existing entries would have no image. Make Thumbnail optional to add it.' : 'Media, optional. 12 entries are unaffected.', rf ? 'Can\'t be applied' : null), rf && S('color:var(--ui-text-muted);font-size:12px;line-height:18px', 'Back to editing keeps your other changes.')])) }
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.')])) 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 // 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 } } const GF = { media: THUMB, 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') { if (v === 'gallery') {
bare = true; if (m) { bw = '390px'; bhh = '844px' } bare = true; if (m) { bw = '390px'; bhh = '844px' }
const f = { ...GF[k], saved: false }, t = k, L = f.label 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 ERR = { media: [['required', 422, 'Pick an image for ' + L + '.'], ['type', 422, L + ' must be an image from the library.'], ['min', '', 'Not used for media.'], ['max', '', 'Not used for media.'], ['options', '', 'Not used for media.'], ['unique', '', 'Not used for media.']], 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 SAMPLE = { media: ['', ''], 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 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 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 specCtl = { media: Ctl(f, { st: 'filled', hover: true }), 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 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 stateLbl = { media: 'Filled, pointer over the thumbnail', 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 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 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 cellVals = { media: ['ok', ''], 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 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'), t === 'media' && cell('miss', 'Image missing'))), 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.', media: 'A 40 px square thumbnail, 32 px in cards. Not sortable. A dash when empty.' }[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 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 = { media: [['has an image'], 'media'], 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 fw = FW[1] === 'media' ? Seg([['any', 'Any'], ['yes', 'Has an image'], ['no', 'No image']], 'any') : 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 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 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 }))) const inspCol = !m && sec('Inspector options', card(Insp(f, { one: true })))
@@ -287,7 +312,7 @@ class Component extends DCLogic {
} }
// 5 entries // 5 entries
const visCols = k === 'cols' ? [EV[0], EV[1], EV[2], EV[3]] : [EV[0], EV[1], EV[2], EV[3]] const visCols = ['thumb', 'thumbcols', 'thumbtip'].includes(k) ? [EV[0], THUMB, EV[1], EV[5]] : [EV[0], EV[1], EV[2], EV[3]]
if (v === 'entries') { if (v === 'entries') {
shell.nav = 'content'; shell.crumbs = ['Content', 'Events']; shell.mTitle = 'Events'; shell.contentOn = k === 'notfound' ? null : 'events' 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 (s.many && m) { shell.drawer = true; shell.contentOpen = true }
@@ -305,19 +330,20 @@ class Component extends DCLogic {
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 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 { else {
const rows = ROWS.slice(0, size > 7 ? 7 : 5) 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 gc = '48px ' + visCols.map((f, i) => i === 0 ? 'minmax(0,1.6fr)' : f.type === 'boolean' || f.type === 'number' || f.type === 'media' ? '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 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')), 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)))) ...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 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', visCols.some(f => f.type === 'media') && cellM(r.thumbnail, 32), 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 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'))) 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) 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])) 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 (m && k !== 'error' && k !== 'loading') ov.push(Fab('New entry'))
if (k === 'cols') { if (k === 'thumbtip' && !m) ov.push(D('position:absolute;z-index:30;left:609px;top:416px;padding:6px 8px;background:var(--ui-bg-inverted);color:var(--ui-text-inverted);font-size:12px;line-height:18px;box-shadow:var(--rc-shadow-pop);white-space:nowrap', 'Image no longer in the library'))
const items = EV.map((f, i) => [f, i < 4]) if (k === 'cols' || k === 'thumbcols') {
const items = k === 'thumbcols' ? [...EV, THUMB].map(f => [f, ['title', 'thumbnail', 'starts_on', 'category'].includes(f.key)]) : 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'))) 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 })])) 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 })))) 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 }))))
@@ -327,6 +353,7 @@ class Component extends DCLogic {
// 6 entry // 6 entry
if (v === 'entry') { if (v === 'entry') {
const mk = s.m || null, mErr = mk === 'err' || mk === 'missingreq'
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' 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 })) 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 { else {
@@ -338,16 +365,18 @@ class Component extends DCLogic {
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 === '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.' } 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 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 sk = k === 'dirty' ? 'dirty' : k === 'saving' ? 'saving' : k === 'saved' ? 'saved' : k === 'fail' ? 'fail' : (k === 'required' || k === 'rules' || k === 'unique' || mErr) ? '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 chip = k === 'required' || k === 'rules' || k === 'unique' || mErr ? 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 canSave = k === 'dirty' || k === 'fail' || k === 'new' || k === 'required' || k === 'rules' || k === 'unique' || mErr
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 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 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 mo = { hover: { st: 'filled', hover: true }, focus: { st: 'filled', focus: true }, filled: { st: 'filled' }, err: { st: 'empty', err: 'Pick an image for Thumbnail.', ringBtn: 'pick' }, missing: { st: 'missing' }, missingreq: { st: 'missing', err: 'Pick an image for Thumbnail.', ringBtn: 'choose' } }[mk] || { st: 'empty' }
const mUI = mk && Ctl({ ...THUMB, req: ['emptyreq', 'err', 'missingreq'].includes(mk) }, { ...mo, dis })
const grid = (a, b) => D('display:grid;grid-template-columns:' + (m ? '1fr' : '1fr 1fr') + ';gap:16px', a, b) 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 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], mUI, 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 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' && mk ? Alert('warning', 'triangle-alert', 'The fields of Events changed', 'The Thumbnail field was changed 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 === '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' })) 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) 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, mk ? D('flex:1;min-height:0;overflow:hidden', D('margin-top:' + (m ? (k === 'changed' ? -740 : -560) : -380) + 'px', form)) : 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 === '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.')) if (k === 'saved') ov.push(Toast('success', 'circle-check', 'Entry saved', '"Lime plaster workshop" is up to date.'))
} }
+446
View File
@@ -0,0 +1,446 @@
export const tables = [
{
"title": "Media field: scope",
"tpl": "260px 140px minmax(0,1fr)",
"cols": [
"Screen or state",
"Scope",
"Note"
],
"rows": [
[
"2 Builder: media field selected, new, required",
"Available now",
"Needs the media type in the schema API."
],
[
"3 Review: refused and clean",
"Available now",
"The refusal is known to the client before the server answers."
],
[
"4 Field types: Media frame",
"Available now",
"The filter widget is Later: filtering on custom fields isn't in the API."
],
[
"5 Entry list: Thumbnail column, Columns menu, tooltip",
"Available now",
"Needs image summaries in the entry list payload."
],
[
"6 Entry editor: Media control, 10 states",
"Available now",
""
],
[
"10 Picker for fields, 8 states",
"Available now",
"Same endpoints as the article picker."
],
[
"11 Media library usage, 4 states",
"Available now",
"Needs entries in the usage endpoint."
],
[
"1 Schema list: custom type read-only view",
"Available now",
"Table only; the route is a decision, see conflicts."
],
[
"Several images in one field",
"Not drawn",
"Out of scope."
]
]
},
{
"title": "Media field: exact copy",
"tpl": "200px 200px minmax(0,1fr)",
"cols": [
"Surface",
"Element",
"Copy"
],
"rows": [
[
"Inspector",
"Hint",
"Holds one image from the media library. Entries link to the image instead of keeping a copy, so they always show its current version."
],
[
"Inspector",
"Locked type",
"Media · Can't change after saving."
],
[
"Inspector",
"Required",
"Required · An entry can't be saved with this field empty."
],
[
"Field row",
"Tag",
"Required"
],
[
"Review",
"Refusal row",
"Add Thumbnail · Can't be applied · Media, required. A media field can't have a default, so the 12 existing entries would have no image. Make Thumbnail optional to add it."
],
[
"Review",
"Clean row",
"Add Thumbnail · Media, optional. 12 entries are unaffected."
],
[
"Control",
"Empty",
"No image selected. · Pick an image"
],
[
"Control",
"Filled",
"lime-plaster-workshop.jpg · 1600 × 900 · 240 KB · Change image · Remove"
],
[
"Control",
"Help",
"One image from your library."
],
[
"Control",
"Error",
"Pick an image for Thumbnail."
],
[
"Control",
"Missing",
"This image is no longer in the library · Choose another image · Clear"
],
[
"Control",
"Missing help",
"Optional: You can still save. The entry keeps the link until you change it. Required: Thumbnail is required. Choose another image to save."
],
[
"Control",
"Announcements (live, polite)",
"Image selected: lime-plaster-workshop.jpg · Image removed from Thumbnail. · Thumbnail cleared."
],
[
"Read view",
"Rules cell",
"Optional · One image from the library"
],
[
"Gallery",
"Name, description",
"Media · One image from your media library"
],
[
"Picker",
"Title, search, row",
"Choose an image · Search by filename · No image · Leave this field empty."
],
[
"Picker",
"Badge and buttons",
"Current · Load more · Cancel · Use this image · Remove image (when No image is chosen)"
],
[
"Picker",
"States",
"Your library is empty · Images you upload appear here, ready to use in any article or entry. · Upload an image · Couldn't load your library · Check your connection and try again. · Try again"
],
[
"Entry list",
"Header, empty, missing",
"Thumbnail · – · Image no longer in the library"
],
[
"Media library",
"Badge and tooltip",
"Used in 3 · Used in entries: 3"
],
[
"Media library",
"Panel",
"Used in entries · and 2 more"
],
[
"Media library",
"Delete",
"Delete an image that's in use? · \"lime-plaster.jpg\" is used in 5 entries and 2 articles. Those entry fields will show \"This image is no longer in the library\", and the articles will show a broken image. This can't be undone. · Cancel · Delete image"
]
]
},
{
"title": "Media field: components, reused and new",
"tpl": "220px 140px minmax(0,1fr)",
"cols": [
"Component",
"Status",
"Notes"
],
"rows": [
[
"AppFrame, SchemaFrame builder rows, Insp, FRow, review dialog rows, entry form, entry list and Columns menu",
"Reused",
"The inspector hides Unique, default and limits for media, as it does for yes or no. One more type tile (seven)."
],
[
"MediaFrame: grid card, list row, detail panel, delete dialog, picker dialog",
"Reused",
"Picker gains a field mode (no alt text, no variant select, Current, No image). Panel gains a Used in entries list. Badge counts articles plus entries."
],
[
"MediaFieldControl",
"New (the only one)",
"Props: label, required, modelValue (image id or null), image (summary or missing), disabled, error. Emits update:modelValue. Opens the picker."
],
[
"Nuxt UI mapping",
"Nuxt UI v4",
"UFormField (label, help, error, required) · UButton \"Pick an image\", \"Change image\", \"Choose another image\" (outline) · UButton \"Remove\", \"Clear\" (ghost) · UModal on desktop and a bottom UDrawer on mobile for the picker, as the article picker · UTooltip in the list and on the badge · UIcon lucide:image, lucide:image-off, lucide:unlink. The thumbnail is a plain button."
]
]
},
{
"title": "Picker and field failures: status to copy",
"tpl": "160px minmax(0,1fr)",
"cols": [
"Request and status",
"Copy"
],
"rows": [
[
"GET /v1/media/ 400",
"That request wasn't valid. Check the fields and try again. (search is trimmed first, so this is rare)"
],
[
"GET /v1/media/ 401, 403",
"Global redirect, no local copy."
],
[
"GET /v1/media/ 429",
"Too many requests. Try again in a few minutes. (countdown alert as on the Media page)"
],
[
"GET /v1/media/ 500, network",
"Couldn't load your library · Check your connection and try again. · Try again (500 body: Something went wrong on our side. Nothing was changed. Try again in a moment.)"
],
[
"POST /v1/media/ 413",
"That file is too large."
],
[
"POST /v1/media/ 400",
"That request wasn't valid. Check the fields and try again."
],
[
"POST /v1/media/ 429",
"Too many requests. Try again in a few minutes."
],
[
"POST /v1/media/ 500, network",
"Something went wrong on our side. Nothing was changed. Try again in a moment."
],
[
"PUT entry 422 invalid_entry thumbnail: required",
"Pick an image for Thumbnail."
],
[
"PUT entry 422 invalid_entry thumbnail: type",
"Thumbnail must be an image from the library. (the image was deleted between the pick and the save)"
],
[
"PUT entry 409",
"This changed somewhere else. Reload and try again."
],
[
"DELETE /v1/media/{id} 404",
"That item no longer exists."
],
[
"DELETE /v1/media/{id} 500, network",
"Something went wrong on our side. Nothing was changed. Try again in a moment."
]
]
},
{
"title": "Row height with media",
"tpl": "220px minmax(0,1fr)",
"cols": [
"Surface",
"Choice and reason"
],
"rows": [
[
"Desktop table",
"The design rule is 48 px rows (56 px for the media library). The brief mentions 32 px, which the design does not use. The thumbnail is 40 px, so a 48 px row keeps 4 px above and below and does not grow. No row exceeds 48 px."
],
[
"Mobile card",
"Cards are 68 px minimum. The thumbnail is 32 px and leads the card. Cards do not grow."
],
[
"Missing image",
"Dashed square with the same 40 px (32 px) footprint, so the columns stay aligned and the row does not move."
]
]
},
{
"title": "Accessibility",
"tpl": "220px minmax(0,1fr)",
"cols": [
"Topic",
"Notes"
],
"rows": [
[
"Group and label",
"MediaFieldControl is role=\"group\" labelled by the field label. A required field adds aria-required to the control button and the * is part of the label text."
],
[
"Button names",
"Pick an image → \"Pick an image for Thumbnail\". Thumbnail button → \"Change image, lime-plaster-workshop.jpg, 1600 by 900, 240 KB\". Remove → \"Remove image from Thumbnail\". Clear → \"Clear Thumbnail\". Missing placeholder: role img, \"Image no longer in the library\". Each name starts with the visible label."
],
[
"Focus order",
"Label, thumbnail, Change image, Remove, help or error. The thumbnail duplicates Change image; if reviewers prefer one stop, make it tabindex -1 and keep the pointer shortcut."
],
[
"Announcements",
"One polite live region on the control: \"Image selected: lime-plaster-workshop.jpg\", \"Image removed from Thumbnail.\", \"Thumbnail cleared.\" No announcement when the picker opens."
],
[
"Focus after actions",
"Picker closes with Use this image: focus goes to Change image. Remove or Clear: focus goes to Pick an image. Cancel or Esc: focus returns to the button that opened it. Save refused: focus goes to the first invalid control (Pick an image or Choose another image)."
],
[
"Error",
"The error text has an id. The control button gets aria-invalid=\"true\" and aria-describedby set to the error id, then the help id. aria-invalid is not defined for group, so it sits on the focusable button."
],
[
"Picker",
"Tabs follow the existing tablist pattern. Tiles are buttons with aria-pressed and names like \"stone-steps.jpg, 310 KB\" and \", Current\". No image is a button with aria-pressed. Use this image uses aria-disabled while nothing is chosen. Load more keeps focus until new tiles arrive."
],
[
"Contrast and targets",
"Current badge is on-sand on sand (14.3). Text on selected tiles uses on-sand, never muted. The hover bar is inverted text on inverted ground (18.9). Dashed borders use border-accented (3.6). Mobile targets are 44 px."
],
[
"Motion and touch",
"No hover on mobile. Hover and focus never carry information alone."
]
]
},
{
"title": "Needs backend",
"tpl": "260px minmax(0,1fr)",
"cols": [
"Item",
"What is needed"
],
"rows": [
[
"Media field type",
"Schema API accepts type \"media\" with label, key, required only. The value is an image id or null. Writes with a missing id on a changed value return 422 invalid_entry, type."
],
[
"Image summary in entries",
"Entry and list responses include, per media field, filename, width, height, size and a small thumbnail URL, or a flag that the image is missing, so the editor and list need no extra requests."
],
[
"Usage by entries",
"GET /v1/media/{id}/usage returns articles and entries (content type name, key, entry id, title), a total count and the first few items."
],
[
"Counts for the badge and delete",
"GET /v1/media/ list items carry the combined use count. DELETE keeps working for used images; the entries keep their ids."
],
[
"Required with entries",
"The server refuses a new required media field on a type with entries with schema_incompatible. The client shows the refusal first."
]
]
},
{
"title": "Media field: conflicts with the existing design, decide before coding",
"tpl": "40px 260px minmax(0,1fr)",
"cols": [
"#",
"Brief",
"Existing design and what the board does"
],
"rows": [
[
"1",
"Rows follow a 32 px density rule.",
"Tables use 48 px rows (56 px for media) and 68 px cards. Drawn at 48 and 68; the 40 px thumbnail fits without growing a row."
],
[
"2",
"Thumbnail sits between Description and Starts on.",
"In the existing editor Description is the last field and Starts on comes second. Drawn after Description, at the end of the form, which is schema order. Moving it needs a different form order."
],
[
"3",
"\"Used in 3\" counts entries.",
"Today \"Used in N\" counts articles. Drawn as articles plus entries; the tooltip and the panel split them."
],
[
"4",
"Delete title \"Delete this image?\".",
"The existing dialog for an image in use is \"Delete an image that's in use?\" with an articles list. Kept that title and added the entries list. \"Delete this image?\" stays the unused-image title."
],
[
"5",
"\"Clear\" in the missing state.",
"The glossary says Remove detaches and the filled state uses Remove. Kept \"Clear\" as written. Suggest Remove for both."
],
[
"6",
"\"1600 x 900 - 240 KB\".",
"The design uses × and the middle dot (\"1600 × 900 · 240 KB\")."
],
[
"7",
"Refuse the required media field in the review step.",
"The review is informational and Apply changes is never disabled; the server decides. This one case is certain, so Apply is off. Alternative: leave Apply on and show the 422 refusal dialog."
],
[
"8",
"Primary button \"Use this image\".",
"The article picker says \"Insert image\". When No image is chosen the button reads \"Remove image\" (my addition). The picker keeps its existing copy for empty and failed states."
],
[
"9",
"Pick an image on empty optional fields too.",
"The brief names the button for required fields only. One name covers both."
],
[
"10",
"Read view of a custom type.",
"Only owners and admins see Schema, and they edit. No read-only route exists for custom types. Table drawn as the built-in one; the route is a decision."
],
[
"11",
"Thumbnail focus ring.",
"The thumbnail and Change image open the same picker, so there are two tab stops. See accessibility."
],
[
"12",
"Disabled look.",
"Entry form fields dim to 60% and foundations.md says 40%. The control follows the form."
],
[
"13",
"Picker page behind the dialog.",
"The existing picker frame shows the article editor. The field picker shows a stand-in for the entry form."
]
]
}
]
+45 -7
View File
@@ -1,3 +1,4 @@
import { tables as mfTables } from './media-field-tables.js'
const N = 'available now', L = 'later' const N = 'available now', L = 'later'
const st = (name, scope, trigger, s, copy, o = {}) => ({ name, scope, trigger, s, copy, ...o }) const st = (name, scope, trigger, s, copy, o = {}) => ({ name, scope, trigger, s, copy, ...o })
@@ -8,7 +9,8 @@ export const groups = [
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('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('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('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.') 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.'),
st("Custom type: read-only view", N, "The fields table of a custom type with a media field. Same table as the built-in view; the Media type shows the image icon and the name \"Media\".", {"v":"types","k":"customro"}, "Events · Read only · You can read these fields here · Only an owner or admin can change a content type. · Label · Key · Type · Rules · Thumbnail · thumbnail · Media · One image from the library")
] }, ] },
{ 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: [ { 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('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'),
@@ -26,7 +28,10 @@ export const groups = [
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('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('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('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') 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'),
st("Media field selected", N, "Thumbnail was saved before. Key and type are locked. The inspector shows Label, Key, Type and Required only; the hint explains the field holds one image.", {"v":"builder","k":"media"}, "Thumbnail · thumbnail · Field: Thumbnail · Key · Used in the API, so it can't change. · Type · Can't change after saving · Media · One image from your media library · Required · An entry can't be saved with this field empty. · Holds one image from the media library. Entries link to the image instead of keeping a copy, so they always show its current version."),
st("New media field, seven types", N, "Add field, then Media. The type tiles show all seven types; key and type can still change.", {"v":"builder","k":"mnew"}, "New · Type · Text · Rich text · Number · Yes or no · Date · Choice · Media · One image from your media library · Key · The name used in the API. Starts with a letter. Lowercase letters, digits and underscores."),
st("Media field, required", N, "A saved required media field. The row carries the Required marker.", {"v":"builder","k":"mreq"}, "Thumbnail · thumbnail · Required (marker) · Required · An entry can't be saved with this field empty.")
] }, ] },
{ 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: [ { 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('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'),
@@ -35,9 +40,11 @@ export const groups = [
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('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: 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: 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') 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'),
st("Review: required media field refused", N, "Thumbnail is required and Events has 12 entries. A media field can't have a default, so Apply is off.", {"v":"review","k":"mrefuse"}, "Review changes to Events · Apply them to save the content type. · Add 1 field · Events has 12 entries. Each one is checked against the new fields when you apply. · Add Thumbnail · Can't be applied · Media, required. A media field can't have a default, so the 12 existing entries would have no image. Make Thumbnail optional to add it. · Back to editing keeps your other changes. · Back to editing · Apply changes (disabled)"),
st("Review: optional media field", N, "Thumbnail is optional.", {"v":"review","k":"mclean"}, "Review changes to Events · Add 1 field · Events has 12 entries. Each one is checked against the new fields when you apply. · Add Thumbnail · Media, optional. 12 entries are unaffected. · Back to editing · Apply changes")
] }, ] },
{ 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: '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', 'media'].map((t, i) => st(['Text', 'Rich text', 'Number', 'Yes or no', 'Date', 'Choice', 'Media'][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.', media: 'Media · One image from your media library · Label · Key · Required · Holds one image from the media library. Entries link to the image instead of keeping a copy, so they always show its current version. · Pick an image · No image selected. · One image from your library. · Change image · Remove · lime-plaster-workshop.jpg · 1600 × 900 · 240 KB · This image is no longer in the library · Choose another image · Clear · Pick an image for Thumbnail. · Thumbnail must be an image from the library. · Not used for media. · Thumbnail: has an image (later)', 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: [ { 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('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('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)'),
@@ -47,7 +54,10 @@ export const groups = [
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('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('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('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') 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'),
st("Thumbnail column", N, "Events list with a Thumbnail column: 40 px square thumbnails, one \"–\", one missing image. Row height stays 48 px. Mobile: 32 px thumbnail leads the card. Not sortable.", {"v":"entries","k":"thumb"}, "Thumbnail · Lime plaster workshop · Winter open day · – · Limewash masterclass · Image no longer in the library (accessible name)"),
st("Columns menu with Thumbnail", N, "Columns. Thumbnail is listed with the image icon.", {"v":"entries","k":"thumbcols"}, "Columns · 4 of 6 · Title · Description · Thumbnail · Starts on · Ends on · Online · Capacity · Category · Reset · Choose up to 6 fields to show. 4 selected."),
st("Missing image: tooltip", N, "Hover or focus on the dashed square (desktop). Mobile has no tooltip.", {"v":"entries","k":"thumbtip"}, "Image no longer in the library")
] }, ] },
{ 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: [ { 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('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'),
@@ -62,7 +72,17 @@ export const groups = [
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('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('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('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') 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'),
st("Media control: empty, optional", N, "Thumbnail follows Description. Empty optional field.", {"v":"entry","k":"m","m":"empty"}, "Thumbnail · No image selected. · Pick an image · One image from your library."),
st("Media control: empty, required", N, "Field marked *.", {"v":"entry","k":"m","m":"emptyreq"}, "Thumbnail * · No image selected. · Pick an image · One image from your library."),
st("Media control: filled", N, "An image is picked.", {"v":"entry","k":"m","m":"filled"}, "Thumbnail · lime-plaster-workshop.jpg · 1600 × 900 · 240 KB · Change image · Remove · One image from your library."),
st("Media control: hover", N, "Pointer over the thumbnail (desktop). The border darkens and a bar reads Change image. Mobile shows the filled state.", {"v":"entry","k":"m","m":"hover"}, "Change image"),
st("Media control: focus", N, "Keyboard focus on the thumbnail: 2 px primary ring, 2 px offset.", {"v":"entry","k":"m","m":"focus"}, "Change image, lime-plaster-workshop.jpg (accessible name)"),
st("Media control: validation error", N, "Save with a required field empty (422 invalid_entry, required). Focus moves to Pick an image.", {"v":"entry","k":"m","m":"err"}, "Pick an image for Thumbnail. · Not saved"),
st("Media control: image no longer in the library", N, "The image was deleted. The entry keeps the link. Optional field: saving is allowed.", {"v":"entry","k":"m","m":"missing"}, "This image is no longer in the library · You can still save. The entry keeps the link until you change it. · Choose another image · Clear"),
st("Media control: missing image, required", N, "Same, on a required field. Save is refused.", {"v":"entry","k":"m","m":"missingreq"}, "This image is no longer in the library · Thumbnail is required. Choose another image to save. · Choose another image · Clear · Pick an image for Thumbnail. · Not saved"),
st("Media control: saving", N, "PUT in flight. The thumbnail and its buttons are disabled with the rest of the form.", {"v":"entry","k":"saving","m":"filled"}, "Saving…"),
st("Media control: read-only, type changed", N, "422 unknown_field. The form is read-only until reloaded.", {"v":"entry","k":"changed","m":"filled"}, "The fields of Events changed · The Thumbnail field was changed after you opened this form. Reload the form to continue. What you typed here can't be saved against the old fields. · Reload form")
] }, ] },
{ 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: [ { 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 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"'),
@@ -77,6 +97,22 @@ export const groups = [
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('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 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') 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')
] },
{ label: '10 Media picker for fields', title: '10 Image picker from the entry editor', route: '/content/events/:id (dialog)', api: 'GET /v1/media/?q=&limit=&cursor= · POST /v1/media/', auth: 'Any verified user', note: "The existing picker (Media picker and Editor picker groups of the back-office board) with Upload and Library tabs, single selection, search and Load more. Changes: the title is \"Choose an image\", the primary button reads \"Use this image\", there is no alt text and no variant select, the current image carries \"Current\" in place of \"In this article\", and \"No image\" tops the Library tab for optional fields only. Desktop dialog, mobile bottom sheet. The page behind is a stand-in for the entry editor.", states: [
st("Library: nothing chosen", N, "Change image on an optional field. Current marks the image in the field.", {"frame":"media","kind":"picker","picker":true,"field":true,"pk":{"tab":"Library","cur":1}}, "Choose an image · Upload · Library · Search by filename · No image · Leave this field empty. · Current · Newest first · 48 images · Load more · Cancel · Use this image (disabled)"),
st("Library: image chosen", N, "One tile selected (single selection). A strip shows filename, dimensions and size. No alt text field.", {"frame":"media","kind":"picker","picker":true,"field":true,"pk":{"tab":"Library","cur":1,"sel":4}}, "kitchen-before.webp · 2400 × 1600 · 1.1 MB · Cancel · Use this image"),
st("Library: No image chosen", N, "Optional fields only. The primary button changes.", {"frame":"media","kind":"picker","picker":true,"field":true,"pk":{"tab":"Library","cur":1,"sel":"none"}}, "No image · Leave this field empty. · Cancel · Remove image"),
st("Library: required field", N, "No \"No image\" row.", {"frame":"media","kind":"picker","picker":true,"field":true,"pk":{"tab":"Library","cur":1,"req":true}}, "Choose an image · Cancel · Use this image (disabled)"),
st("Library: empty", N, "Zero images. Upload an image switches to the Upload tab.", {"frame":"media","kind":"picker","picker":true,"field":true,"pk":{"tab":"Library","empty":"first"}}, "Your library is empty · Images you upload appear here, ready to use in any article or entry. · Upload an image"),
st("Library: failed to load", N, "500 or network failure. Other statuses: see the failures table.", {"frame":"media","kind":"picker","picker":true,"field":true,"pk":{"tab":"Library","error":true}}, "Couldn't load your library · Check your connection and try again. · Try again"),
st("Library: loading", N, "First open or a new search. Skeleton tiles after 150 ms.", {"frame":"media","kind":"picker","picker":true,"field":true,"pk":{"tab":"Library","loading":true}}, "(skeleton) · Use this image (disabled)"),
st("Upload tab", N, "The existing upload flow, including crop and resize. The new image lands in the library and is selected.", {"frame":"media","kind":"picker","picker":true,"field":true,"pk":{"tab":"Upload"}}, "Drop an image here, or choose a file · PNG, JPEG, WEBP, SVG · max 10 MB")
] },
{ label: '11 Media library: usage', title: '11 Media library: usage by entries', route: '/media', api: 'GET /v1/media/ · GET /v1/media/{id}/usage · DELETE /v1/media/{id}', auth: 'Verified users', note: "Same Media screens as the back-office board. Entries count as uses: the \"Used in N\" badge adds articles and entries, its tooltip splits them, and the detail panel gains a \"Used in entries\" list (up to 3 links, then \"and N more\"). Deleting an image that entries use says how many and what the fields will show.", states: [
st("Grid: usage badge tooltip", N, "Hover or focus the \"Used in 3\" badge on bathroom-tiles.png (3 entries, no article).", {"frame":"media","ent":true,"tip":10}, "Used in 3 · Used in entries: 3 · Unused"),
st("List view: usage badge", N, "List view; mobile uses the card rows.", {"frame":"media","ent":true,"view":"list"}, "Used in 3 · Used in 7 · Unused"),
st("Detail panel: used in entries", N, "Click lime-plaster.jpg (2 articles, 5 entries). Right-hand panel; full screen on mobile.", {"frame":"media","ent":true,"panel":{"id":11}}, "Used in 2 articles · Used in entries · Events · Lime plaster workshop · Events · Heritage stone walk · Events · Winter open day · and 2 more"),
st("Delete: image used by entries", N, "Delete in the panel.", {"frame":"media","ent":true,"panel":{"id":11},"modal":{"k":"delEnt"}}, "Delete an image that's in use? · \"lime-plaster.jpg\" is used in 5 entries and 2 articles. Those entry fields will show \"This image is no longer in the library\", and the articles will show a broken image. This can't be undone. · Cancel · Delete image")
] } ] }
] ]
@@ -172,5 +208,7 @@ export const tables = [
['Type picker', 'A radio group. The locked state sets aria-disabled and the line "Can\'t change after saving" is read with the group.'], ['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.'], ['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.'], ['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.']] } ['Touch', 'Controls are 44 px on mobile. The inspector, columns and API preview are bottom sheets.']] },
...mfTables
] ]
+3
View File
@@ -104,3 +104,6 @@ Keys: a type key is 2 to 40 lowercase letters, digits and hyphens (chosen at cre
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"). 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"). 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").
## Media field (pass 5)
Copy and states are in `media-field-changes.md` (sections 2 to 6). Entry rules for a media field: required 422 "Pick an image for Thumbnail."; type 422 "Thumbnail must be an image from the library."; min, max, options and unique do not apply. A required media field added to a type with entries is refused client side in the review ("Can't be applied") and by the server as 409 schema_incompatible. Image deleted while entries use it: the control shows "This image is no longer in the library"; saving is refused only when the field is required. HTTP statuses for the picker and the field use the table above (400, 401, 403, 404, 409, 413, 429, 500, network).
+1 -1
View File
@@ -36,7 +36,7 @@ setting does, so a client holding an old value gets a fresh 200. `Cache-Control`
Every generated file is a blob in `image.Storage` (local directory or S3) plus a row in Every generated file is a blob in `image.Storage` (local directory or S3) plus a row in
`image_variant_files` (variant, source stored name, cached stored name, content type, size, settings `image_variant_files` (variant, source stored name, cached stored name, content type, size, settings
fingerprint). The pair (variant, source) is unique. Concurrent first requests share one generation fingerprint). The pair (variant, source) is unique. Concurrent first requests share one generation
(`singleflight` keyed by variant, settings and source); different variants or different images are (a single-flight group keyed by variant, settings and source); different variants or different images are
generated in parallel. generated in parallel.
Only a stored name that has an image record can be a variant source, so generated files and orphan blobs Only a stored name that has an image record can be a variant source, so generated files and orphan blobs
+1
View File
@@ -41,3 +41,4 @@ Each body lives in `docs/releases/<tag>.md`. Publish with `tea releases create -
| `v3.2.1-beta` | Paged media library and remembered page sizes | | `v3.2.1-beta` | Paged media library and remembered page sizes |
| `v3.3.0-beta` | Sites, authors and search and sharing | | `v3.3.0-beta` | Sites, authors and search and sharing |
| `v3.4.0-beta` | Custom content types | | `v3.4.0-beta` | Custom content types |
| `v3.4.1-beta` | Media field and security updates |
+59
View File
@@ -0,0 +1,59 @@
This release adds a Media field type to custom content types, shows where each image is used, makes merging duplicate images safe against concurrent edits, and replaces or updates dependencies to close known security advisories.
## New
**Media field**
- A custom content type can now have a Media field that holds one image from the media library. The entry stores the image, not a copy, so the field always shows the current library image.
- A Media field has a label, a key and a required switch. It has no default, unique, minimum, maximum or choices, and its type cannot change after the first save.
- In the schema builder, Media is the seventh field type. Adding a required Media field to a type that already has entries is refused in the review step, because such a field cannot have a default.
- In the entry editor, the field shows a thumbnail with Change image and Remove buttons, opens the library picker on click or keyboard, and can upload a new image from the picker's Upload tab. A required field has no "No image" choice.
- When an image was deleted after an entry was saved, the entry keeps the link and the field shows "This image is no longer in the library". An optional field can still be saved, and a required one asks for a new image.
- The entry list gets a Thumbnail column and a thumbnail on mobile cards. It can be added from the Columns menu or shown as the first column.
**Image usage in the media library**
- Entries now count as uses of an image, together with articles, authors and sites. The usage badge, the Unused filter and the unused count all include them.
- Hovering or focusing a usage badge on a card shows how many articles and entries use the image.
- The image detail panel has a "Used in entries" section listing each entry with its content type and title, as a link to the entry.
- Deleting, bulk deleting and merging images now warn with counts of uses, and say what happens to entries that point at the image. Deleting a used image is still allowed and leaves the entries' data untouched.
## Improvements and fixes
- Merging duplicate images is now all-or-nothing. If any step fails, articles, entries and the library are left exactly as they were.
- Stored files are removed only after the merge is committed. A file that cannot be removed afterwards is logged and does not undo the merge.
- A merge no longer overwrites an article or entry edited while it was running. Articles and entries are re-read before they are rewritten, and ones deleted in the meantime are skipped.
- A duplicate purge scans entries once instead of once per group, commits one group at a time, so one failing group no longer undoes the others, and stops cleanly when the request is cancelled.
- Sessions now expire. New sign-in tokens carry a 24 hour expiry, matching the cookie. Sessions created before this release keep working until you sign out.
## API
- Changed: an entry response now has eight keys, the seven existing ones plus `media`. It is an object keyed by Media field key, `{}` when the type has no Media field. Each value is `{ "id", "filename", "width", "height", "size", "thumbnail_url" }` for an existing image, or `{ "id", "missing": true }` when the image is gone. `data` keeps the image id, or `null`, as the field's value. It is on `POST` (201), `PUT` (200), `GET` one and every item of the list.
- `POST /v1/content-type` and `PUT /v1/content-type/{key}` accept fields of type `media`. A Media field with `unique`, `default`, `min`, `max` or `options` answers `422` `invalid_field`.
- `POST` and `PUT` on `/v1/content-type/{key}/entry` check that a new or changed image id exists in the library, otherwise `422` `invalid_entry: <key>: type`. A required Media field that is empty, or whose stored image is gone, answers `422` `invalid_entry: <key>: required`.
- Changed: `used_in` on `GET /v1/media/` and `GET /v1/media/{id}` now includes entries, and `filter=unused` and `counts.unused` treat an image used by an entry as used.
- Changed: `GET /v1/media/{id}/usage` also returns items of type `entry`, with `id`, `fields`, `content_type_key`, `content_type_name` and `first_field` (`key`, `type` and the raw stored `value`). They follow the article, author and site items, ordered by content type name and then id. Existing item shapes are unchanged.
- Merging duplicates, by hand or through the purge, now repoints entry Media values to the kept image.
## Under the hood
- Seven direct and twelve indirect Go modules are gone. Sign-in tokens, SMTP delivery, `.env` loading, CORS, request logging and the image-variant single-flight group are now small in-repo implementations on the standard library, with tests. The removed modules are `jwtauth`, `lestrrat-go/jwx`, `gomail`, `httplog`, `godotenv`, `go-chi/cors` and `x/sync/singleflight`, and the dependencies they pulled in.
- Every remaining Go module is updated, and the Go toolchain moves to 1.27.3. `govulncheck` reports no vulnerability reachable from the code, where it found thirteen in the standard library and several in `golang.org/x/net` and `chi` before.
- Web dependencies are updated, which clears all but three dev-only audit findings. `npm-run-all2` is removed, and `bun run build` now runs the type check and then the build.
- A transaction port in the domain lets use cases commit several writes together, with a GORM adapter that works on SQLite, MySQL, MariaDB and PostgreSQL.
- 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.
- No schema change and no new environment variable. A Media field is stored in the existing content type and entry tables.
- `.env` files no longer expand `$VARIABLES` and do not support multi-line values. A malformed line now makes the file ignored, and the server logs the line number. Real environment variables still take precedence.
- If you build the image yourself, the Go base image is now `golang:1.27.3-alpine`.
- SMTP now fails with a clear error when a login is set but the server offers no authentication, where it used to continue without logging in. Credentials are never sent in clear text to a host other than localhost.
- `CORS_ALLOWED_ORIGINS` also accepts one `*` per entry, for example `https://*.preview.example.com`, and a lone `*` for any origin. Credentials are never allowed cross-origin.
## Known limitations
- A Media field holds one image. Galleries are not supported.
- Entries still cannot be filtered or searched by their field values, and there are no relations between types.
- The editor preview of a Media field uses the original image, with no variant choice.
+2 -2
View File
@@ -39,7 +39,7 @@ Feature: Owners and admins define custom content types, and users manage entries
And a field response has exactly the keys key, label, type, required, unique, default, min, max, 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 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, 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 created_at, updated_at, media, where content_type is the type's key
And errors are plain text from http.Error, and the new apperr strings are 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, 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 invalid_content_type_key, invalid_field, schema_incompatible, entry_not_found and invalid_entry
@@ -201,7 +201,7 @@ Feature: Owners and admins define custom content types, and users manage entries
When the client sends POST /v1/content-type/recipe/entry with body When the client sends POST /v1/content-type/recipe/entry with body
{"data": {"title": "Pad thai", "difficulty": "easy"}} {"data": {"title": "Pad thai", "difficulty": "easy"}}
Then the response status is 201 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 the body has exactly the keys id, content_type, data, created_by, updated_by, created_at, updated_at, media
And content_type is "recipe", created_by and updated_by are 2 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 is {"title": "Pad thai", "difficulty": "easy", "servings": 4, "vegetarian": false}
And data has no "published_on" and no "notes" key And data has no "published_on" and no "notes" key
+296
View File
@@ -0,0 +1,296 @@
Feature: Media field usage in the Media library
As an owner, admin or verified user managing the media library
I want to see which entries use an image and be warned before deleting it
So that I know what an image is used for and what a delete will break
Background:
Given the SPA calls the API with relative URLs under /v1 and the "jwt" HttpOnly cookie
And API errors are plain text
And this slice changes only web/ (and web/visual); the backend of features/media_field_type.feature is done and not touched
And the design is docs/design/media-field-changes.md section 3.8 and section 4, with the board group "11 Media library: usage" (4 states) of "RenewCMS Screens Schema.dc.html", which draws MediaFrame.dc.html with entries counted as uses
And GET /v1/media/ items carry "used_in", which counts articles, authors, sites and entries together, and no split
And GET /v1/media/{id}/usage answers an array ordered articles, authors, sites, then entries by content type name then entry id, with no total and no "first few" wrapper
And an article item is {"type":"article","id","title","published","fields"}
And an entry item is {"type":"entry","id","fields","content_type_key","content_type_name","first_field":{"key","type","value"}} with no title and no published, and first_field absent when the type has no first field
And the SPA keeps the first 3 entry items, counts the rest, and derives the entry title from first_field with the title rules of the entry list (see "Entry title in the usage lists")
And deleting a used image stays allowed; entries keep the id and show "This image is no longer in the library"
And the usage badge, panel and dialog never branch on the role; the Media page is the same for every user who reaches it
And sentence case, "image" and never "asset", buttons are verbs
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
And decisions D1 to D12 of this slice are listed in the QA procedure header and in the conversation
And out of scope: filtering the library by media-field use, the read-only view of a custom type, any change to the Go API
Scenario Outline: The label of the usage badge
Given an image with used_in <used_in>
Then the badge reads "<badge>"
Examples:
| used_in | badge |
| 0 | Unused |
| 1 | Used in 1 |
| 3 | Used in 3 |
| 7 | Used in 7 |
Scenario: The badge counts articles and entries together
Given bathroom-tiles.png has used_in 3 (0 articles, 3 entries) and lime-plaster.jpg has used_in 7 (2 articles, 5 entries)
Then the grid card, the list row and the mobile card of bathroom-tiles.png read "Used in 3" and those of lime-plaster.jpg read "Used in 7"
And the badge is the outline kind of MediaBadge, without an icon, as today
Scenario: Tooltip for entries only (design "Grid: usage badge tooltip")
Given bathroom-tiles.png has 0 articles and 3 entries, and a desktop viewport
When the pointer rests on the badge "Used in 3"
Then GET /v1/media/10/usage is sent once
And a tooltip (--ui-bg-inverted, --ui-text-inverted, 12/18, 6 px 8 px padding, below the badge, left aligned) reads on one line "Used in entries: 3"
Scenario: Tooltip for articles and entries
Given lime-plaster.jpg has 2 articles and 5 entries, and a desktop viewport
When the pointer rests on the badge "Used in 7"
Then the tooltip reads "Used in articles: 2" on the first line and "Used in entries: 5" on the second
Scenario: Tooltip for articles only
Given north-wall.jpg has 2 articles and 0 entries, and a desktop viewport
When the pointer rests on the badge "Used in 2"
Then the tooltip reads "Used in articles: 2" and no "Used in entries" line shows
Scenario: Tooltip opens on keyboard focus
Given a desktop viewport
When the keyboard focus reaches the card (grid) of an image that is used
Then the same tooltip opens, and it closes on blur or Escape without closing anything else
And the focus ring of the card is unchanged
Scenario: The usage is fetched once per image
Given the tooltip of image 10 was opened once
When the user hovers it again, or opens its detail panel
Then no second GET /v1/media/10/usage is sent while the list is not reloaded
And a reload of the list (search, filter, sort, page, retry) clears the cached usage
Scenario: The tooltip waits for the usage
Given GET /v1/media/10/usage has not answered
Then no tooltip shows and the badge keeps its label
When it answers and the pointer or focus is still on the badge
Then the tooltip opens
Scenario Outline: The tooltip never shows without a useful split
Given the pointer rests on the badge of an image and GET /v1/media/{id}/usage <outcome>
Then no tooltip shows and nothing else changes
Examples:
| outcome |
| answers 500 |
| fails on the network |
| answers 404 |
| answers only authors and sites |
Scenario: No tooltip on mobile
Given a 390 px viewport
Then no tooltip opens on tap and the badge is read inside the card as "Used in 3"
Scenario: No tooltip on an unused image
Given an image with used_in 0
Then the badge "Unused" has no tooltip and no usage request is sent for it
Scenario Outline: The accessible name of a card (proposed copy)
Given an image "north-wall.jpg", 3.9 MB, with used_in <used_in>
Then the card button is named "<name>"
Examples:
| used_in | name |
| 0 | north-wall.jpg, 3.9 MB, unused |
| 1 | north-wall.jpg, 3.9 MB, used in 1 place |
| 7 | north-wall.jpg, 3.9 MB, used in 7 places |
Scenario: The list table column (design "List view: usage badge", written spec 3.8)
Given a desktop viewport and the list view
Then the "Used in" column of a used image is the underlined button "Used in 3" that opens the detail panel, as the "N articles" button does today
And an image with used_in 0 shows the "Unused" badge
And the mobile card shows the "Used in 3" badge and the existing meta line
Scenario: Panel for an image used by articles and entries (design "Detail panel: used in entries")
Given lime-plaster.jpg has 2 articles and 5 entries, whose first three entries are Events "Lime plaster workshop", Events "Heritage stone walk" and Events "Winter open day"
When the user opens its panel
Then the preview is 16:10 on desktop and 16:3.6 on mobile only when usage holds at least one entry, and 16:10 and 4:3 otherwise
And the section "Used in 2 articles" lists the two articles with title, Online or Draft and the arrow-up-right icon, as today, with the note "Counted from the text of your articles each time you open this page."
And below it the section "Used in entries" (600 14/22, 8 px gap) holds a bordered list of 3 rows, then the row "and 2 more" in the muted colour, with a muted top border and no link
And each entry row is 36 px high on desktop and 48 px on mobile and holds, left to right, the content type name in 12 px muted (52 px wide, one line, ellipsis), the entry title as a link in weight 500 underlined (one line, ellipsis) and the arrow-up-right icon (14 px, muted)
And the link of a row goes to /content/events/<id> in the same tab
Scenario Outline: Counts in the "Used in entries" section
Given an image whose usage holds <entries> entry items
Then the section shows <rows> rows and <more>
Examples:
| entries | rows | more |
| 1 | 1 | no "and N more" row |
| 3 | 3 | no "and N more" row |
| 4 | 3 | the row "and 1 more" |
| 5 | 3 | the row "and 2 more" |
| 120 | 3 | the row "and 117 more" |
Scenario: Entries only, no article
Given bathroom-tiles.png has 3 entries and 0 articles
When the user opens its panel
Then the articles heading reads "Not used in any article"
And the line under it reads "No article shows it." and never "This image is safe to delete."
And the section "Used in entries" follows
Scenario: Articles only
Given north-wall.jpg has 2 articles and 0 entries
Then the panel is unchanged from before this slice and shows no "Used in entries" section
Scenario: Nothing uses the image
Given window-frame.jpg has used_in 0
Then the panel reads "Not used in any article" and "This image is safe to delete. No article shows it."
And no usage request is sent
Scenario: Authors and sites only (decision D7)
Given an image with used_in 2 and a usage that holds one author and one site
Then the articles heading reads "Not used in any article"
And the line reads "No article shows it." and no "safe to delete" claim is made
And no authors or sites are listed
Scenario: The articles heading counts articles only
Given lime-plaster.jpg has used_in 7 (2 articles, 5 entries)
Then the heading reads "Used in 2 articles" and never "Used in 7 articles"
Scenario: Entry link keyboard and focus
Given the panel of lime-plaster.jpg is open
Then Tab reaches the articles links, then the entry links, in reading order
And an entry link has the 2 px --ui-primary focus ring with a 2 px offset
And "and 2 more" is not a stop
Scenario: Usage loading in the panel (decision D6)
Given GET /v1/media/11/usage has not answered
Then after 150 ms a skeleton of three rows shows under the heading "Used in" (proposed copy)
And before 150 ms nothing shows in the section
And Copy URL, Rename and Delete stay enabled
When it answers
Then the real sections replace the skeleton
Scenario Outline: Usage failure in the panel (decision D5)
Given the panel of an image with used_in 7 is opened
When GET /v1/media/{id}/usage <outcome>
Then <result>
Examples:
| outcome | result |
| answers 500 | the section reads "Couldn't load where this image is used." (proposed copy) with the ghost button "Try again", and Delete stays enabled |
| fails on the network | the same |
| answers 429 | the same |
| answers 404 | the existing gone flow: the panel closes and "That image no longer exists" shows |
| answers 401 | the global redirect, no local copy |
Scenario: Try again in the panel
Given the usage failure is shown
When the user activates "Try again"
Then only GET /v1/media/{id}/usage is sent again and the sections replace the message
Scenario: Switching images while the usage is loading
Given the panel of image 10 is waiting for its usage
When the user opens image 11
Then the answer of image 10 is ignored and the panel shows only image 11 data
Scenario Outline: Entry title from first_field
Given an entry item with id 42 and first_field {"key":"title","type":"<type>","value":<value>}
Then the row title reads "<title>"
Examples:
| type | value | title |
| text | "Lime plaster workshop" | Lime plaster workshop |
| text | "" | Entry 42 |
| text | null | Entry 42 |
| richtext | "## Heritage walk\n\nMeet at 9" | the first line as richTextFirstLine gives it (not the Markdown marks of the whole body) |
| richtext | "" | Entry 42 |
| number | 1500 | 1,500 (as the entry list formats a number) |
| number | 0 | 0 |
| boolean | true | Yes |
| boolean | false | No |
| date | "2026-11-21" | the entry list date format of 2026-11-21 |
| select | "Workshop" | Workshop |
| media | 7 | Entry 42 |
| media | null | Entry 42 |
Scenario: first_field is absent or unknown
Given an entry item with id 42 and no first_field, or a first_field of an unknown type
Then the row title reads "Entry 42" for no first_field and the String of the value for an unknown type, as describeCell does for the default case
Scenario: Long titles and long type names (decision D4)
Given an entry title of 120 characters and the type name "Press mentions and partner coverage"
Then both stay on one line with an ellipsis, the row height does not change, the title link keeps the full title as its accessible name and a native title attribute, and "and N more" is unaffected
Scenario: The order of the three rows
Given the API returns entries ordered by content type name then entry id
Then the three kept rows keep that order and the SPA does not sort again
Scenario: Delete an image used by entries and articles (design "Delete: image used by entries")
Given lime-plaster.jpg has 2 articles and 5 entries and the user activates Delete in its panel
Then the confirm dialog (ConfirmDialog, tone danger) titled "Delete an image that's in use?" opens
And its description reads "\"lime-plaster.jpg\" is used in 5 entries and 2 articles. Those entry fields will show \"This image is no longer in the library\", and the articles will show a broken image. This can't be undone."
And the body holds, in this order, the bordered "Used in entries" list (heading "Used in entries", 3 rows, then "and 2 more") and the bordered list of the 2 articles with title and Online or Draft
And the buttons are "Cancel" and the destructive "Delete image"
And the entry rows show the type name and the title and are not links in the dialog (decision D10)
Scenario Outline: The wording by what uses the image
Given an image "lime-plaster.jpg" with <articles> articles and <entries> entries in its loaded usage
Then the title is "<title>"
And the description reads <description>
Examples:
| articles | entries | title | description |
| 2 | 5 | Delete an image that's in use? | "lime-plaster.jpg" is used in 5 entries and 2 articles. Those entry fields will show "This image is no longer in the library", and the articles will show a broken image. This can't be undone. |
| 1 | 1 | Delete an image that's in use? | "lime-plaster.jpg" is used in 1 entry and 1 article. Those entry fields will show "This image is no longer in the library", and the articles will show a broken image. This can't be undone. |
| 2 | 0 | Delete an image that's in use? | "lime-plaster.jpg" is used in 2 articles. If you delete it, they will show a broken image. This can't be undone. |
| 0 | 3 | Delete an image that's in use? | "lime-plaster.jpg" is used in 3 entries. Those entry fields will show "This image is no longer in the library". This can't be undone. (proposed copy) |
| 0 | 0 | Delete this image? | "lime-plaster.jpg" will be deleted from your library. No article uses it. This can't be undone. (used_in is 0) |
Scenario: Delete an unused image
Given window-frame.jpg has used_in 0
Then the dialog is titled "Delete this image?" with the unchanged copy, no lists and no usage request
Scenario: Delete an image used only by authors or sites
Given used_in 2 and a usage with no article and no entry
Then the existing in-use title shows with the generic fallback description of the next scenario
Scenario: The usage is not ready when the dialog opens (decision D6)
Given the user activates Delete before GET /v1/media/{id}/usage answered, or after it failed
Then the dialog is titled "Delete an image that's in use?" because used_in is above 0
And the description reads "\"lime-plaster.jpg\" is in use. Articles will show a broken image and entry fields will show \"This image is no longer in the library\". This can't be undone." (proposed copy)
And no lists show, "Delete image" is enabled, and when the usage answers while the dialog is open the dialog switches to the full copy and lists without moving the focus
Scenario: Confirm and results
Given the delete dialog is open
When the user activates "Delete image"
Then DELETE /v1/media/<id> is sent and the existing in-progress, failed, done and 404 states run unchanged
And on 204 the toast "Image deleted" / "\"lime-plaster.jpg\" is gone from your library." shows and the focus moves to the next item
Scenario: Cancel and Escape
When the user activates "Cancel" or presses Esc
Then nothing is deleted and the focus returns to the Delete button of the panel
Scenario: The variants note is kept
Given an image with cached variants and used by entries
Then the existing variant removal note still shows under the lists
Scenario: Mobile dialog
Given a 390 px viewport
Then the dialog is a bottom sheet, the entry rows are 48 px high and the buttons are 44 px high
Scenario: Bulk delete counts uses, not articles (proposed copy)
Given 3 images are selected, 2 of them used for 7 places in total (articles and entries)
Then each row keeps its badge "Used in N" or "Unused"
And the description counts "7 places" in the sentence where it said "7 articles" and reads "which will show a broken image or a missing-image notice." instead of "which will show a broken image."
And no usage request is sent for the bulk dialog
Scenario: Merge counts uses, not articles (proposed copy)
Given a merge group whose other copies have used_in 5 and 2
Then the dialog says "7 places will be updated" and "Kept · used in N places now"
And the toast after the merge keeps "N copies merged. M articles updated." from articles_updated
Scenario: Accessibility of the usage UI
Then the tooltip is exposed with aria-describedby on its trigger and uses role "tooltip"
And the entry title link is named "<title>, <content type name>" (proposed)
And "and 2 more" is plain text read in order
And the arrow-up-right icon is aria-hidden
And a skeleton or error line in the panel is inside the section so a screen reader reads it after the heading
And the delete dialog moves focus to "Cancel" as it does today, and its lists are read after the description
And mobile targets are 44 px, with rows of 48 px, and there is no hover on mobile
+101
View File
@@ -0,0 +1,101 @@
# QA: Media field usage in the Media library (slice C)
Runner: Vitest + Vue Test Utils (`task test:web`). No Go test and no Go change: the usage API is covered by features/media_field_type.qa.md. Kit: extend the Media view test kit with
- the library list (`GET /v1/media/?page=&size=&q=&filter=` with `items`, `total`, `counts`);
- `GET /v1/media/{id}/usage` fixtures:
- image 10 `bathroom-tiles.png`: 3 entries (Events), `used_in` 3;
- image 11 `lime-plaster.jpg`: 2 articles ("Open day at the workshop" online, "Restoring lime plaster" draft) plus 5 Events entries (first three: first_field text "Lime plaster workshop", "Heritage stone walk", "Winter open day"), `used_in` 7;
- image 1 `north-wall.jpg`: 2 articles, `used_in` 2;
- image 8 `window-frame.jpg`: `used_in` 0;
- an author-and-site-only image, `used_in` 2;
- entry items of every `first_field.type`, plus items with no `first_field`;
- failures: 500, network, 429, 404, 401.
Pin the time zone; never freeze the system date. No state of this slice depends on the clock.
Decisions accepted by the user (all as the feature draft assumes):
- D1 split source for the tooltip: lazy `/usage` fetch, SPA-only.
- D2 wording of the card name and the table column: "used in N places", underlined "Used in N" button.
- D3 title derivation: reuse `describeCell` and `plainCellText`.
- D4 truncation: one line, ellipsis, native title.
- D5 usage failure: inline message with "Try again" in the panel, silent tooltip.
- D6 usage loading: skeleton after 150 ms, delete dialog opens at once with a generic description.
- D7 authors and sites in the usage: filtered out, heading counts articles only.
- D8 bulk delete: "N places".
- D9 merge: "N places".
- D10 entry rows in the delete dialog are not links.
- D11 mobile panel as drawn.
- D12 visual gate setup.
## Automated
Pure logic (lib/__tests__, it.each over the feature's Examples):
1. `splitUsage(items)`: articles are those with `type === 'article'`, entries those with `type === 'entry'`, authors and sites are counted by neither. Entry rows keep API order, the first 3 are kept, `more` is the rest (0, 1, 2, 117). An absent array gives zeros.
2. `usageEntryTitle(item)`: the table "Entry title from first_field" for text, richtext (empty and Markdown), number (0 and 1500), boolean, date, select, media and null, empty string, absent first_field and an unknown type (falls to the default case of `describeCell`). It reuses `describeCell` and `plainCellText`; no second title rule exists. `entryTitle` itself is unchanged and its existing specs pass untouched.
3. Wording helpers: pluralEntries ("1 entry", "5 entries"), usage description by case (articles+entries, singular forms, articles only unchanged, entries only, usage unavailable fallback), `usedInLabel` for the card name ("used in 1 place", "used in 7 places", "unused").
4. Tooltip lines: entries only gives one line, both gives articles first, articles only gives one line, authors or sites only gives none.
MediaCardBadges, MediaTable, MediaGrid, MediaCardList (components/__tests__):
5. Badge label for used_in 0, 1, 3, 7. Outline kind, no icon. Same label in the grid card, the list row (underlined button in the table, badge in the mobile card) and the mobile card.
6. Tooltip: hover on the badge (`pointerenter`) fetches `/usage` once and opens with the right lines for the three splits; focus on the grid card opens it; Escape and blur close it without closing the panel; no fetch for `used_in` 0; no tooltip on mobile (viewport helper 390); nothing opens while the request is pending, and it opens on answer if the pointer is still there; failures (500, network, 404, authors-only) leave no tooltip; the usage is cached per image and cleared on reload of the list.
7. Card `aria-label`: the three names of the feature, replacing the "used in 2 articles" assertions in the existing specs; update those specs and change nothing else in them.
8. Table: the "Used in" cell is the underlined button "Used in N" (`data-testid="media-used-in"` kept) that opens the panel; "Unused" badge at 0.
MediaDetailPanel (components/__tests__/MediaDetailPanel.spec.ts, views/__tests__/MediaView*.spec.ts):
9. Articles and entries: heading "Used in 2 articles" built from the articles of the usage, not from `used_in`; article rows unchanged; "Used in entries" heading and 3 rows with type name, title link to `/content/<key>/<id>` and the arrow icon; "and 2 more" as plain text; the counts table (1, 3, 4, 5, 120 entries); row heights 36 px (desktop) and 48 px (mobile) as classes.
10. Entries only: heading "Not used in any article" with "No article shows it."; articles only: no entries section and the panel as before; unused: "safe to delete" line and no `/usage` request; authors and sites only: "No article shows it." and no list.
11. Preview aspect: 16:10 desktop and 4:3 mobile without entries, 16:6 desktop and 16:3.6 mobile with entries (classes, after the usage answers).
12. Loading: nothing before 150 ms, the three-row skeleton after, the real sections after the answer; fake timers only for the 150 ms delay, never the date. Failure: 500, network and 429 show "Couldn't load where this image is used." with "Try again" that repeats only `/usage`; 404 runs the existing gone flow; 401 is left to the global redirect; Delete stays enabled; switching images ignores the late answer.
13. Long title and long type name: one line, ellipsis classes, native title attribute on the link, row height unchanged.
14. Focus and tab order: article links, then entry links; the ring classes on a link; "and 2 more" not focusable.
DeleteMediaDialog (components/__tests__/DeleteMediaDialog.spec.ts):
15. The description table (2/5, 1/1, 2/0, 0/3, 0/0), the title for in use vs unused, the body order (entries list with heading and "and 2 more", then the articles list), the buttons, the variants note kept, no link in the entry rows.
16. Usage not ready (pending, failed): the generic description, no lists, "Delete image" enabled; when the usage answers while open the copy and lists switch and the focus stays.
17. Delete flow (confirm, in progress, failed, done, 404) runs unchanged; Cancel and Esc return focus to the Delete button of the panel.
BulkDeleteMediaDialog and MergeMediaDialog:
18. Bulk description counts "places" and uses "which will show a broken image or a missing-image notice."; rows and badges unchanged; no `/usage` request.
19. Merge dialog says "N places will be updated" and "Kept · used in N places now"; the toast stays "N copies merged. M articles updated.".
Cross-cutting:
20. French: every new string has an entry (the i18n completeness spec passes).
21. Regression: the existing Media view specs pass unchanged except the assertions named in 7, 18 and 19; if any other spec needs an edit, stop and report.
## Visual (task visual:check -- media)
In scope: the 4 states of the board group "11 Media library: usage" of RenewCMS Screens Schema.dc.html (they draw MediaFrame, and the copy list gives them the sample data). Every capture must be within 10 %, desktop and mobile, light and dark. Out of scope: states whose setups exist already and whose data does not change (they must keep passing untouched), and the picker states of slice B.
Prerequisites in web/visual, no change under docs/design (decision D12):
- `check.ts`: add the source `{ board: 'RenewCMS Screens Schema.dc.html', group: '11 Media library: usage', states: [the four below] }` to `extraSources.media`. The group differs from the screen's primary group ("Media"), so no merge change is needed.
- `states.ts`: the four setups, with the media API mock extended by `GET /v1/media/10/usage` and `GET /v1/media/11/usage` (shapes above). Existing media states keep their data, so `used_in` stays articles-only there.
- Board data:
- image 10 bathroom-tiles.png, 3 entries, `used_in` 3;
- image 11 lime-plaster.jpg, 2 articles and 5 entries, `used_in` 7;
- the grid also holds an unused image, so "Unused" shows in the captures.
| Board state | Setup in web/visual/states.ts | Board sample data |
|---|---|---|
| Grid: usage badge tooltip | /media with ent counts; step: hover the badge of image 10 (desktop), wait for the tooltip; mobile shows the grid with no tooltip | "Used in 3", tooltip "Used in entries: 3", "Unused" |
| List view: usage badge | /media?view=list; desktop table, mobile cards | "Used in 3", "Used in 7", "Unused" |
| Detail panel: used in entries | step: open image 11; wait for the entries list | "Used in 2 articles", "Used in entries", Events + "Lime plaster workshop", "Heritage stone walk", "Winter open day", "and 2 more" |
| Delete: image used by entries | step: open image 11, activate Delete; wait for the lists | the title, the description of 5 entries and 2 articles, both lists, "Cancel", "Delete image" |
Board caveats to report, never hide:
- The desktop table of the board draws `usedLink` with `pl(im.used)` (articles only). It shows "N articles" for lime-plaster.jpg and "Unused" for bathroom-tiles.png, while the written spec 3.8 says the list row carries the same badge. The spec follows the written text (D2); if the desktop capture of "List view: usage badge" exceeds 10 % the exception needs the user's explicit approval (`approvedBy`).
- The board draws the entry rows in the delete dialog as underlined links with the arrow icon; the spec renders plain rows (D10). If a capture exceeds 10 %, report it before changing the choice.
- The tooltip is drawn at a fixed place (left aligned, 26 px below the badge); a Nuxt UI tooltip may centre it. Use the `align` and offset that match the frame.
- The board titles ("Lime plaster workshop") come from the setup's `first_field` values, not from a title field.
- Clock-sensitive: none of the four states shows a relative date.
## Manual
- Real backend, owner and a second verified user: upload an image, use it in an article and in two entries through a Media field, and read "Used in 3" in the grid, list and mobile card. Hover and focus the badge for the tooltip, and check that a card with no entries shows "Used in articles: N" only.
- Open the panel: the entries link opens /content/<key>/<id> and shows the right entry. Add a fourth entry and read "and 1 more". Delete the entry and reload: counts fall.
- Delete the image from the panel with the dialog open: read the real counts, confirm, then open one of the entries and see "This image is no longer in the library" with the id kept.
- Throttle or kill the network while opening the panel and the dialog: the error line, "Try again" and the generic delete description.
- An image used only by an author or a site: no "safe to delete" claim anywhere.
- Keyboard: tab order across card, badge tooltip (focus), panel links and dialog buttons; Escape closes the tooltip first, then the panel; the focus return after Cancel; screen reader reads the card name, the tooltip and the lists.
- Motion and hover: the tooltip opening and closing, the skeleton fade at 150 ms, no layout jump larger than the preview change when the usage answers.
- Mobile: the full-screen panel, 48 px rows, the bottom-sheet dialog, 44 px targets, no tooltip.
- Contrast of the tooltip pair and of the muted type name in light and dark.
+492
View File
@@ -0,0 +1,492 @@
Feature: Media field type in the SPA
As an owner or admin building a content type, and as a verified user filling an entry
I want a Media field that holds one image from the media library
So that entries link to a library image and always show its current version
Background:
Given the SPA calls the API with relative URLs under /v1 and the "jwt" HttpOnly cookie
And API errors are plain text
And this slice changes only web/ (and web/visual); the backend of features/media_field_type.feature is done
And the design is docs/design/media-field-changes.md sections 1, 2, 3.2 to 3.7, 4, 6 and 7, with the board groups 2 Schema builder, 3 Review and delete, 4 Field types, 5 Content and entry list, 6 Entry editor and 10 Media picker for fields of "RenewCMS Screens Schema.dc.html"
And the registry is lib/fieldTypes with lib/entryEditors, the single source for the builder, the list cells and the entry form; no screen branches on the type name "media" where a registry property can say it
And a media value is the id of a library image (a uint32 of at least 1) or null
And every entry answer (POST 201, PUT 200, GET one, each list item) carries a top-level "media" object keyed by media field key: {"id","filename","width","height","size","thumbnail_url"} for an existing image, or {"id","missing":true} when the image is gone; a null value has no key
And the API refuses with 422 "invalid_entry: <key>: required" or "invalid_entry: <key>: type", 409 "schema_incompatible" for a new required media field on a type with entries, and 422 "invalid_field" for forbidden options
And the picker is the existing ImageUploader with MediaPicker, loading GET /v1/media/?page=&size=&q= with the total in the "counts" and "total" fields as the article picker does; the Sites, Authors, SEO and article pickers are unchanged
And the picker in field mode never requests /v1/image-variants and never shows the variant select or the alt text
And the form dimming stays the entry form's 70 % (design conflict 12, existing rule kept); inside the control the thumbnail drops to 60 % and the buttons take the disabled look
And sentence case, "image" and never "asset", buttons are verbs
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
And user decisions already taken: Apply is disabled for the certain refusal; thumbnail after Description in schema order; "Clear"; "1600 × 900 · 240 KB"; "Use this image" and "Remove image"; "Pick an image" on optional fields; row heights 48 and 68
And out of scope (slice C): "Used in" badge, usage panel and delete warning of the Media library, the read-only view of a custom type, filtering by media
Scenario Outline: Media in the registry
Given the registry entry for "media"
Then <property> is <value>
Examples:
| property | value |
| type name in the API | media (the seventh entry, after select) |
| label | Media |
| description | One image from your media library |
| icon | lucide:image |
| control | MediaFieldControl |
| pairs with a neighbour | no, full width (as text, richtext and select) |
| empty value | null |
| initial on create | null; a media field has no default, so no "Default" tag ever shows |
| initial on edit | the stored id, or null |
| supports unique | no |
| supports limits | no |
| supports default | no |
| supports choices | no |
| counter | none |
| help | One image from your library. |
| list cell | thumbnail, column 80 px, not right-aligned, not sortable |
| sample in the API preview | null |
Scenario Outline: Client validation of a media value
Given a media field "Thumbnail" that is <required>
When the value is <value>
Then the rule is <rule>
Examples:
| required | value | rule |
| required | null | required |
| required | undefined | required |
| optional | null | none |
| optional | 7 | none |
| required | 7 | none |
| optional | 0 | type |
| optional | -1 | type |
| optional | 7.5 | type |
| optional | "7" | type |
| optional | true | type |
| optional | 4294967296 | type |
Scenario Outline: Messages of a media field
Given a media field labelled "Thumbnail"
Then the message of the rule <rule> reads <message>
Examples:
| rule | message |
| required | Pick an image for Thumbnail. |
| type | Thumbnail must be an image from the library. |
| min | not produced for media |
| max | not produced for media |
| options | not produced for media |
| unique | not produced for media |
Scenario: A loaded media field is not shown as Text
Given GET /v1/content-type/events returns a field {"key":"thumbnail","label":"Thumbnail","type":"media","required":false,"unique":false,"default":null,"min":null,"max":null,"options":[]}
Then the builder, the entry form and the list resolve it to the media entry of the registry, never to the fallback type "text"
# ---------- Schema builder (groups 2 and 4)
Scenario: Seven type tiles
Given the inspector of a field that can still change type
Then seven radio tiles are shown in this order, 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 |
| Media | image | One image from your media library |
And the grid has 3 columns in the desktop inspector and 2 in the mobile sheet
Scenario: Adding a media field (design "New media field, seven types")
Given Events with 7 saved fields and 37 entries
When the user activates "Add field", types the label "Thumbnail" and chooses the tile "Media"
Then the new row shows the badge "New", the key "thumbnail" (Auto, editable) with the help "The name used in the API. Starts with a letter. Lowercase letters, digits and underscores."
And the seven tiles are all enabled with Media selected and the legend "Type" has no lock
And the chip reads "Unsaved changes"
And the row is: grip, a 28 px square holding the image icon, the label, the key in mono and the badge "New"
Scenario: The inspector of a media field shows only what applies (design "Media field selected")
Given Events with a saved optional media field "Thumbnail" as its eighth field
When the user selects the row "Thumbnail"
Then the inspector reads "Field: Thumbnail" and holds, in this order, the Label input, the locked Key "thumbnail" with "Used in the API, so it can't change.", the Type tiles, the switch "Required" with "An entry can't be saved with this field empty." and the hint block
And the legend of the tiles reads "Type" with a lock and "Can't change after saving", Media is selected and the six other tiles are dimmed to 40 % and not selectable
And the hint block is info-soft with an info icon and reads "Holds one image from the media library. Entries link to the image instead of keeping a copy, so they always show its current version."
And "Unique values", "Default value", the limit inputs, the "Limits" heading and the choice list are not rendered at all
Scenario: Changing a new row to and from Media
Given a new row of type Text, required, with a Longest of 80
When the user chooses the tile "Media"
Then the label, the key and Required are kept and unique, default, limits and choices are reset
When the user then chooses the tile "Number"
Then the media hint is gone and the number controls show with no stale value
Scenario: A required media field (design "Media field, required")
Given a saved media field "Thumbnail" that is required
Then its row carries the existing Required marker "R" (accessible name "Required") next to the key
And its inspector shows Required switched on
Scenario: The PUT and POST body of a media field
Given a media field with the label "Thumbnail", the key "thumbnail" and Required off
When the type is saved
Then the field is sent as {"key":"thumbnail","label":"Thumbnail","type":"media","required":false,"unique":false,"default":null,"min":null,"max":null,"options":[]}
And a round trip of the loaded field to the payload produces no change
Scenario: Media in the API preview
Given the builder holds a media field "Thumbnail"
Then the sample entry shows "thumbnail": null and no "Example text"
Scenario: The mobile sheet of a media field
Given a 390 px viewport
When the user selects the row "Thumbnail"
Then the 92 % sheet titled "Field: Thumbnail" shows the same inspector in one column with the type tiles in 2 columns and the footer button "Done"
Scenario: The field-type gallery (group 4) has no SPA screen
Then the registry facts above are covered by the registry scenarios and no route renders the gallery frame
# ---------- Review (group 3)
Scenario: A required media field added to a type with entries is refused first (design "Review: required media field refused")
Given Events with 12 entries and a new media field "Thumbnail" that is required
When the user activates Save
Then no PUT is sent
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 1 field" and "Events has 12 entries. Each one is checked against the new fields when you apply."
And the row "Add Thumbnail" has the warning badge "Can't be applied" and the text "Media, required. A media field can't have a default, so the 12 existing entries would have no image. Make Thumbnail optional to add it."
And the note "Back to editing keeps your other changes." shows instead of the "Flagged changes can be refused..." note
And "Back to editing" is enabled and "Apply changes" is disabled (aria-disabled), so pressing it sends nothing
Scenario: The refusal is only for a new required media field with entries
Given Events with <entries> entries and the edit <edit>
When the user activates Save
Then <result>
Examples:
| entries | edit | result |
| 12 | adds Thumbnail, Media, optional | the review opens, "Apply changes" is enabled |
| 12 | adds Thumbnail, Media, required | the review opens, "Apply changes" is disabled |
| 0 | adds Thumbnail, Media, required | no review, the PUT is sent at once |
| 12 | makes the saved optional media field Thumbnail required | the review opens, row "Change Thumbnail" "Now required." flagged "Entries may not fit", Apply enabled; the server decides |
| 12 | adds Thumbnail required and changes Capacity | both rows listed, Apply disabled |
Scenario Outline: The clean row (design "Review: optional media field")
Given Events with <entries> entries and a new optional media field "Thumbnail"
Then the row "Add Thumbnail" reads "<text>" with no flag
And "Apply changes" is enabled
Examples:
| entries | text |
| 12 | Media, optional. 12 entries are unaffected. |
| 1 | Media, optional. 1 entry is unaffected. (proposed copy) |
Scenario: Back to editing after the refusal
Given the refused review is open
When the user chooses "Back to editing" (or presses Esc or the close icon)
Then the dialog closes, every edit is kept and no request was sent
When the user turns Required off on the new row and activates Save
Then the review opens with the clean row and "Apply changes" enabled
Scenario: The refusal follows offline and applying
Given the refused review is open
Then "Apply changes" stays disabled whatever the connection
And with a clean review, "Apply changes" is still disabled while offline, as before
Scenario: The server refuses anyway
Given the entry count was stale and the client opened no refusal
When the PUT answers 409 "schema_incompatible"
Then the existing "Nothing was changed" refusal flow of features/schema_builder_edit.feature runs unchanged
Scenario: 422 invalid_field on a media field
Given the PUT answers 422 "invalid_field"
Then the existing invalid-field failure of the builder is shown and the edits stay
# ---------- MediaFieldControl in the entry editor (group 6)
Scenario: Where the control sits
Given Events with the fields Title, Starts on, Ends on, Online, Capacity, Category, Description and Thumbnail
Then the control for Thumbnail is the eighth, after Description, full width in the 760 px column, and the footer lines come after it
Scenario: Empty, optional (design "Media control: empty, optional")
Given /content/events/new, or an entry whose thumbnail is null
Then the label reads "Thumbnail"
And a dashed box (1 px, border-accented, padding 12) holds a 40 px square with the image icon, the text "No image selected." and the outline button "Pick an image" with the image-plus icon
And the help line reads "One image from your library."
And on mobile the box stacks and the button is 44 px high
Scenario: Empty, required (design "Media control: empty, required")
Given the field is required
Then the label reads "Thumbnail *" with the asterisk hidden from assistive technology, and the rest is as the empty state
Scenario: Filled (design "Media control: filled")
Given an entry whose thumbnail is 7 and media.thumbnail is {"id":7,"filename":"lime-plaster-workshop.jpg","width":1600,"height":900,"size":245760,"thumbnail_url":"/media/lime-plaster-workshop.jpg"}
Then a solid 1 px box (border-accented, padding 12) holds a 160 × 120 thumbnail button showing thumbnail_url, the filename in weight 500, "1600 × 900 · 240 KB" in 12/18 muted, the outline button "Change image" (image icon) and the ghost button "Remove" (x icon)
And the help line reads "One image from your library."
And on mobile the thumbnail is full width at 16:9 and the two buttons are full width and 44 px high
And a width or height of null (a vector image) reads "Vector · 8 KB"
Scenario: Hover (design "Media control: hover")
Given the filled state on desktop
When the pointer is over the thumbnail
Then the box border takes the --ui-text-muted colour and a 28 px bar at the bottom of the thumbnail (--ui-bg-inverted, --ui-text-inverted) reads "Change image" with the image icon at 14 px
And mobile has no hover state and shows the filled state
Scenario: Focus (design "Media control: focus")
Given the filled state
When the keyboard focus reaches the thumbnail button
Then it has a 2 px --ui-primary outline with a 2 px offset
Scenario: Pointer and keyboard open the picker
Given the filled state
When the user activates the thumbnail, "Change image", or on an empty control "Pick an image"
Then the picker opens in field mode and nothing else changes
Scenario: Remove
Given the filled state
When the user activates "Remove"
Then the value becomes null, the control shows the empty state and the chip reads "Unsaved changes"
And the live region says "Image removed from Thumbnail." and the focus is on "Pick an image"
Scenario: Missing image, optional (design "Media control: image no longer in the library")
Given media.thumbnail is {"id":7,"missing":true} and the field is optional
Then the box is solid with a dashed 160 × 120 placeholder (16:9 on mobile) holding image-off at 24 px, with role "img" and the name "Image no longer in the library"
And beside it "This image is no longer in the library" in weight 500, the help "You can still save. The entry keeps the link until you change it." in 12/18 muted, the outline button "Choose another image" and the ghost button "Clear"
And there is no help line under the box
And "Save" is allowed and the data sent keeps thumbnail 7
Scenario: Clear
Given the missing state
When the user activates "Clear"
Then the value becomes null, the live region says "Thumbnail cleared." and the focus is on "Pick an image"
Scenario: Missing image, required (design "Media control: missing image, required")
Given media.thumbnail is {"id":7,"missing":true} and the field is required
Then the in-box help reads "Thumbnail is required. Choose another image to save."
And when the user saves, no request is sent, the box takes the error border, the line "Pick an image for Thumbnail." shows with a circle-alert icon, the chip reads "Not saved" and the focus is on "Choose another image"
Scenario: Validation error on an empty required field (design "Media control: validation error")
Given an empty required media field
When the user activates "Save"
Then no request is sent
And the box border is --ui-error with an inset 1 px --ui-error, the error line "Pick an image for Thumbnail." with circle-alert at 14 px replaces the help line, and the chip reads "Not saved"
And the focus moves to "Pick an image" and the page scrolls to it
And only the first field in schema order with an error takes the focus
Scenario: Picking clears the error
Given the validation error is shown
When the user picks an image
Then the error and the error border go, the chip reads "Unsaved changes" and nothing else is validated
Scenario: Saving (design "Media control: saving")
Given the PUT has not answered
Then the form is dimmed to 70 %, the thumbnail is at 60 %, the buttons take the disabled look, the thumbnail button and the buttons are not operable and the picker cannot open
And Save reads "Saving…"
Scenario: Read-only after a schema change (design "Media control: read-only, type changed")
Given the PUT answers 422 "invalid_entry: thumbnail: unknown_field" and thumbnail is a media field of the loaded type
Then a warning alert "The fields of Events changed" reads "The Thumbnail field was changed after you opened this form. Reload the form to continue. What you typed here can't be saved against the old fields." with the action "Reload form"
And the control looks as in Saving and cannot be operated
And "Reload form" fetches the type and the entry again and rebuilds the form with the control from the answered media map
And any other key keeps the copy of features/content_entry_editor.feature state 12
Scenario Outline: What the control shows and sends
Given the loaded value <loaded> with media <media>
When the user <action> and activates "Save"
Then the control shows <shown>
And the data holds "thumbnail": <sent>
Examples:
| loaded | media | action | shown | sent |
| null | none | saves with nothing changed | the empty state | null |
| 7 | existing image 7 | saves with nothing changed | the filled state | 7 |
| 7 | missing image 7 (optional) | saves with nothing changed | the missing state | 7 |
| 7 | existing image 7 | picks image 8 | image 8 (its own library data) | 8 |
| 7 | existing image 7 | activates Remove | the empty state | null |
| 7 | missing image 7 | activates Clear | the empty state | null |
| null | none | picks image 8 | image 8 | 8 |
Scenario: Right after a pick the control uses the picked library item
Given the user picks "bathroom-tiles.png" (id 8, 800 × 600, 51200 bytes) from the library
Then before any save the control shows its filename, "800 × 600 · 50 KB" and its url as the thumbnail
And no request is made for it
When the PUT answers 200 with media.thumbnail for image 8
Then the control is rebuilt from the answered media map
Scenario: Dirty tracking of a media value
Given an entry whose thumbnail is 7
When the user picks image 8 then picks image 7 again
Then the chip reads "Saved", "Save" is disabled and the leave guard does not prompt
When the user picks image 8
Then the chip reads "Unsaved changes" and the leave guard prompts
Scenario Outline: Server answers for a media field
Given the client found no error and the PUT or POST is sent
When the server answers <status> "<body>"
Then <result>
Examples:
| status | body | result |
| 422 | invalid_entry: thumbnail: required| "Pick an image for Thumbnail." under the control, error border, chip "Not saved", focus on the first button |
| 422 | invalid_entry: thumbnail: type | "Thumbnail must be an image from the library." under the control, chip "Not saved", focus on "Change image" or "Pick an image" (the image was deleted between the pick and the save) |
| 409 | schema_incompatible | not an entry answer; never produced by the entry routes |
Scenario: Create payload with a media field
Given /content/events/new with Title "Open day", Starts on 2026-11-21 and the media field left empty
When the user activates "Save"
Then POST /v1/content-type/events/entry is sent once with "thumbnail": null among the other keys, never absent
And with image 8 picked it holds "thumbnail": 8, a JSON number
Scenario: The title of an entry whose first field is media
Given a type whose first field is a media field
Then the page title, the breadcrumb and the saved toast read "Entry 42" (an id is not a title) and the list card title reads the same (proposed)
Scenario: Layout of the generated form with a media field
Given a boolean, a number or a date field before the media field
Then the media field never pairs and is full width at every viewport
# ---------- Picker in field mode (group 10)
Scenario: Opening the picker from an optional field (design "Library: nothing chosen")
Given the control holds image 1 "north-wall.jpg" and the field is optional
When the user activates "Change image"
Then the dialog (640 px wide on desktop, a bottom sheet on mobile) is titled "Choose an image" and has the tabs "Upload" and "Library", opening on Library
And the search reads "Search by filename"
And the first row of the Library tab is "No image" with "Leave this field empty."
And the summary reads "Newest first · 48 images", the tiles are square, 4 columns on desktop and 3 on mobile, and "Load more" shows
And the tile of image 1 carries the badge "Current" (sand fill, --rc-on-sand text, 18 px high, bottom left)
And "Cancel" is enabled and "Use this image" is disabled (aria-disabled)
And there is no alt text field, no variant select, and no request to /v1/image-variants
Scenario: Choosing an image (design "Library: image chosen")
When the user selects a tile
Then it gets the primary outline with a check at top right, aria-pressed is true, and a strip appears below the grid with a 56 px thumbnail, the filename and "dimensions · size"
And the grid shrinks and "Load more" is hidden while a tile is selected, as in the article picker
And "Use this image" is enabled
When the user activates it
Then the dialog closes, the value becomes that image's id, the control shows its data, the live region says "Image selected: <filename>" and the focus is on "Change image"
Scenario: Choosing "No image" (design "Library: No image chosen")
When the user selects the row "No image"
Then it takes the sand fill, the primary border and a check, with aria-pressed true, and any selected tile is released
And the primary button reads "Remove image"
When the user activates it
Then the value becomes null, the live region says "Image removed from Thumbnail." and the focus is on "Pick an image"
Scenario: A required field has no "No image" row (design "Library: required field")
Given the field is required
Then the Library tab shows no "No image" row and the title is still "Choose an image"
Scenario: Choosing the current image again
Given the control holds image 1
When the user selects the tile "Current" and activates "Use this image"
Then the dialog closes, the value does not change, the chip stays as it was, and no announcement is made (proposed)
Scenario: Empty library (design "Library: empty")
Given GET /v1/media/ returns no image
Then the picker opens on the Upload tab unless the user already chose a tab, and the Library tab reads "Your library is empty" / "Images you upload appear here, ready to use in any article or entry." with "Upload an image"
And "Upload an image" switches to the Upload tab
And the article picker keeps "Images you upload appear here, ready to use in any article."
Scenario Outline: Library failures (design "Library: failed to load")
Given GET /v1/media/ answers <outcome>
Then <result>
Examples:
| outcome | result |
| 500 | the error alert "Couldn't load your library" / "Check your connection and try again." with "Try again", no "No image" row |
| a network error | the same |
| 429 | the countdown alert of the Media page |
| 401 | the global redirect, no local copy |
Scenario: Try again
Given the failed state
When the user activates "Try again"
Then only GET /v1/media/ is sent again and the grid replaces the alert
Scenario: Loading (design "Library: loading")
Given GET /v1/media/ has not answered
Then after 150 ms skeleton tiles show (8 on desktop, 9 on mobile), no "No image" row shows and "Use this image" is disabled
Scenario: Search and no results
When the user types "wall"
Then the search is trimmed and debounced, the selection is released and the grid reloads
And an empty match reads "No images match \"wall\"" with "Clear search", as in the article picker
Scenario: Load more
When the user activates "Load more"
Then the next page loads, the focus stays on the button until the new tiles arrive and then moves to the first new tile
Scenario: Upload tab (design "Upload tab")
When the user opens the Upload tab
Then the existing flow runs unchanged: "Drop an image here, or choose a file", "PNG, JPEG, WEBP, SVG · max 10 MB", crop and resize, the duplicate check "Already in your library" with "Use existing" and "Upload anyway"
And a finished upload lands in the library and becomes the value of the field, as in the Sites and Authors pickers, then the dialog closes and the live region says "Image selected: <filename>" (to confirm, decision D5)
Scenario Outline: Upload failures keep the existing copy
Given the POST /v1/media/ answers <outcome>
Then <copy> shows and nothing is chosen
Examples:
| outcome | copy |
| 413 | That file is too large. |
| 400 | That request wasn't valid. Check the fields and try again. |
| 429 | Too many requests. Try again in a few minutes. |
| 500 | Something went wrong on our side. Nothing was changed. Try again in a moment. |
Scenario: Cancel and Escape
When the user activates "Cancel" or presses Esc or the close icon
Then nothing changes and the focus returns to the button that opened the picker
Scenario: Tile names in field mode
Then each tile is a button named "stone-steps.jpg, 310 KB" and "stone-steps.jpg, 310 KB, Current" for the current image, with aria-pressed, and no "used in" part
And "No image" is a button with aria-pressed and "Use this image" uses aria-disabled while nothing is chosen
Scenario: The other pickers are unchanged
Then the article picker still reads "Add an image", "Insert image", "In this article", the alt text and the variant select
And the Sites, Authors and SEO pickers still read "Use image" with no strip and no "No image" row
# ---------- Entry list (group 5), minimal safe cell
Scenario: The Thumbnail column (design "Thumbnail column")
Given Events with a Thumbnail media field, the columns Title, Thumbnail, Starts on and Category chosen, and the items 42 and 41 with an existing image, 40 and 37 with null, 39 with a missing image
Then the header reads "Thumbnail" with no sort icon and no aria-sort, in a column 80 px wide
And an existing image shows a 40 px square thumbnail from media.thumbnail_url, with 4 px above and below, so the row stays 48 px
And a null value shows "–" in the muted colour
And a missing image shows a dashed 40 px square with the unlink icon, role "img" and the name "Image no longer in the library"
And the thumbnail is read from the item's own "media" object, with no extra request
Scenario: Tooltip of the missing placeholder
Given a missing image in the list on desktop
When the pointer or the focus reaches the dashed square
Then a tooltip reads "Image no longer in the library"
And mobile has no tooltip
Scenario: The mobile card (design "Thumbnail column", mobile)
Given a 390 px viewport and the Thumbnail column chosen
Then a 32 px thumbnail leads each card, "–" stands for none, a dashed 32 px square for a missing image, and the card keeps its 68 px minimum height
And when no media field is among the chosen columns the card is unchanged
Scenario: Columns menu (design "Columns menu with Thumbnail")
When the user opens "Columns"
Then "Thumbnail" is listed with the image icon, its key "thumbnail", and a checkbox like the other fields
And the summary reads "4 of 6" and on mobile "Choose up to 6 fields to show. 4 selected."
And the cap of 6, Reset and the stored choice work as for any field
Scenario: Thumbnail as the first column
Given a type whose first field is a media field
Then the first column still links to the editor and the thumbnail is the link content
Scenario: Plain text of a media cell
Given the card or a title needs the text of a media cell
Then it reads "–" for none and never the numeric id
# ---------- Accessibility (media-field-changes.md section 6)
Scenario: Accessibility of the control
Then the control is role="group" labelled by the field label
And the main button (Pick an image, or Change image) carries aria-required when the field is required
And the accessible names are "Pick an image for Thumbnail", "Change image, lime-plaster-workshop.jpg, 1600 by 900, 240 KB" (the thumbnail), "Remove image from Thumbnail", "Clear Thumbnail" and, for the placeholder, role "img" "Image no longer in the library"
And the error text has an id, and the main button gets aria-invalid="true" and aria-describedby with the error id then the help id
And the tab order is label, thumbnail, Change image, Remove, then help or error (two stops open the same picker, as drawn; decision D8)
And one polite live region announces "Image selected: lime-plaster-workshop.jpg", "Image removed from Thumbnail." and "Thumbnail cleared."; nothing is announced when the picker opens
And focus goes to the first invalid control on a refused save and, after the picker, to the places of the picker scenarios
And mobile targets are 44 px and there is no hover on mobile
Scenario: Accessibility of the builder and the review
Then the Media tile is a radio in the existing radio group, the dimmed tiles are disabled, "Can't be applied" is a text badge and not only a colour, and the disabled "Apply changes" is announced as disabled
+114
View File
@@ -0,0 +1,114 @@
# QA: Media field type in the SPA (slice B)
Runner: Vitest + Vue Test Utils (`task test:web`). No Go test: the backend is covered by features/media_field_type.qa.md and nothing changes in it. Kit: extend `views/__tests__/schemaTestKit.ts` with the Events type (7 fields, plus Thumbnail as the 8th, optional or required, saved or new), entries whose `data.thumbnail` and top-level `media` vary, the library list (`GET /v1/media/?page=&size=&q=` with `items`, `total`, `counts`), and the plain-text bodies `invalid_entry: thumbnail: required`, `invalid_entry: thumbnail: type`, `invalid_entry: thumbnail: unknown_field`, `schema_incompatible`, `invalid_field`. Library fixtures: 1 "north-wall.jpg", 7 "lime-plaster-workshop.jpg" (1600 × 900, 245760 bytes, shown "240 KB"), 8 "bathroom-tiles.png" (800 × 600, 51200 bytes, "50 KB"), a vector image with null width and height. Pin the time zone; never freeze the system date. No state of this slice depends on the clock.
## Automated
Registry and pure logic (lib/__tests__, it.each over the feature's Examples):
1. Registry `media`: label, description, icon, control, no pairing, empty value, initial on create and edit, no unique, limits, default or choices, counter none, help, cell, API preview sample null. A loaded field of type `media` never resolves to the `text` fallback in the builder, the form or the list. The six existing types still pass every existing registry assertion unchanged (update the count assertions from six to seven).
2. Validation table: required and optional with null, undefined, 7, 0, -1, 7.5, "7", true, 4294967296. A required field whose image is missing is `required` (registry takes the image summary, or the form passes it).
3. Messages for required and type with the label "Thumbnail"; min, max, options and unique are never produced.
4. Payload: id to id, null to null, an optional missing stored id is sent unchanged, never absent. The builder payload of a media field equals `{key,label,type:'media',required,unique:false,default:null,min:null,max:null,options:[]}`; a loaded media field round-trips with no diff.
5. Builder model: `changeFieldType` to and from media resets unique, default, limits and options and keeps label, key and required. Sample preview value is null.
6. Review diff: the add row of a media field, required with total > 0 is flagged "Can't be applied" with the exact text; optional reads "Media, optional. N entries are unaffected." (plural rule for 1); total 0 gives no review; making a saved media field required stays "Now required." with "Entries may not fit". Summary line is unchanged.
7. Entry helpers: `entryTitle` with a media first field gives "Entry N"; `describeCell` and `plainCellText` give "–" for none and never the id; media summary parsing for existing, missing and absent keys; `formatDimensions` and `formatSize` give "1600 × 900" and "240 KB" for 245760 bytes and "Vector" for null dimensions.
Schema builder (views/__tests__/SchemaBuilderMedia*.spec.ts):
8. Seven tiles in order with icon, name and description; 3 columns in the desktop inspector, 2 in the sheet.
9. New media field: "New" badge, key editable with its help, seven tiles enabled, chip "Unsaved changes".
10. Saved media field: key locked with its help, legend lock and "Can't change after saving", six tiles dimmed and unselectable, hint block copy, Required switch and copy, and that "Unique values", "Default value", limit inputs, "Limits" heading and choice list are absent from the DOM.
11. Required marker on the row; row anatomy (28 px image square, label, key, badges).
12. Mobile sheet: title "Field: Thumbnail", footer "Done", one column.
13. Save paths: PUT and POST bodies; 422 invalid_field and 409 schema_incompatible keep their existing flows.
Review (views/__tests__/SchemaBuilderMediaReview.spec.ts):
14. Refusal: dialog copy, summary, row, badge, note "Back to editing keeps your other changes.", Apply `aria-disabled` and a click sends no PUT; Back to editing, Esc and close keep the edits and send nothing; turning Required off then Save shows the clean row with Apply enabled.
15. The table of the feature (entries 12 and 0, optional and required, changed to required, mixed with a Capacity change); Apply stays disabled offline in both reviews.
16. A stale count: PUT 409 `schema_incompatible` runs the existing refusal flow.
MediaFieldControl (components/__tests__/MediaFieldControl.spec.ts), one test per state and viewport (components/__tests__/viewport.ts for 1440 and 390):
17. Empty optional and required: structure, copy, " *" hidden from AT, help line, 44 px button on mobile.
18. Filled: thumbnail 160 × 120 (full width 16:9 on mobile), filename, "1600 × 900 · 240 KB", buttons and icons, help line; vector image reads "Vector".
19. Hover bar on desktop only (`pointerenter` on the thumbnail), absent on mobile; focus ring classes on the keyboard-focused thumbnail.
20. Error: border classes, error line replaces help, aria-invalid and aria-describedby order (error id, help id), focus on "Pick an image" or "Choose another image".
21. Missing optional and required: placeholder role img and name, copy, no help line under the box, buttons.
22. Saving and read-only: form 70 %, thumbnail 60 %, buttons disabled, picker cannot open.
23. Events: emits `update:modelValue` with the id or null for pick, "Remove image" choice, Remove and Clear; announcements in one polite live region; focus targets after Use this image (Change image), Remove, Clear and "Remove image" (Pick an image), and after Cancel and Esc (the opener).
24. Names and role: group labelled by the label, the exact accessible names, aria-required on the main button, two tab stops as drawn.
Entry editor (views/__tests__/EntryEditorMedia*.spec.ts):
25. Position after Description, full width, never pairs; form built from the type with Thumbnail.
26. The table "What the control shows and sends" (it.each): loaded value and media map to shown state and PUT body.
27. After a pick the control shows the picked library item's data with no request; after the PUT it is rebuilt from the answered `media`; after "Reload form" from the refetched entry.
28. Dirty tracking: pick 8 then 7 is clean; pick 8 is dirty and the leave guard prompts.
29. Client validation: required empty and required missing give no request, "Not saved" chip, focus and scroll on the first error in schema order; picking clears the error; optional missing saves with the id unchanged.
30. Server answers: 422 required and type map to the control with their messages and focus; 422 `unknown_field` on a media key shows the "The Thumbnail field was changed..." line, other keys keep the state 12 copy of features/content_entry_editor.feature; create payload `thumbnail: null` and `thumbnail: 8`.
31. Title of an entry whose first field is media: "Entry N" in title, breadcrumb, toast and list card.
Picker field mode (components/__tests__/ImageUploaderField.spec.ts, views/__tests__/EntryEditorPicker.spec.ts):
32. Title, tabs, search, "No image" row on optional only and never on required, empty, error and loading states; "Current" badge replaces "In this article"; tile names with and without ", Current"; aria-pressed on tiles and on "No image"; no alt field, no variant select, and no `/v1/image-variants` request.
33. Selection: strip with 56 px thumbnail, filename and "dimensions · size"; Load more hidden while selected; "Use this image" `aria-disabled` until a choice; "Remove image" when No image is chosen; selecting a tile releases No image and the reverse; selecting the Current tile then Use closes with no change and no announcement.
34. Library states: empty (field copy with "or entry", and the article copy unchanged), 500 and network failure with Try again repeating only GET /v1/media/, 429 countdown alert, 401 global, loading skeleton after 150 ms (8 and 9 tiles), search trimmed and debounced, no results, Load more focus move.
35. Upload tab: unchanged flow including the duplicate card; a finished upload becomes the field value (per decision D5) and announces "Image selected: ..."; the four upload failure copies.
36. Dialog 640 px wide on desktop, bottom sheet on mobile; Cancel, Esc and close return focus to the opener.
37. Regression: the article picker and the Sites, Authors and SEO pickers keep their copy and behavior (run their existing specs unchanged; if one needs an edit, stop and report).
Entry list (components/__tests__/FieldCell.spec.ts, EntryTable, EntryCardList, ColumnPicker):
38. Thumbnail, "–" and missing cells: size 40 px, 4 px margins, row height 48 px, role img and name on the placeholder, tooltip on desktop only, `alt` of the thumbnail (proposed: the filename).
39. Header "Thumbnail": no sort icon, no `aria-sort`, 80 px; mobile card with a 32 px leading thumbnail and the 68 px minimum height, unchanged when no media column is chosen.
40. Columns menu: Thumbnail listed with the image icon and its key; "4 of 6" and the cap behaviour; stored choice in localStorage.
41. No extra request for thumbnails; a first media column still links to the editor.
Cross-cutting:
42. French: every new string has an entry (the i18n completeness spec passes, including the files added to the list in `i18n/contentMessages.spec.ts` if any).
43. Existing specs that assert six types or six tiles are updated to seven and nothing else in them changes.
## Visual (task visual:check)
Prerequisites in web/visual, no change under docs/design:
- `check.ts`: states of the board groups 5 and 6 that the design markdown does not list (`Thumbnail column`, `Columns menu with Thumbnail`, `Missing image: tooltip`; the ten `Media control: ...` states) must be added to the screens `content` and `entry`. Today `extraSources` entries whose group equals the screen's primary group are dropped (decision D3), so the runner must be changed to merge them. Groups 2 and 3 (screen `schema`) and group "10 Media picker for fields" (add to `extraSources.entry`, board RenewCMS Screens Schema.dc.html) are plain `extraSources` additions. Group 4 "Media" is a reference gallery with no SPA route: no setup, covered by Vitest. Group 1 "Custom type: read-only view" and group 11 are slice C.
- `states.ts`: Events gets an eighth field Thumbnail (media) in `schemaEventsFields` variants for these states only, so existing states keep their 7 fields. Image URLs (`thumbnail_url`, library `url`) are fulfilled by the setup with an SVG stand-in drawing the board's placeholder (repeating-linear-gradient 135deg between --ui-bg-elevated and --ui-bg-accented, mono label "1600 × 900"), as `stubBoardImage` does for the picker. The media size is 245760 bytes so `formatSize` prints "240 KB". Sidebar calls stay mocked. Every capture within 10 %, desktop and mobile, light and dark.
| Board group, state | Setup in web/visual/states.ts | Board sample data |
|---|---|---|
| 2, Media field selected | /schema/events, Events + saved optional Thumbnail, 37 entries; step: open the row "Thumbnail" | row "Thumbnail", key "thumbnail", "Field: Thumbnail", "Used in the API, so it can't change.", "Can't change after saving", tiles Text to Media, hint "Holds one image from the media library. ..." |
| 2, New media field, seven types | /schema/events (7 saved fields); step: Add field, label "Thumbnail", click tile Media | "New" badge, key "thumbnail" help "The name used in the API. ...", seven tiles, chip "Unsaved changes" |
| 2, Media field, required | /schema/events, saved Thumbnail required; step: open its row | marker "R" on the row, "Required" switch on with "An entry can't be saved with this field empty." |
| 3, Review: required media field refused | 12 entries (`total: 12`); step: add Thumbnail, Media, Required on, Save | "Review changes to Events", "Add 1 field", "Events has 12 entries. ...", "Add Thumbnail", "Can't be applied", "Media, required. A media field can't have a default, so the 12 existing entries would have no image. Make Thumbnail optional to add it.", "Back to editing keeps your other changes.", Apply disabled |
| 3, Review: optional media field | same with Required off | "Add Thumbnail", "Media, optional. 12 entries are unaffected.", Apply enabled |
| 5, Thumbnail column | /content/events; localStorage `renewcms-content-columns-events` = ["title","thumbnail","starts_on","category"]; the 7 standard rows 42, 41, 40, 39, 38, 37, 36 with thumbnail ok, ok, none, missing, ok, none, ok | header "Thumbnail", 40 px thumbnails, "–" on 40 and 37, dashed unlink square on 39; mobile 32 px leading thumbnail |
| 5, Columns menu with Thumbnail | same storage; step: click "Columns" | "Columns", "4 of 6", Thumbnail with the image icon, "Choose up to 6 fields to show. 4 selected." (mobile) |
| 5, Missing image: tooltip | step: hover the dashed square of row 39 (desktop); mobile has no tooltip and shows the list | "Image no longer in the library" |
| 6, Media control: empty, optional | /content/events/42 with thumbnail null; Events with Thumbnail | "Thumbnail", "No image selected.", "Pick an image", "One image from your library." |
| 6, Media control: empty, required | Thumbnail required, thumbnail null | "Thumbnail *", same body |
| 6, Media control: filled | thumbnail 7, media {id 7, "lime-plaster-workshop.jpg", 1600, 900, 245760} | "lime-plaster-workshop.jpg", "1600 × 900 · 240 KB", "Change image", "Remove", help |
| 6, Media control: hover | filled; step: hover the thumbnail (desktop); mobile is the filled frame | bar "Change image" |
| 6, Media control: focus | filled; step: Tab to the thumbnail (keyboard, so :focus-visible) | 2 px primary ring, name "Change image, lime-plaster-workshop.jpg" |
| 6, Media control: validation error | Thumbnail required, thumbnail null; step: click Save | "Pick an image for Thumbnail.", chip "Not saved", focus on "Pick an image" |
| 6, Media control: image no longer in the library | optional, media {id 7, missing true} | "This image is no longer in the library", "You can still save. The entry keeps the link until you change it.", "Choose another image", "Clear" |
| 6, Media control: missing image, required | required, missing; step: click Save | "Thumbnail is required. Choose another image to save.", "Pick an image for Thumbnail.", "Not saved", focus on "Choose another image" |
| 6, Media control: saving | filled; step: edit Title, Save, PUT `hang: true` | "Saving…", thumbnail at 60 % |
| 6, Media control: read-only, type changed | filled; step: edit Capacity, Save, PUT 422 `invalid_entry: thumbnail: unknown_field` | "The fields of Events changed", "The Thumbnail field was changed after you opened this form. Reload the form to continue. What you typed here can't be saved against the old fields.", "Reload form" |
| 10, Library: nothing chosen | /content/events/42 (control holds image 1 "north-wall.jpg", optional); step: click "Change image"; library = the board's 12 images, counts.all 48 | "Choose an image", "Upload", "Library", "Search by filename", "No image", "Leave this field empty.", "Current" on north-wall.jpg, "Newest first · 48 images", "Load more", "Cancel", "Use this image" (disabled) |
| 10, Library: image chosen | step: select the 4th tile (the frame draws id 4 logo-renew.svg, "Vector · 8 KB"; the copy list says kitchen-before.webp, report the mismatch) | strip with filename, "dimensions · size", "Use this image" enabled |
| 10, Library: No image chosen | step: click the row "No image" | sand row with check, "Remove image" |
| 10, Library: required field | Thumbnail required | no "No image" row, "Use this image" disabled |
| 10, Library: empty | `GET /v1/media/` returns no item | "Your library is empty", "Images you upload appear here, ready to use in any article or entry.", "Upload an image" |
| 10, Library: failed to load | `GET /v1/media/` 500 | "Couldn't load your library", "Check your connection and try again.", "Try again" |
| 10, Library: loading | `GET /v1/media/` `hang: true`; wait for the skeleton tile | skeleton tiles, "Use this image" disabled |
| 10, Upload tab | step: click the tab "Upload" | "Drop an image here, or choose a file", "PNG, JPEG, WEBP, SVG · max 10 MB" |
Board caveats to report, never hide:
- The group 6 media states draw the form with a negative margin (-380 px desktop, -560 px mobile) under an intact title row inside an overflow-hidden box. A real page can only scroll as a whole, so the title row and topbar will differ. If a capture exceeds 10 %, an exception needs the user's explicit approval (`approvedBy`), as for existing schema states. Do not call `schemaSettle` after scrolling to the control, since it resets scrollTop.
- Group 10 draws a stand-in entry form behind the dialog (design conflict 13), not the real editor. Expect a possible exception request for the page behind the dialog.
- The frame and the copy list disagree on "Library: image chosen" (see above) and on the list row titles of "Thumbnail column"; the frame wins.
- Group 6 "Saved" is not checked here; the existing entry setups are untouched.
## Manual
- Real backend, owner and a second verified user: create a type with a required Title and an optional Thumbnail; add an entry with an image; the thumbnail shows in the editor and in the list; change the image; remove it; save.
- Delete the image from the Media page, reload the entry: the missing state, then save with the optional field kept (the id is sent unchanged); make the field required through a type with no entries and see "Pick an image for Thumbnail." on save.
- Add a required Thumbnail to a type with entries: the review refuses with Apply disabled; make it optional and apply (real PUT 200). Make an existing optional media field required while an entry has none: real 409, then the existing refusal flow.
- Upload from the Upload tab of the picker with crop and resize, and an already-in-library duplicate; confirm the final selection behaves as decided in D5.
- Keyboard: tab order across the control (thumbnail, Change image, Remove), Enter and Space on a tile, Esc and Cancel return focus to the opener, focus after Use this image, Remove and Clear; screen reader announcements of the live region and of the error; contrast of the Current badge and the hover bar in light and dark.
- Mobile: bottom sheet, 44 px targets, no hover.
+269
View File
@@ -0,0 +1,269 @@
Feature: Media field type for custom content types
As a site owner or admin
I want a content type field that holds one image from the media library
So that entries link to the library image instead of keeping a copy
Background:
Given internal/domain/contenttype adds the field type "media" next to text, richtext, number, boolean, date and select
And a media field accepts only label, key and required; unique, default, min, max and options are refused with ErrInvalidField
And a stored media value is the id of a library image (uint32, at least 1) or null
And the entry rules required and type apply to a media field; min, max, options and unique never apply
And entry.Validate stays pure; the check that an image exists in the library is done by CreateEntry and UpdateEntry through the domain image.Repository
And CreateEntry, UpdateEntry, GetEntry and ListEntries receive image.Repository, wired only in api/dependecyInjection.go
And a changed value means a value that is not equal to the id the entry holds in the stored document for that key; on POST every non-null value is changed; on PUT the value is unchanged only when the id equals the stored one
And a changed or new non-null value must be an existing library image, else 422 "invalid_entry: <key>: type"
And an unchanged stored id whose image was deleted since passes the type check
And a required media field is never saved empty: null or absent gives 422 "invalid_entry: <key>: required", and so does an unchanged stored id whose image no longer exists
And rules are checked in field order for Validate, then library existence in field order, then unique, and the body names one field per answer
And an entry response keeps its seven keys (id, content_type, data, created_by, updated_by, created_at, updated_at) and adds the key "media"
And data keeps the image id (or null) as the value of each media field
And "media" is a JSON object keyed by media field key, always present ({} when the type has no media field or every media value is null)
And "media"[key] is {"id","filename","width","height","size","thumbnail_url"} for an existing image, with width and height null when unknown, or {"id","missing":true} when the image is gone
And thumbnail_url is the image's original path, the same value as the url of a media list item
And the same "media" object is on POST 201, PUT 200, GET one and every item of the list
And usage in the library means distinct articles, authors, sites and entries; one entry counts once however many of its media fields point at the image
And GET /v1/media/ and GET /v1/media/{id} items carry used_in = articles + authors + sites + entries, and the counts.unused filter counts entries as uses
And GET /v1/media/{id}/usage stays a JSON array and gains items of type "entry"
And an entry usage item is {"type":"entry","id":<entry id>,"fields":[<media field keys>],"content_type_key":"event","content_type_name":"Events","first_field":{"key":<key>,"type":<field type>,"value":<raw stored value or null>}}, with no "title" and no "published"
And first_field is the first field of the type in schema order and its value is the raw stored JSON value, never formatted or truncated by the server; the client formats it with the same rule as the entry list and shows "Entry N" for null
And article, author and site usage items are unchanged and keep their "title"
And usage items are ordered articles by id, authors, sites, then entries by content type name then entry id; the array has no cap and the client shows the first few and the total
And the media routes keep their access rules and their plain-text errors (404 image_not_found, 400 uint32 format)
And DELETE /v1/media/{id} stays allowed for an image used by entries and leaves their data untouched
And MergeMedia (including the purge run) repoints entry media values from every merged copy to the kept image and reports it in the existing counts
And no repository method is added: entries that reference an image are found with contenttype.Repository.List and entry.Repository.ListPage (Unpaged), filtered in Go, so the code works on SQLite, MySQL/MariaDB and PostgreSQL with no JSON operators
And schema compatibility does not consult the library
And the key set assertions of the earlier custom content type and entry features and tests are amended from seven keys to eight
And types: the library images are 7 "lime-plaster.jpg" 1600x900 240000 bytes, 8 "bathroom-tiles.png" 800x600 51200 bytes; the type "event" has title (text, required) then thumbnail (media, label "Thumbnail", optional)
And users: admin id 2 (verified) can write types; any verified user can write entries
Scenario: Creating a content type with a media field
Given a valid jwt cookie for admin 2
When the client sends POST /v1/content-type with fields title (text, required) and {"key":"thumbnail","label":"Thumbnail","type":"media","required":false,"unique":false,"default":null,"min":null,"max":null,"options":[]}
Then the response status is 201
And the thumbnail field comes back with type "media", unique false, default null, min null, max null and options []
Scenario Outline: A media field refuses options it can't have
Given a valid jwt cookie for admin 2
When the client sends POST /v1/content-type with a media field that has <option>
Then the response status is 422
And the response body is "invalid_field"
And no content type is stored
Examples:
| option |
| unique true |
| default 7 |
| default "lime" |
| min 1 |
| max 5 |
| options ["a"] |
Scenario: The type of a saved media field never changes
Given the type "event" has an entry and a saved media field "thumbnail"
When admin 2 sends PUT /v1/content-type/event turning "thumbnail" into a text field
Then the response status is 422 with invalid_field and the schema is unchanged
When admin 2 sends PUT turning the text field "title" into a media field
Then the response status is 422 with invalid_field and the schema is unchanged
Scenario Outline: Adding a media field to a type that has entries
Given the type "event" has 12 entries
When admin 2 sends PUT /v1/content-type/event adding a media field "thumbnail" that is <required>
Then the response status is <status>
And the response body is <message>
And the stored schema is <outcome>
Examples:
| required | status | message | outcome |
| required | 409 | schema_incompatible | unchanged |
| optional | 200 | | updated |
Scenario: Making a media field required
Given the type "event" has a saved optional media field "thumbnail", one entry with image 7 and one entry with null
When admin 2 sends PUT making "thumbnail" required
Then the response status is 409 with schema_incompatible
When the entry holding null is deleted and the PUT is sent again
Then the response status is 200
Scenario: Making a media field required while a stored image is gone
Given the type "event" has a saved optional media field "thumbnail" and one entry holding the id of a deleted image
When admin 2 sends PUT making "thumbnail" required
Then the response status is 200
Scenario: Creating an entry with an image
Given a valid jwt cookie for admin 2
When the client sends POST /v1/content-type/event/entry with {"data":{"title":"Lime plaster workshop","thumbnail":7}}
Then the response status is 201
And data.thumbnail is 7
And media is {"thumbnail":{"id":7,"filename":"lime-plaster.jpg","width":1600,"height":900,"size":240000,"thumbnail_url":"<the image path>"}}
Scenario Outline: An empty optional media field
When the client sends POST /v1/content-type/event/entry with <data>
Then the response status is 201
And data.thumbnail is <stored>
And media is {}
Examples:
| data | stored |
| {"data":{"title":"A","thumbnail":null}} | null |
| {"data":{"title":"A"}} | absent |
Scenario Outline: Entry values that break a media field are refused and store nothing
Given the type "event" has a media field "thumbnail" that is <required>
When the client sends POST /v1/content-type/event/entry with <data>
Then the response status is 422
And the response body is <message>
And no entry exists
Examples:
| required | data | message |
| required | {"data":{"title":"A"}} | invalid_entry: thumbnail: required |
| required | {"data":{"title":"A","thumbnail":null}} | invalid_entry: thumbnail: required |
| optional | {"data":{"title":"A","thumbnail":999}} | invalid_entry: thumbnail: type |
| optional | {"data":{"title":"A","thumbnail":"7"}} | invalid_entry: thumbnail: type |
| optional | {"data":{"title":"A","thumbnail":0}} | invalid_entry: thumbnail: type |
| optional | {"data":{"title":"A","thumbnail":-1}} | invalid_entry: thumbnail: type |
| optional | {"data":{"title":"A","thumbnail":7.5}} | invalid_entry: thumbnail: type |
| optional | {"data":{"title":"A","thumbnail":4294967296}} | invalid_entry: thumbnail: type |
| optional | {"data":{"title":"A","thumbnail":true}} | invalid_entry: thumbnail: type |
| optional | {"data":{"title":"A","thumbnail":[7]}} | invalid_entry: thumbnail: type |
Scenario: Replacing the image of an entry
Given the entry 5 of type "event" holds thumbnail 7
When a verified user sends PUT .../entry/5 with {"data":{"title":"Lime plaster workshop","thumbnail":8}}
Then the response status is 200, data.thumbnail is 8 and media.thumbnail.filename is "bathroom-tiles.png"
When the user sends PUT with thumbnail null on an optional field
Then data.thumbnail is null and media is {}
Scenario: An image deleted after the entry was saved
Given the entry 5 holds thumbnail 7
When DELETE /v1/media/7 answers 204
And the client sends GET /v1/content-type/event/entry/5
Then data.thumbnail is still 7
And media is {"thumbnail":{"id":7,"missing":true}}
Scenario: An unchanged id whose image is gone can still be saved when the field is optional
Given the entry 5 holds thumbnail 7 and the image 7 was deleted
When the user sends PUT .../entry/5 with a new title and thumbnail 7
Then the response status is 200 and data.thumbnail is 7
And media.thumbnail is {"id":7,"missing":true}
Scenario Outline: A changed value must exist even when the old one is gone
Given the entry 5 holds thumbnail 7 and the image 7 was deleted
When the user sends PUT .../entry/5 with thumbnail <value>
Then the response status is <status> and the body is <message>
Examples:
| value | status | message |
| 999 | 422 | invalid_entry: thumbnail: type |
| 8 | 200 | |
| null | 200 | |
Scenario Outline: A required media field with a missing image can't be saved as is
Given the entry 5 of a type whose "thumbnail" is required holds thumbnail 7 and the image 7 was deleted
When the user sends PUT .../entry/5 with thumbnail <value>
Then the response status is <status> and the body is <message>
And the stored entry is <outcome>
Examples:
| value | status | message | outcome |
| 7 | 422 | invalid_entry: thumbnail: required | unchanged |
| null | 422 | invalid_entry: thumbnail: required | unchanged |
| 8 | 200 | | updated |
Scenario: A create always treats the value as changed
Given the image 7 was deleted
When the client sends POST with thumbnail 7
Then the response status is 422 with invalid_entry: thumbnail: type
Scenario: Two broken fields name only one
Given a body with a required field left empty and a media field pointing at a missing image
When the client sends POST
Then the response names one field, with the required and type rules of Validate checked before the library existence
Scenario: Entry list responses carry the media object per item
Given 3 entries: one with image 7, one with image 7 deleted, one with null
When the client sends GET /v1/content-type/event/entry
Then each item keeps its seven keys and adds "media"
And the items' media are one existing object, {"thumbnail":{"id":7,"missing":true}} and {}
And items, total, page and size are unchanged
Scenario: Types without a media field are not enriched
Given the type "recipe" has no media field
When the client sends GET on a recipe entry
Then the body has the seven existing keys and "media" is {}
And the image repository is not called
Scenario: Media list items count entries as uses
Given the image 8 is used by 3 entries (one of them through two media fields) and by no article, author or site
And the image 7 is used by 2 articles and 5 entries
When the client sends GET /v1/media/
Then item 8 has used_in 3 and item 7 has used_in 7
And GET /v1/media/8 has used_in 3
And ?filter=unused does not list 8 or 7, and counts.unused does not count them
Scenario: Usage of an image lists articles and entries
Given the image 7 is used by article 12 "Heat pumps" (cover) and by entries 41, 42 and 43 of "event" and entry 9 of "workshop"
When the client sends GET /v1/media/7/usage
Then the response status is 200 and the body is a JSON array
And the article item is {"type":"article","id":12,"title":"Heat pumps","published":true,"fields":["cover"]}
And the entry items follow in the order event 41, 42, 43, then workshop 9 (content type name, then id), each with exactly type, id, fields ["thumbnail"], content_type_key, content_type_name and first_field, and no title and no published
And a client counts the array for the total
Scenario Outline: The raw first field in usage
Given an entry whose first field "<key>" is of type <type> and holds <stored>
When the client reads the usage of an image the entry uses
Then the entry item first_field is {"key":"<key>","type":"<type>","value":<value>}
And no string is built by the server and the item has no "title" key
Examples:
| key | type | stored | value |
| title | text | "Lime plaster workshop" | "Lime plaster workshop" |
| body | richtext | "\n\nFirst line\n\nSecond" | "\n\nFirst line\n\nSecond" |
| seats | number | 18 | 18 |
| category | select | "Talk" | "Talk" |
| online | boolean | false | false |
| starts_on | date | "2026-11-21" | "2026-11-21" |
| title | text | null | null |
| title | text | the key absent | null |
| cover | media | 7 | 7 |
Scenario: Usage of an unused or unknown image
When the client sends GET /v1/media/8/usage with no use
Then the body is []
When the client sends GET /v1/media/999/usage
Then the response status is 404 with apperr.ImageNotFoundErrorMessage
When the client sends GET /v1/media/abc/usage
Then the response status is 400 with apperr.IdUint32ErrorMessage
Scenario: Deleting an image used by entries is allowed
Given the image 7 is used by 5 entries and 2 articles
When the client sends DELETE /v1/media/7
Then the response status is 204
And the 2 articles lose the image reference as today
And the 5 entries still hold data.thumbnail 7 and are not modified (updated_at and updated_by unchanged)
Scenario: Merging duplicates repoints entry media
Given the images 7 and 9 share the same sha256 and entries 41 and 42 point at 9
When the client sends POST /v1/media/merge with keep_id 7 and merge_ids [9]
Then the response status is 200
And entries 41 and 42 hold thumbnail 7, with created_by, updated_by and updated_at unchanged
And image 9 no longer exists
Scenario: A failure while repointing entries stops the merge
Given the entry repository fails on the second Update
When the client sends POST /v1/media/merge
Then the response status is 500, the entries already repointed are restored, and no image is removed
Scenario: The purge plan counts entries as uses
Given the duplicate group 7, 9 where only 9 is used (by 1 entry)
When the purge preview and the purge run
Then 9 is the kept image and 7 is the merged copy
Scenario: Use case level
Given fake contenttype, entry and image repositories
Then entry.Validate returns an error satisfying errors.Is(err, entry.ErrInvalidEntry) with Key "thumbnail" and Rule "required" or "type" for the shapes above
And CreateEntry and UpdateEntry return the same for a missing library image and perform no Create or Update
And UpdateContentType returns contenttype.ErrSchemaIncompatible for a new required media field and does not call Update
And contenttype.ValidateFields returns contenttype.ErrInvalidField for a media field with unique, default, min, max or options
+59
View File
@@ -0,0 +1,59 @@
# QA procedure: media field type (slice A, API only)
Package: `test` (black-box). No live server, no real SQLite file, no real SMTP, no SPA.
## Setup shared by every case
1. Call `validator.InitValidator()` once per test.
2. Reuse the fakes of the custom content type pair (`mockContentTypeRepo`, `mockEntryRepo`) and of the media tests (image, article, site, author, variant file, storage, recorder fakes). Name any new fake uniquely across the package, for example `mockMediaFieldImageRepo`. The image fake must expose `Get`, a `getCalls` counter and a `delete(id)` helper.
3. `mockEntryRepo` needs no new method (no repository method is added). Give it an `updateCalls` counter and a `failUpdateOn(n)` switch for the merge compensation case.
4. Build `NewHandler(...)` for the entry, content type and media handlers over use cases wired to the fakes (the entry use cases now take the image fake). Mount them on a fresh `chi.NewRouter()` mirroring api/router.go: `/v1/content-type` and `/v1/media`, with `jwtauth.Verifier`, `jwtauth.Authenticator` and a test `jwtauth.New("HS256", []byte("test-secret"), nil)`. Add `RequireOwnerOrAdmin` on the content type write routes. If `api.InitBackendRoutes` with a partial `*api.UseCases` works, prefer it.
5. Seed users: admin 2 and a plain verified user. Seed images 7 "lime-plaster.jpg" (1600x900, 240000 bytes) and 8 "bathroom-tiles.png" (800x600, 51200 bytes), with distinct paths. Seed the type "event" (title text required, thumbnail media optional) and a variant with thumbnail required.
6. Inject a fake clock so `updated_at` > `created_at`.
7. Decode entry and list bodies into `map[string]any`; compare numbers as `float64`.
## Schema
8. POST a media field with the allowed shape -> 201; the field has type "media", unique false, default/min/max null, options [].
9. Table of refused options (unique true, default 7, default "lime", min 1, max 5, options ["a"]) -> 422 `invalid_field`, repo empty. Assert separately that `default: null` is accepted.
10. Type change in both directions on a type with entries -> 422 `invalid_field`, schema byte-identical. On a type with no entries the existing free type change still applies.
11. Add a media field to a type with 12 entries: required -> 409 `schema_incompatible`, schema unchanged; optional -> 200, existing entries still readable and `media` is `{}`. Make an optional media field required: 409 while an entry holds null, 200 once none does. Making it required while an entry holds an id of a deleted image -> 200 (compatibility does not consult the library).
## Entry writes
12. POST with image 7 -> 201; `data.thumbnail` is 7 and `media.thumbnail` has exactly `id`, `filename`, `width`, `height`, `size`, `thumbnail_url`; the key set of the entry is the seven existing keys plus `media`.
13. POST with null and with the key absent on an optional field -> 201, `media` is `{}` (assert JSON `{}`, not null).
14. Refusal table (required: absent, null; any: 999, "7", 0, -1, 7.5, 4294967296, true, [7]): status 422, exact body `invalid_entry: thumbnail: <rule>`, `createCalls == 0`.
15. PUT replace 7 -> 8: 200, filename "bathroom-tiles.png". PUT to null on optional: 200, `media` is `{}`.
16. After `delete(7)` on the image fake: GET entry 5 -> `data.thumbnail` 7 and `media.thumbnail` equals `{"id":7,"missing":true}` (no other key). PUT with the same 7 on an optional field -> 200, still 7 and still missing. PUT 999 -> 422 type, PUT 8 or null -> 200.
17. Required field, image 7 deleted: PUT 7 -> 422 `required`, PUT null -> 422 `required`, entry unchanged; PUT 8 -> 200.
18. POST with a deleted id 7 -> 422 `type` (create is always a changed value).
19. Ordering: a body with two bad fields names one only: Validate rules first in field order, then the existence check.
## Reads
20. List: 3 entries (existing image, deleted image, null) -> each item has the seven keys plus `media`; values as in the feature; `total`, `page` and `size` unchanged; `items` is `[]` for an empty type.
21. A type without a media field: `media` is `{}` and `getCalls == 0` on the image fake. A list of 100 entries pointing at the same image calls `Get` at most once for that id.
## Media library counts
22. Seed: image 8 used by 3 entries (one through two media fields) and no other use; image 7 used by 2 articles and 5 entries. `GET /v1/media/` -> `used_in` 3 and 7; `GET /v1/media/8` -> 3; `?filter=unused` omits both; `counts.unused` excludes both; an image with no use is still counted unused.
23. Unchanged existing cases: article, author and site usage counts and the unused counts still pass with no entries in the fake.
## Usage endpoint
24. Image 7 with article 12 (cover), entries 41, 42, 43 of "event" and entry 9 of "workshop": status 200, a JSON array, article item unchanged (keys type, id, title, published, fields). Entry items have exactly the keys `type`, `id`, `fields`, `content_type_key`, `content_type_name`, `first_field`, and no `title` and no `published`. Order: article, then event 41, 42, 43, then workshop 9.
25. Raw first-field table (text, richtext with leading blank lines, number 18, select, boolean false, date, text null, key absent, media 7). Assert `first_field` is exactly `{key, type, value}` with the value byte-equal to the stored JSON (richtext unmodified, number as a JSON number, null as JSON `null`). Assert the entry item JSON has no `title` key.
26. Unused image -> `[]`; unknown -> 404 `image_not_found` text; `abc` -> 400 `apperr.IdUint32ErrorMessage`.
## Delete and merge
27. DELETE /v1/media/7 used by 5 entries and 2 articles -> 204; articles cleared as before; the fake entry repo records no Update; the 5 entries are byte-identical.
28. Merge keep 7, merge [9] with equal sha256 and two entries on 9 -> 200; the entries hold 7; `created_by`, `updated_by` and `updated_at` are unchanged; image 9 is gone. Entries pointing at other images are untouched.
29. Merge with `failUpdateOn(2)` -> 500, the first repointed entry is restored to 9, no image deleted, articles/sites/authors repointing rolled back as today.
30. Purge preview and run on a duplicate group where only the copy is used by an entry: the used copy is the kept one; the fingerprint changes accordingly.
## Use case level (no HTTP)
31. `contenttype.ValidateFields` -> `ErrInvalidField` for each refused option. `entry.Validate` rows -> `errors.Is(err, entry.ErrInvalidEntry)` with the right key and rule. `CreateEntry`/`UpdateEntry` with a missing library image -> same error and no write. `UpdateContentType` with a new required media field -> `ErrSchemaIncompatible`, no `Update`.
## Existing tests to amend
32. Amend the existing key-set assertions from seven to eight keys in the earlier custom content type and entry feature, spec and test files (decision: `media` is always present). The coder owns this.
## Manual verification (not exercised by the Go tests)
- Real SQLite, then MySQL/MariaDB and PostgreSQL via the driver tasks: create a type with a media field, upload an image, save an entry, delete the image, reload the entry and confirm the id stays and `media` is `{missing:true}`.
- Merge duplicates with entries on a copy against real storage and confirm the entries repoint and the file is removed.
- Time `GET /v1/media/` with 1,000 entries across a type with a media field (usage lookup loads the entries of such types).
- The SPA (builder, editor control, picker, list cell, library badge and detail panel) is slices B and C and is not checked here.
+2 -2
View File
@@ -363,11 +363,11 @@ Feature: The media library holds every uploaded image as a library-level asset
And article 1's body is back to its original text, article 2 is unchanged And article 1's body is back to its original text, article 2 is unchanged
And images 2 and 3 still exist And images 2 and 3 still exist
Scenario: A failure deleting a copy after the rewrite is 500 and the bodies stay switched Scenario: A failure deleting a copy after the rewrite is 500 and the bodies are rolled back
Given the image repository's Delete fails for image 3 Given the image repository's Delete fails for image 3
When the client sends POST /v1/media/merge with {"keep_id": 2, "merge_ids": [3]} When the client sends POST /v1/media/merge with {"keep_id": 2, "merge_ids": [3]}
Then the response status is 500 Then the response status is 500
And article 1's and article 2's bodies use image 2's url and image 3 still exists And article 1's and article 2's bodies are back to their original text and image 3 still exists
@manual @manual
Rule: Startup backfill and migration (persistence, verified by hand, see the qa.md) Rule: Startup backfill and migration (persistence, verified by hand, see the qa.md)
+1 -1
View File
@@ -26,7 +26,7 @@ Package: `test` (black-box). New file `test/media_library_http_test.go`. Fake ty
13. Rename: assert 200 with the new filename, the same `url`, the article body unchanged, and every invalid row -> 400 with `"Enter a filename.\n"` for the filename rows; 404 for 9999; 400 with `apperr.IdUint32ErrorMessage` for `abc`. Assert the repository filename is unchanged after each 400. 13. Rename: assert 200 with the new filename, the same `url`, the article body unchanged, and every invalid row -> 400 with `"Enter a filename.\n"` for the filename rows; 404 for 9999; 400 with `apperr.IdUint32ErrorMessage` for `abc`. Assert the repository filename is unchanged after each 400.
14. Delete: in-use image -> 204 with an empty body, article bodies byte-identical, `deleteCalls == [1]`; 404, 400, 500 rows. The "file already gone" case is a persistence behaviour and is a manual item. 14. Delete: in-use image -> 204 with an empty body, article bodies byte-identical, `deleteCalls == [1]`; 404, 400, 500 rows. The "file already gone" case is a persistence behaviour and is a manual item.
15. Usage: assert the exact JSON arrays (raw body compared as JSON), the empty `[]`, the absolute-url article, 404 and 400. 15. Usage: assert the exact JSON arrays (raw body compared as JSON), the empty `[]`, the absolute-url article, 404 and 400.
16. Merge: assert 200 `{articles_updated, merged}`, resulting bodies (both occurrences replaced), unchanged bodies for the other articles, and only image 2 left. Assert the 409 rows and 404 row, with no body change and no `Delete` calls (`deleteCalls` empty). Assert every 400 row with `apperr.MediaMergeRequestErrorMessage`. Assert the two failure rows: `UpdateBody` failing for article 2 leaves article 1 restored and no `Delete` call; `Delete` failing for image 3 leaves bodies switched and returns 500. 16. Merge: assert 200 `{articles_updated, merged}`, resulting bodies (both occurrences replaced), unchanged bodies for the other articles, and only image 2 left. Assert the 409 rows and 404 row, with no body change and no `Delete` calls (`deleteCalls` empty). Assert every 400 row with `apperr.MediaMergeRequestErrorMessage`. Assert the two failure rows: `UpdateBody` failing for article 2 leaves article 1 restored and no `Delete` call; `Delete` failing for image 3 returns 500 and rolls the bodies back to their original text, with image 3 still present.
17. Unit-level asserts (same file, no HTTP) with `errors.Is` on the sentinels `ErrImageUnreadable`, `ErrMergeCopyMissing`, `ErrMergeHashMismatch`, `ErrInvalidFilename`. 17. Unit-level asserts (same file, no HTTP) with `errors.Is` on the sentinels `ErrImageUnreadable`, `ErrMergeCopyMissing`, `ErrMergeHashMismatch`, `ErrInvalidFilename`.
18. Layering guard: `go list -deps` or a grep-style test that `api/handlers/media` imports no `persistence`, `mailer`, `models` or `gorm` package. 18. Layering guard: `go list -deps` or a grep-style test that `api/handlers/media` imports no `persistence`, `mailer`, `models` or `gorm` package.
+274
View File
@@ -0,0 +1,274 @@
Feature: Media merge hardening: atomic merge, no lost entry edits, one entry scan per purge
As a site owner or admin
I want a duplicate merge to either fully happen or not happen at all
So that a failure halfway never leaves articles, sites, authors, entries or the library half merged
Background:
Given this slice is backend only: no route, request body, response body, status code, error text or audit payload changes
And internal/domain gains a unit-of-work port (package transaction): Transactor with Run(ctx, func(Repositories) error) error, and Repositories holding the article, site, author, entry and image repositories bound to the open transaction
And internal/domain/transaction imports only the stdlib and other internal/domain/* packages
And Run commits when the function returns nil and rolls everything back when it returns an error or panics, and returns that error unchanged
And the GORM adapter lives in internal/infrastructure/persistence, asserts var _ transaction.Transactor = &X{}, and is built only in api/dependecyInjection.go
And SQL in the adapter stays portable across SQLite, MySQL/MariaDB and PostgreSQL
And MergeMedia and RunPurge depend on transaction.Transactor and never on persistence, gorm or models
And MergeMedia keeps its order: validate, load copies, plan which articles contain a copy name, then inside one transaction re-read each planned article body, apply the replacement of the copy names by the kept name to that re-read body and UpdateBody it, articles RepointImage, sites RepointImage, authors RepointAvatar, entry repoint and image row delete per copy
And restoreBodies, the entry restore of entryMediaScanner and every logCompensation call of the merge are deleted; nothing compensates by hand any more
And the stored file, the variant cache files and the variant cache rows of a merged copy are removed only after the transaction committed, through image.Storage and the variant file repository
And a failure removing those files after the commit is written to the injected *log.Logger, never rolled back, never changes the response or the audit event
And the audit event media.merge and the audit event media.purge are recorded outside the transaction, with the same params as today
And entries are repointed from candidates found by one scan (contenttype.Repository.List then entry.Repository.ListPage with Unpaged, filtered in Go), and each candidate is re-read with entry.Repository.Get inside the transaction before it is written
And an entry repoint only changes the media values that still point at a merged copy in the re-read data, keeps every other value of the re-read data, and leaves created_by, updated_by, created_at and updated_at untouched
And a candidate that no longer exists at re-read time is skipped
And RunPurge and PreviewPurge scan entries once per run and once per preview into an index of image id to entries, shared by the usage counts and by every duplicate group; the index is built in the use case and no repository method is added
And RunPurge runs one transaction per duplicate group, so a failing group rolls back alone and the other groups still merge
And the replacement of a copy name inside an article body matches whole stored file names only, so a name that is a suffix of another name is not rewritten inside it
And the media-field walks (field-type loops, the required and type rule constants, the entry.InvalidField wrapper) are deduplicated into one place; this is a pure refactor and has no scenario of its own beyond "behaviour unchanged"
And MergeMediaResult, purge.RunResult, the merge response {"articles_updated","merged"} (plus sites_updated and authors_updated where the sites and authors features already report them) and the 409, 404, 400 and 500 answers are unchanged
And fixtures: images 7, 8 and 9 share sha256 A with stored names; image 2 and 3 share sha256 B; the type "event" has title (text, required) then thumbnail (media, optional); users: admin 2 (verified)
Rule: A merge is all-or-nothing
Scenario Outline: Any failing step leaves the library exactly as it was
Given images 7 and 9 share sha256 A and 7 is the kept one
And article 1 and article 2 contain the stored name of image 9 in their bodies, article 3 has image 9 as its cover
And site 1 uses image 9 as its default social image and author 4 uses image 9 as its avatar
And entries 41 and 42 of "event" hold thumbnail 9
And <failing step> is armed to fail
When the client sends POST /v1/media/merge with {"keep_id": 7, "merge_ids": [9]}
Then the response status is 500 and the body is "Internal server error"
And the bodies of articles 1 and 2 are byte-identical to before
And article 3 still has cover 9, site 1 still uses 9, author 4 still uses avatar 9
And entries 41 and 42 still hold thumbnail 9 with updated_at and updated_by unchanged
And images 7 and 9 both still exist
And image.Storage.Delete and the variant file repository Delete are never called
And one failed media.merge audit event is recorded
Examples:
| failing step |
| the UpdateBody of the first article |
| the UpdateBody of the second article |
| the article repository RepointImage |
| the site repository RepointImage |
| the author repository RepointAvatar |
| the entry repository Get of the second entry |
| the entry repository Update of the second entry |
| the image repository Delete of image 9 |
| the commit of the transaction |
Scenario: The transaction cannot start
Given the transactor fails to begin
When the client sends POST /v1/media/merge with {"keep_id": 7, "merge_ids": [9]}
Then the response status is 500
And no repository other than the reads of the planning phase was called, and no file was touched
Scenario: Several copies roll back together
Given images 7, 8 and 9 share sha256 A and the image repository Delete fails for image 9 after image 8 was deleted
When the client sends POST /v1/media/merge with {"keep_id": 7, "merge_ids": [8, 9]}
Then the response status is 500
And image 8 exists again, image 9 exists and no article, site, author or entry changed
Scenario: A successful merge still does everything
Given the Background fixtures of the first scenario and no armed failure
When the client sends POST /v1/media/merge with {"keep_id": 7, "merge_ids": [9]}
Then the response status is 200 and the body is {"articles_updated": 3, "merged": 1} plus the existing sites_updated and authors_updated keys
And entries 41 and 42 hold thumbnail 7 with created_by, updated_by and updated_at unchanged
And image 9 is gone from the repository and its stored file is removed
Scenario: A validation or lookup error never opens a transaction
Given any of the existing 400, 404 or 409 merge requests
Then the transactor Run is not called
Scenario: A rollback leaves updated_at and updated_by of entries untouched
Given the entries 41 and 42 hold thumbnail 9 with known created_at, updated_at, created_by and updated_by
And the repoint of entry 42 fails
When the client sends POST /v1/media/merge with {"keep_id": 7, "merge_ids": [9]}
Then the response status is 500
And entries 41 and 42 are byte-identical to before, including updated_at and updated_by
Rule: Stored files are removed only after the commit
Scenario: Files are touched after the commit and never before
Given a merge of image 9 into image 7 that succeeds
Then image.Storage.Delete("<stored name of 9>") is called after the transaction committed
And the variant files of image 9 are removed after the commit
And at no time before the commit is a file or a variant cache row of image 9 removed
Scenario Outline: A file failure after the commit is logged, not rolled back
Given a merge of the copies 8 and 9 into image 7 where <file failure>
When the client sends POST /v1/media/merge with {"keep_id": 7, "merge_ids": [8, 9]}
Then the response status is 200 and the body is the same as without the failure
And images 8 and 9 are gone from the repository and the articles, sites, authors and entries stay repointed
And the removal of the other copy is still attempted
And the injected logger holds one line naming the stored name and the error
And the media.merge audit event is a success with the usual params
Examples:
| file failure |
| image.Storage.Delete fails for image 9 |
| the variant file purge of image 9 fails |
Scenario: A purge group with a file failure after the commit counts as purged
Given groups A and B are planned and image.Storage.Delete fails for a merged copy of group A
When the client sends POST /v1/media/purge with {}
Then the response status is 200 and the body has groups_purged 2 and failed_groups 0
And the merged count includes the copies of group A
And the injected logger holds the file failure
Rule: A concurrent entry edit survives a merge
Scenario: An edit made after the scan is kept
Given entry 41 of "event" is {"title": "Workshop", "thumbnail": 9}
And the entry repository changes entry 41 to {"title": "Workshop 2026", "thumbnail": 9}, with a new updated_at and updated_by, right after the scan returns it
When the client sends POST /v1/media/merge with {"keep_id": 7, "merge_ids": [9]}
Then the response status is 200
And entry 41 is {"title": "Workshop 2026", "thumbnail": 7}
And its updated_at and updated_by are the ones of the concurrent edit, not older ones
Scenario: A concurrent edit that moved the entry off the merged copy is not overwritten
Given entry 41 holds thumbnail 9 when scanned
And the entry repository changes entry 41 to thumbnail 8 right after the scan returns it
When the client sends POST /v1/media/merge with {"keep_id": 7, "merge_ids": [9]}
Then entry 41 still holds thumbnail 8
And the entry repository Update is not called for entry 41
Scenario: An entry deleted after the scan is skipped
Given entry 41 holds thumbnail 9 when scanned
And entry 41 is deleted right after the scan returns it
When the client sends POST /v1/media/merge with {"keep_id": 7, "merge_ids": [9]}
Then the response status is 200 and image 9 is gone
Scenario: Entries are written from the re-read data
Given entry 41 holds {"title": "A", "thumbnail": 9, "poster": 9} when scanned
When the merge runs
Then entry 41 holds thumbnail 7 and poster 7 and the same title
And the entry repository Update is called once for entry 41
Rule: A concurrent article edit survives a merge
Scenario: A body edited after planning is kept
Given article 1 contains the stored name of image 9 and the planning has read its body
And the article repository changes article 1 to the same text plus a new paragraph, right after the planning read returns it
When the client sends POST /v1/media/merge with {"keep_id": 7, "merge_ids": [9]}
Then the response status is 200
And article 1's body holds the new paragraph and the stored name of image 7 instead of image 9
Scenario: A body edited so that it no longer holds the copy name is not rewritten
Given article 1 contains the stored name of image 9 when planned
And the article repository changes article 1 to a text without the stored name of image 9 right after the planning read returns it
When the client sends POST /v1/media/merge with {"keep_id": 7, "merge_ids": [9]}
Then article 1's body is the edited text and the article repository UpdateBody is not called for article 1
And article 1 is not counted in "articles_updated"
Scenario: An article deleted after planning is skipped
Given article 1 contains the stored name of image 9 when planned
And article 1 is deleted right after the planning read returns it
When the client sends POST /v1/media/merge with {"keep_id": 7, "merge_ids": [9]}
Then the response status is 200 and image 9 is gone
Scenario: Only whole stored names are replaced
Given image 9 has the stored name "a.jpg" and article 1 contains "ba.jpg" and "a.jpg"
When the client sends POST /v1/media/merge with {"keep_id": 7, "merge_ids": [9]}
Then article 1 still contains "ba.jpg" and no longer contains the standalone "a.jpg"
Rule: A cancelled purge stops cleanly
Scenario: A request cancelled between groups stops the run
Given groups A, B and C are planned and the request context is cancelled after group A committed
When the purge runs
Then group A stays merged and groups B and C are untouched
And the run returns the context error and records no last_purge_* values and no media.purge success event
And failed_groups is not incremented for B and C
Scenario: The scheduler passes its context to the run
Given the scheduler context is cancelled while a scheduled purge is between groups
Then the run stops after the group in progress and records no last_purge_* values
Rule: A purge scans entries once
Scenario: A preview over many groups scans once
Given 6 planned duplicate groups, 40 entries and 2 content types with a media field
When the client sends GET /v1/media/purge-preview
Then contenttype.Repository.List is called once
And entry.Repository.ListPage is called once per content type with a media field, 2 times in all
And the response is the same as before this slice
Scenario: A run over many groups scans once
Given the same 6 groups, 40 entries and 2 content types with a media field
When the client sends POST /v1/media/purge with {}
Then contenttype.Repository.List is called once
And entry.Repository.ListPage is called 2 times in all, not once per group
And the response and the stored last_purge_* values are the same as before this slice
Scenario: The index is stale after a group but the result is right
Given entry 41 holds thumbnail 2 and poster 5, where 2 is a copy of group A and 5 is a copy of group B
When the client sends POST /v1/media/purge with {}
Then entry 41 holds the kept image of group A as thumbnail and the kept image of group B as poster
And entry.Repository.Update is called twice for entry 41
Scenario: The usage counts and the candidates come from the same scan
Given the duplicate group 7, 9 where only 9 is used, by 1 entry
When the purge preview and the purge run
Then 9 is the kept image and 7 is the merged copy
And there is one scan per call
Rule: A purge run commits one group at a time
Scenario Outline: A failing group rolls back alone
Given groups A, B and C are planned, in that order
And <failure> is armed for group B
When the client sends POST /v1/media/purge with {}
Then the response status is 200
And the body is {"groups_total": 3, "groups_purged": 2, "merged": <copies of A and C>, "articles_updated": <distinct articles of A and C>, "failed_groups": 1}
And all of group B's article bodies, entries, sites, authors and images are back to their original state
And groups A and C are merged
And the stored last_purge_merged and last_purge_articles_updated equal the response totals
Examples:
| failure |
| the UpdateBody of the second article |
| the article repository RepointImage |
| the entry repository Update |
| the image repository Delete of a merged copy |
Scenario: Every group failing is still a 200
Given every group is armed to fail
When the client sends POST /v1/media/purge with {}
Then the response status is 200
And groups_purged is 0 and failed_groups equals groups_total
And no image, body, entry, site or author changed and the stored last_purge_at is set
Scenario: The run opens one transaction per planned group
Given 3 planned groups
When the client sends POST /v1/media/purge with {}
Then the transactor Run is called 3 times
Rule: Behaviour unchanged (the media-field walk refactor)
Scenario: The shared walk changes nothing
Given the media-field rule constants, the InvalidField wrapper and the walks over a content type's media fields live in one place
Then every scenario of features/media_field_type.feature, media_library.feature and media_purge.feature passes unchanged, except the two amended below
Rule: Amendments to earlier features
Scenario: media_library.feature "A failure deleting a copy after the rewrite is 500 and the bodies are rolled back" is amended
Given the image repository's Delete fails for image 3
When the client sends POST /v1/media/merge with {"keep_id": 2, "merge_ids": [3]}
Then the response status is 500
And article 1's and article 2's bodies are back to their original text and image 3 still exists
Scenario: media_purge.feature "A group that fails after rewriting bodies" is amended
Given the image repository's Delete fails for a merged image of group A, and group B is planned
When the client sends POST /v1/media/purge with {}
Then the response status is 200, "failed_groups" is 1 and "groups_purged" is 1
And group A contributes 0 to "merged" and none of its article ids to "articles_updated"
And group A's article bodies are back to their original text
And a following GET /v1/media/purge-preview plans group A again, and the next run converges
@manual
Rule: Persistence (verified by hand, see the qa.md)
Scenario: The GORM adapter rolls back on SQLite, MySQL/MariaDB and PostgreSQL
Given duplicates with articles, a site, an author and entries pointing at a copy
When a merge fails at the image delete on each driver
Then no row changed on any of the three drivers
+80
View File
@@ -0,0 +1,80 @@
# QA procedure: media_merge_hardening
Package: `test` (black-box). New file `test/media_merge_hardening_test.go`. Go only: no SPA, no env var, no live server, no real SQLite file, no real SMTP. Fake type names must be unique in the package.
## Setup shared by every case
1. Call `validator.InitValidator()` once per test.
2. Reuse the fakes of the media tests and the purge tests: `mockImageRepo`, `mockArticleRepo`, the site, author and storage fakes, the variant file fake, the audit recorder fake, `mockContentTypeRepo`, `mockEntryRepo`, `mockPurgeSettingsRepo`, and the helpers `seedGroup` and `articleUsing`.
3. New fake `mockMergeTransactor` (implements `transaction.Transactor`):
- It holds the fakes of step 2 and hands them to the function as the `Repositories` struct. In-memory fakes need no real binding to the transaction.
- Rollback emulation: before calling the function it snapshots the state of every fake it holds (a deep copy of their maps), and it restores the snapshots when the function returns an error. Counters (`updateCalls`, `getCalls`, `deleteCalls`) are NOT restored, so tests can still assert that calls happened.
- Switches: `failBegin`, `failCommit`. `failCommit` restores the snapshots and returns the error after the function returned nil.
- Fields: `runCalls`, and a `committed bool` that is true only between the commit and the next Run.
- Each fake gains `snapshot()` and `restore()` helpers in the test package only; no production code change.
4. Fake extensions (no new method on a domain interface):
- `mockEntryRepo`: `listPageCalls`, `getCalls`, `failUpdateOn(n)` (already exists), `failGetOn(n)`, and `afterListPage func()` called right after `ListPage` builds its result, used to mutate or delete an entry after the scan.
- `mockContentTypeRepo`: `listCalls`.
- `mockArticleRepo`: failure switches for `UpdateBody` (per id and per call number) and `RepointImage`.
- Site and author fakes: failure switches for `RepointImage` and `RepointAvatar`.
- `mockImageRepo`: `Delete` with `failDeleteFor`.
- Storage fake: records `Delete` calls, with a failure switch per stored name; each record notes `transactor.committed` at call time.
- Variant file fake: the same recording and failure switch.
5. Build `NewMergeMediaUseCase(...)` with the transactor, storage, variant files, recorder, the fakes, an injected `*log.Logger` over a `bytes.Buffer`, and `NewRunPurgeUseCase` / `NewPreviewPurgeUseCase` over the same fakes. The constructors are chosen by the coder. Mount the media handler on a fresh `chi.NewRouter()` mirroring `NewMediaRouter` in api/router.go, with the media_purge.qa.md setup, `jwtauth.New("HS256", []byte("test-secret"), nil)` and an admin 2 cookie. Compare error bodies as `message + "\n"`.
6. Seed: images 7, 8 and 9 (same sha256 A), 2 and 3 (sha256 B). The type "event" has title and thumbnail (media, optional), plus a second type with two media fields (thumbnail, poster) for the walk and index cases. Seed articles, a site and an author that point at the copies. Inject a fixed clock so entry `updated_at` is known.
7. Snapshot helper `libraryState()` deep-copying every fake. Assert "unchanged" with `reflect.DeepEqual` of before and after.
## All-or-nothing
8. Failing step table (the 9 rows of the first outline), one subtest per row. Arm the failure, POST `/v1/media/merge` with keep 7 and merge [9]. Assert 500 and "Internal server error\n". Assert `libraryState()` equals the state before, including bodies, cover ids, site and author references, entries with `updated_at` and `updated_by`, and both image rows. Assert the storage fake and the variant fake recorded no `Delete` call. Assert exactly one failed `media.merge` audit event. Use `failCommit` for the commit row.
9. `failBegin`: 500, no write call on any fake, no file call.
10. Two copies (8 and 9), `failDeleteFor(9)` after 8 was deleted: 500, image 8 exists again after rollback, all else unchanged.
11. Success path: 200 and the unchanged body, entries 41 and 42 hold 7 with `created_by`, `updated_by`, `created_at` and `updated_at` unchanged, image 9 gone, the storage fake got `Delete`, and the audit event is a success with `merged` and `articles_updated`.
12. Validation, lookup and 409 requests (all existing 400, 404, 409 cases): `runCalls == 0`.
13. Rollback and `updated_at` / `updated_by`: arm `failUpdateOn(2)` on the entry fake, assert both entries are `DeepEqual` to the seed.
## Files after commit
14. Success: the storage fake `Delete` record has `committed == true` for every call; the variant fake records likewise. Failure rows of step 8: no records at all.
15. File failure table (storage `Delete` fails for 9; variant purge fails for 9) with copies 8 and 9: 200 and the same body as the no-failure run, images gone, repoints kept, the other copy's removal still attempted, the log buffer holds one line with the stored name and the error text, the audit event is a success with the usual params.
16. Purge group with a storage failure after commit: 200, `groups_purged` 2, `failed_groups` 0, merged count includes the copies of group A, the log buffer holds the failure.
## Concurrent entry edit
17. Edit after the scan: set `afterListPage` to rewrite entry 41 to a new title with new `updated_at` and `updated_by`. After the merge, entry 41 has the new title, thumbnail 7 and the edit's `updated_at` and `updated_by`.
18. Edit that moves the entry to image 8 after the scan: entry 41 still holds 8 and the entry fake saw no `Update` for 41.
19. Entry deleted after the scan: 200, image 9 gone, no error.
20. Re-read data: an entry with thumbnail 9 and poster 9: both become 7, the title is kept, `Update` is called once for that entry.
## Concurrent article edit
17a. `mockArticleRepo` gains `afterFindByBody func()` called right after `FindByBodyContaining` builds its result. Edit after planning: article 1 gets an extra paragraph; after the merge it holds the paragraph and the kept stored name. Edit removing the copy name: no `UpdateBody` for article 1, not in `articles_updated`. Article deleted after planning: 200, image 9 gone. Suffix collision (`a.jpg` inside `ba.jpg`): `ba.jpg` untouched. Add a property-style table for the replacement helper (identity without the copy name, idempotence, kept name never removed).
## Cancelled purge
17b. Cancel the context from a fake hook after group A commits: A merged, B and C untouched, `Execute`/`Run` return the context error, `failed_groups` unchanged, no `last_purge_*` saved, no success `media.purge` audit event. Scheduler: `Execute` receives the scheduler context (no more `context.Background()`), cancelled between groups it stops the same way.
## One scan per run and per preview
21. Preview over 6 groups, 40 entries, 2 media types: `contenttype listCalls == 1`, `entry listPageCalls == 2`. Body equals the body from before the slice (same seed in an existing test).
22. Run over the same seed: `listCalls == 1`, `listPageCalls == 2`, and the response and stored `last_purge_*` match.
23. Stale index: an entry with thumbnail in group A and poster in group B ends with both kept ids, `Update` called twice for it.
24. Media-used-only-by-entry group (existing step 30 of media_field_type.qa.md): the used copy is kept, the preview and the run each scan once.
## Purge per group
25. Failure table (UpdateBody of the second article, article RepointImage, entry Update, image Delete for a merged copy) armed for group B in plan order A, B, C: 200 and the counters of the feature, group B fully rolled back, A and C merged, `Save` counters equal the response.
26. All groups failing: 200, `groups_purged` 0, `failed_groups == groups_total`, state unchanged, `last_purge_at` saved.
27. Three groups: `transactor.runCalls == 3`.
## Amended existing tests (the coder owns them)
28. media_library test "failure deleting a copy": bodies are now restored and image 3 still exists. media_purge step 30: group A's bodies are restored (no longer switched), failed_groups 1, groups_purged 1, A contributes 0, the next run converges.
29. Every other existing test passes unchanged. Constructors of `MergeMedia`, `RunPurge` and `PreviewPurge` gain the transactor and logger; update the call sites in tests only.
## Behaviour unchanged (walk refactor)
30. No new case. Run the full existing suites (`task test`) and require them to pass, as the pure-refactor proof.
## Layering guards
31. `internal/domain/transaction` imports only the stdlib and `internal/domain/*`. The use cases import no `persistence`, `gorm`, `models` or `net/http`. The GORM adapter asserts `var _ transaction.Transactor = &X{}` and is constructed only in api/dependecyInjection.go. Use the grep-style test of media_purge.qa.md.
## Manual verification (not exercised by the Go tests)
- Real SQLite, then MySQL/MariaDB and PostgreSQL via the driver tasks: seed duplicates with articles, a site, an author and entries on a copy; make the image delete fail (for example a read-only DB or a trigger); confirm no row changed.
- Real merge against real uploads: the copy's file and variant files are gone after a 200, and still present after a forced failure.
- Concurrent merge and entry edit with two shells (curl with the jwt cookie): the edit survives.
- Time `POST /v1/media/purge` with many groups and 1,000 entries (one scan, not one per group).
- Check that a SQLite transaction does not deadlock with the connection settings in `persistence/database` (all reads inside the transaction go through the tx-bound repositories).
## Decisions accepted by the user
Amend the two earlier scenarios; a file failure after commit is 200 plus a log line (injected `*log.Logger`); one transaction per purge group; entries scanned then re-read per candidate inside the transaction; article bodies are re-read and rewritten inside the transaction (the user chose to fix the body race: the plan only decides which articles change); a purge cancelled by its context stops between groups without recording a run; entries created after the scan that point at a copy are not repointed (accepted limitation, shown as missing); adapter verified by hand, Go tests use fakes with snapshot/restore rollback.
+3 -2
View File
@@ -342,11 +342,12 @@ Feature: Owners and admins can merge duplicate images in use, with persisted pur
And group B's UpdatedArticleIDs is empty, so no article of group B is in "articles_updated" And group B's UpdatedArticleIDs is empty, so no article of group B is in "articles_updated"
And the stored last_purge_merged and last_purge_articles_updated equal the response totals And the stored last_purge_merged and last_purge_articles_updated equal the response totals
Scenario: A group that fails after rewriting bodies is reported as failed and contributes nothing Scenario: A group that fails after rewriting bodies is rolled back, reported as failed and contributes nothing
Given the image repository's Delete fails for a merged image of group A, and group B is planned Given the image repository's Delete fails for a merged image of group A, and group B is planned
When the client sends POST /v1/media/purge with {} When the client sends POST /v1/media/purge with {}
Then the response status is 200, "failed_groups" is 1 and "groups_purged" is 1 Then the response status is 200, "failed_groups" is 1 and "groups_purged" is 1
And group A contributes 0 to "merged" and its article ids are not added to "articles_updated", even though its article bodies stay switched to the kept copy And group A contributes 0 to "merged" and its article ids are not added to "articles_updated"
And group A's article bodies are back to their original text
And "articles_updated" and "merged" count only the fully merged group B And "articles_updated" and "merged" count only the fully merged group B
And a following GET /v1/media/purge-preview plans group A again, and the next run converges because the plan is recomputed from current data And a following GET /v1/media/purge-preview plans group A again, and the next run converges because the plan is recomputed from current data
+1 -1
View File
@@ -57,7 +57,7 @@ Package: `test` (black-box). New files `test/media_purge_http_test.go` and `test
27. Fingerprint: match gives 200. A stale fingerprint gives 409 with `apperr.PurgeConflictErrorMessage + "\n"`, no `Delete`, no `UpdateBody`, no `Save`. A garbage string gives 409 with the same body. No fingerprint, `{}` and an empty body all run. 27. Fingerprint: match gives 200. A stale fingerprint gives 409 with `apperr.PurgeConflictErrorMessage + "\n"`, no `Delete`, no `UpdateBody`, no `Save`. A garbage string gives 409 with the same body. No fingerprint, `{}` and an empty body all run.
28. Empty plan: 200 zeros, `Save` with `last_purge_at` = clock and zero counters, and a run with the empty plan's fingerprint is also 200. 28. Empty plan: 200 zeros, `Save` with `last_purge_at` = clock and zero counters, and a run with the empty plan's fingerprint is also 200.
29. Partial failure, rolled back: arm `UpdateBody` to fail for the second article of group B (plan order A, B, C). Assert the body counters, B's bodies restored byte for byte, all B images present, A and C merged, B's articles absent from `articles_updated`, and `Save` counters equal the response. 29. Partial failure, rolled back: arm `UpdateBody` to fail for the second article of group B (plan order A, B, C). Assert the body counters, B's bodies restored byte for byte, all B images present, A and C merged, B's articles absent from `articles_updated`, and `Save` counters equal the response.
30. Partial failure, delete: arm `failDeleteFor` for one of group A's merged images and plan B too. Assert `failed_groups` 1, `groups_purged` 1, A contributes 0 to `merged` and none of its ids to `articles_updated` (only B counts), A's article bodies stay switched to the kept copy, and a following preview plans A again. Run the purge again with the failure disarmed and assert it converges (A's leftover copy is merged away). Then arm every `UpdateBody` and assert `groups_purged` 0, `failed_groups` = `groups_total` and `last_purge_at` still saved. 30. Partial failure, delete: arm `failDeleteFor` for one of group A's merged images and plan B too. Assert `failed_groups` 1, `groups_purged` 1, A contributes 0 to `merged` and none of its ids to `articles_updated` (only B counts), A's article bodies are back to their original text, and a following preview plans A again. Run the purge again with the failure disarmed and assert it converges (A's leftover copy is merged away). Then arm every `UpdateBody` and assert `groups_purged` 0, `failed_groups` = `groups_total` and `last_purge_at` still saved.
31. Concurrency: start run 1 in a goroutine, blocked in the image fake (wait on a "started" channel). Send run 2 (once with a fingerprint, once without). Assert both answer 409 with `apperr.PurgeBusyErrorMessage + "\n"` immediately (use a timeout) and no `Save`/`Delete` calls from them. Release run 1, assert its 200 body and that a later run is accepted. Run this test with `-race`. 31. Concurrency: start run 1 in a goroutine, blocked in the image fake (wait on a "started" channel). Send run 2 (once with a fingerprint, once without). Assert both answer 409 with `apperr.PurgeBusyErrorMessage + "\n"` immediately (use a timeout) and no `Save`/`Delete` calls from them. Release run 1, assert its 200 body and that a later run is accepted. Run this test with `-race`.
32. Sentinels at the use-case level, asserted separately: a stale fingerprint gives `errors.Is(err, purge.ErrPurgeConflict)` true and `errors.Is(err, purge.ErrPurgeBusy)` false; a busy guard gives `ErrPurgeBusy` true and `ErrPurgeConflict` false. Call RunPurge without any HTTP package to prove it is reusable (that test file section imports no `net/http`). 32. Sentinels at the use-case level, asserted separately: a stale fingerprint gives `errors.Is(err, purge.ErrPurgeConflict)` true and `errors.Is(err, purge.ErrPurgeBusy)` false; a busy guard gives `ErrPurgeBusy` true and `ErrPurgeConflict` false. Call RunPurge without any HTTP package to prove it is reusable (that test file section imports no `net/http`).
33. Malformed body gives 400 `apperr.BodyErrorMessage`. `ListDuplicates` failure gives 500 and no `Save`. 33. Malformed body gives 400 `apperr.BodyErrorMessage`. `ListDuplicates` failure gives 500 and no `Save`.
+44 -64
View File
@@ -1,84 +1,64 @@
module RenewCMS module RenewCMS
go 1.27.1 go 1.27.3
require ( require (
github.com/MadAppGang/httplog v1.3.0 github.com/aws/aws-sdk-go-v2 v1.47.3
github.com/aws/aws-sdk-go-v2 v1.47.1 github.com/aws/aws-sdk-go-v2/config v1.33.9
github.com/aws/aws-sdk-go-v2/config v1.33.6 github.com/aws/aws-sdk-go-v2/credentials v1.20.9
github.com/aws/aws-sdk-go-v2/credentials v1.20.6 github.com/aws/aws-sdk-go-v2/service/s3 v1.114.4
github.com/aws/aws-sdk-go-v2/service/s3 v1.114.0
github.com/gen2brain/webp v0.6.4 github.com/gen2brain/webp v0.6.4
github.com/glebarez/sqlite v1.11.0 github.com/glebarez/sqlite v1.11.0
github.com/go-chi/chi/v5 v5.2.3 github.com/go-chi/chi/v5 v5.5.0
github.com/go-chi/cors v1.2.2 github.com/go-playground/validator/v10 v10.30.5
github.com/go-chi/jwtauth/v5 v5.4.0 github.com/go-sql-driver/mysql v1.10.1
github.com/go-playground/validator/v10 v10.28.0
github.com/go-sql-driver/mysql v1.8.1
github.com/google/uuid v1.6.0 github.com/google/uuid v1.6.0
github.com/jackc/pgx/v5 v5.10.0 github.com/jackc/pgx/v5 v5.11.0
github.com/joho/godotenv v1.5.1 golang.org/x/crypto v0.58.0
github.com/lestrrat-go/jwx/v3 v3.3.0 golang.org/x/image v0.47.0
golang.org/x/crypto v0.57.0 golang.org/x/net v0.61.0
golang.org/x/image v0.46.0 golang.org/x/text v0.43.0
golang.org/x/net v0.59.0
golang.org/x/sync v0.23.0
golang.org/x/text v0.42.0
gopkg.in/gomail.v2 v2.0.0-20160411212932-81ebce5c23df
gorm.io/driver/mysql v1.6.0 gorm.io/driver/mysql v1.6.0
gorm.io/driver/postgres v1.6.3 gorm.io/driver/postgres v1.6.3
gorm.io/gorm v1.31.2 gorm.io/gorm v1.31.2
) )
require ( require (
filippo.io/edwards25519 v1.1.0 // indirect filippo.io/edwards25519 v1.2.0 // indirect
github.com/TylerBrock/colorjson v0.0.0-20200706003622-8a50f05110d2 // indirect github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.23 // indirect
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.20 // indirect github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.20.3 // indirect
github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.20.1 // indirect github.com/aws/aws-sdk-go-v2/internal/configsources v1.5.6 // indirect
github.com/aws/aws-sdk-go-v2/internal/configsources v1.5.4 // indirect github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.8.6 // indirect
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.8.4 // indirect github.com/aws/aws-sdk-go-v2/internal/v4a v1.5.6 // indirect
github.com/aws/aws-sdk-go-v2/internal/v4a v1.5.4 // indirect github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.21 // indirect
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.19 // indirect github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.11.7 // indirect
github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.11.5 // indirect github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.14.6 // indirect
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.14.4 // indirect github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.20.6 // indirect
github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.20.4 // indirect github.com/aws/aws-sdk-go-v2/service/signin v1.10.4 // indirect
github.com/aws/aws-sdk-go-v2/service/signin v1.10.1 // indirect github.com/aws/aws-sdk-go-v2/service/sso v1.38.4 // indirect
github.com/aws/aws-sdk-go-v2/service/sso v1.38.1 // indirect github.com/aws/aws-sdk-go-v2/service/ssooidc v1.43.4 // indirect
github.com/aws/aws-sdk-go-v2/service/ssooidc v1.43.1 // indirect github.com/aws/aws-sdk-go-v2/service/sts v1.51.4 // indirect
github.com/aws/aws-sdk-go-v2/service/sts v1.51.1 // indirect github.com/aws/smithy-go v1.28.6 // indirect
github.com/aws/smithy-go v1.28.1 // indirect github.com/dustin/go-humanize v1.1.0 // indirect
github.com/decred/dcrd/dcrec/secp256k1/v4 v4.4.1 // indirect github.com/ebitengine/purego v0.11.2 // indirect
github.com/dustin/go-humanize v1.0.1 // indirect github.com/gabriel-vasile/mimetype v1.4.16 // indirect
github.com/ebitengine/purego v0.10.1 // indirect github.com/glebarez/go-sqlite v1.23.0 // indirect
github.com/fatih/color v1.18.0 // indirect github.com/go-playground/locales v0.14.2 // indirect
github.com/gabriel-vasile/mimetype v1.4.11 // indirect github.com/go-playground/universal-translator v0.18.2 // indirect
github.com/glebarez/go-sqlite v1.22.0 // indirect
github.com/go-playground/locales v0.14.1 // indirect
github.com/go-playground/universal-translator v0.18.1 // indirect
github.com/goccy/go-json v0.10.6 // indirect
github.com/jackc/pgpassfile v1.0.0 // indirect github.com/jackc/pgpassfile v1.0.0 // indirect
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect
github.com/jackc/puddle/v2 v2.2.2 // indirect github.com/jackc/puddle/v2 v2.2.3 // indirect
github.com/jinzhu/inflection v1.0.0 // indirect github.com/jinzhu/inflection v1.0.0 // indirect
github.com/jinzhu/now v1.1.5 // indirect github.com/jinzhu/now v1.1.5 // indirect
github.com/leodido/go-urn v1.4.0 // indirect github.com/leodido/go-urn v1.5.0 // indirect
github.com/lestrrat-go/blackmagic v1.0.4 // indirect github.com/mattn/go-isatty v0.0.24 // indirect
github.com/lestrrat-go/dsig v1.4.0 // indirect github.com/ncruces/go-strftime v1.1.0 // indirect
github.com/lestrrat-go/dsig-secp256k1 v1.0.0 // indirect
github.com/lestrrat-go/httpcc v1.0.1 // indirect
github.com/lestrrat-go/httprc/v3 v3.0.6 // indirect
github.com/lestrrat-go/option/v2 v2.0.0 // indirect
github.com/mattn/go-colorable v0.1.14 // indirect
github.com/mattn/go-isatty v0.0.20 // indirect
github.com/ncruces/go-strftime v1.0.0 // indirect
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect
github.com/segmentio/asm v1.2.1 // indirect github.com/stretchr/testify v1.12.1 // indirect
github.com/valyala/fastjson v1.6.10 // indirect golang.org/x/sync v0.24.0 // indirect
golang.org/x/exp v0.0.0-20251113190631-e25ba8c21ef6 // indirect golang.org/x/sys v0.49.0 // indirect
golang.org/x/sys v0.48.0 // indirect modernc.org/libc v1.79.0 // indirect
gopkg.in/alexcesaro/quotedprintable.v3 v3.0.0-20150716171945-2caba252f4dc // indirect
modernc.org/libc v1.67.0 // indirect
modernc.org/mathutil v1.7.1 // indirect modernc.org/mathutil v1.7.1 // indirect
modernc.org/memory v1.11.0 // indirect modernc.org/memory v1.12.1 // indirect
modernc.org/sqlite v1.40.1 // indirect modernc.org/sqlite v1.61.0 // indirect
) )
+100 -146
View File
@@ -1,165 +1,119 @@
filippo.io/edwards25519 v1.1.0 h1:FNf4tywRC1HmFuKW5xopWpigGjJKiJSV0Cqo0cJWDaA= filippo.io/edwards25519 v1.2.0 h1:crnVqOiS4jqYleHd9vaKZ+HKtHfllngJIiOpNpoJsjo=
filippo.io/edwards25519 v1.1.0/go.mod h1:BxyFTGdWcka3PhytdK4V28tE5sGfRvvvRV7EaN4VDT4= filippo.io/edwards25519 v1.2.0/go.mod h1:xzAOLCNug/yB62zG1bQ8uziwrIqIuxhctzJT18Q77mc=
github.com/MadAppGang/httplog v1.3.0 h1:1XU54TO8kiqTeO+7oZLKAM3RP/cJ7SadzslRcKspVHo= github.com/aws/aws-sdk-go-v2 v1.47.3 h1:HRoT/MkNi3bjO5xF4dCzLzvVmkvRGHj3/cLINDnJejk=
github.com/MadAppGang/httplog v1.3.0/go.mod h1:gpYEdkjh/Cda6YxtDy4AB7KY+fR7mb3SqBZw74A5hJ4= github.com/aws/aws-sdk-go-v2 v1.47.3/go.mod h1:xSl+OSI5ZUw6bSMupWc218zE5Pl+65MCCu3ySWFY99A=
github.com/TylerBrock/colorjson v0.0.0-20200706003622-8a50f05110d2 h1:ZBbLwSJqkHBuFDA6DUhhse0IGJ7T5bemHyNILUjvOq4= github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.23 h1:/fGPpKrXTjzkhsDXExBgNT2cGwxiF9rLrQXh8RlXMhI=
github.com/TylerBrock/colorjson v0.0.0-20200706003622-8a50f05110d2/go.mod h1:VSw57q4QFiWDbRnjdX8Cb3Ow0SFncRw+bA/ofY6Q83w= github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.23/go.mod h1:QWUDuRi9PFjBHIU2iH1Pkldbe7zqLfXJC4wWLbF8nuQ=
github.com/aws/aws-sdk-go-v2 v1.47.1 h1:uOIZnp4PK3ZhKI0dNrJrhTEsLxbpXHTAJlwoS1pvAtw= github.com/aws/aws-sdk-go-v2/config v1.33.9 h1:Hv6bcQUJVnmuWaKjqD6Ot8sE75NrWsWV20oGT5aWle0=
github.com/aws/aws-sdk-go-v2 v1.47.1/go.mod h1:bttEH6JqnUL8LepvDVfdrds/fZ5bCIxzpe3abyUrhDU= github.com/aws/aws-sdk-go-v2/config v1.33.9/go.mod h1:ivowmrZNfBQLcg4QkaItgi5wae4Bzot9RzIdbY1hfTg=
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.20 h1:GPRlPwz40I2B2VrBEASOA3Bi77NyeqejNLkifosX0rs= github.com/aws/aws-sdk-go-v2/credentials v1.20.9 h1:SNO55PnWhaDafsOcv16lCA0kdoFMl/YlegWoVsU02s0=
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.20/go.mod h1:g7PNzKcsOKWb4fkSRBA7BZVAS6Y8IcxzN+nRohhQ1Q8= github.com/aws/aws-sdk-go-v2/credentials v1.20.9/go.mod h1:+2reOTRtdD3VSBqpRDNwrZIYy8yMCYa7oK3WKTJ/I1I=
github.com/aws/aws-sdk-go-v2/config v1.33.6 h1:MBjkSTLczek/UgiK+EYPIoRTqE7gP8vtW3OFbFo7Nug= github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.20.3 h1:gr3b87OLB29jymWPzp/CAyXwQRJVE+sC4Wm0qBIKHsk=
github.com/aws/aws-sdk-go-v2/config v1.33.6/go.mod h1:grRAFzdAZJrwcbasJRg2MPvIrVjtlfXllHssN6+E1JE= github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.20.3/go.mod h1:BRjf4L/Yx2hY54o+ZibPbLJyMMeSwqYQXwcJfqW66a8=
github.com/aws/aws-sdk-go-v2/credentials v1.20.6 h1:NpAFXCU7NzXNkdGK3zQTtsRJ+3v9tZQV0xcdRw8uBdw= github.com/aws/aws-sdk-go-v2/internal/configsources v1.5.6 h1:CqL8NN3p4I0JTwwV5MEoatIl4Y2amZ2X9dRD+0hbRL0=
github.com/aws/aws-sdk-go-v2/credentials v1.20.6/go.mod h1:mcZCoiPnyMvP8VMNbygNX5lLqSlkYJIMPODylQMurOk= github.com/aws/aws-sdk-go-v2/internal/configsources v1.5.6/go.mod h1:exdJ32hMqXl0Wyo6NwqEC5yIhtua3+PDaKE8P29m4qE=
github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.20.1 h1:8gALAAmacnIXh+z6VkdDanv4/IkG5APdg4DZLDTmLog= github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.8.6 h1:FpBq24TG6WVSObTNhQOv7Q0088rounUUlwn3zlNItkM=
github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.20.1/go.mod h1:Z7IJhJU+poOdJjUR2wpyY21ossQ1XS/R3Lk9Msq5kM4= github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.8.6/go.mod h1:ONzdPVYC95oBOu0VWNEsKEntcoemP3xVKjT+qWml1s4=
github.com/aws/aws-sdk-go-v2/internal/configsources v1.5.4 h1:CLq4+8UHCI+ZZYl/EuJxXovaIVN2xeeT8JV+dsApQ5E= github.com/aws/aws-sdk-go-v2/internal/v4a v1.5.6 h1:Qmn60RWuk9+bd2ddvJJqwf3Cpac3VvGMOdbGemtUhX4=
github.com/aws/aws-sdk-go-v2/internal/configsources v1.5.4/go.mod h1:Wv4q5sAM04xAMkoOedxLx2inVf6K5FdxYp+A61L+q/0= github.com/aws/aws-sdk-go-v2/internal/v4a v1.5.6/go.mod h1:h/YJhe4AVyQxEUMluph10iqV7mjajH7A9L+BHF5ppis=
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.8.4 h1:dD4MR81I7YkpEBRk6UP9rocC2QnT3qVuXwzlYTtfGEs= github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.21 h1:e6YW5uME30TkrElR+4/xcY7NB6CCj2dcv7vtmGXhfhQ=
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.8.4/go.mod h1:EcXV1kAFd5XwSkDHlj94gnF3q5CkJyYiIJfH8N0VmrE= github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.21/go.mod h1:obpHAMP693+f3/A8PkLhIqfK1C+NWWn8zXzqD3OH520=
github.com/aws/aws-sdk-go-v2/internal/v4a v1.5.4 h1:7Wo47d/xn/7KttCSBd8EGYeZ7ULRFRkUHr6vkZPBzVQ= github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.11.7 h1:CwvFlKw0uUScfgOMflXSRZa+ayXgOf6wk7lhyMemQYU=
github.com/aws/aws-sdk-go-v2/internal/v4a v1.5.4/go.mod h1:tDB2IVC1xC3vX8o+6uRlzhTxP3g1b77CZXFX/oD2FnQ= github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.11.7/go.mod h1:4SbD8BB+p+QEnG0aX6DoWwrtk9SufyYXRsUv0nve8LE=
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.19 h1:bAdDl/HkGCcGPoe25ToSHEw23VIxt6CT5fLcg111BKg= github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.14.6 h1:LHHdobjo5le1sjJdolitV7uVvYg3wkaeM1Ju2fDgeZQ=
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.19/go.mod h1:KaUzbLxv4CeSxh6ZCl9B4m7CuFenS8kUEaDs+f/DQr4= github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.14.6/go.mod h1:CBGB0evAiaMD3Lk4wPO7LQCcCZLuhzL5Qf/wfEUHQ5w=
github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.11.5 h1:/TYsZXdA8UTa+WCtCYSAJIr1vwl0+eho6TUgJGwFFO8= github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.20.6 h1:mYViDr2azcgxOpRrObZOl631bvavqILoE/L+Kxgbwys=
github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.11.5/go.mod h1:qPqp1Uwd/BqdhPufv6oem9j5J7HNsgc2V22dUiDPn+s= github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.20.6/go.mod h1:OXVdAo9jNhggB+hJRGOyy7WolGTKB6Rg7IIulDeSzPM=
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.14.4 h1:29SvnfGhXjTl8ONxFwbj2rs6lbhiFXD2CgFQmbT/bXY= github.com/aws/aws-sdk-go-v2/service/s3 v1.114.4 h1:MrkWRB58Qw5TEkb51QVooVLjlM3IevO2iVXEz74B8pg=
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.14.4/go.mod h1:wm04I5DMuNVvZHFe/dHnUxincvNbbK7AiNBbYsQivek= github.com/aws/aws-sdk-go-v2/service/s3 v1.114.4/go.mod h1:yfIxaKRHasvfy6tNEm3/LpqKsupMzQjMaWj9Y0jMVbo=
github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.20.4 h1:pPiWfgeNxqluKEph7hvU88kuGKBPOWzO+Dk9t2zqqNs= github.com/aws/aws-sdk-go-v2/service/signin v1.10.4 h1:tvpDjuUvgKURf3Yk4hOaGbZ4QdY+070OWcA5d6LUv2A=
github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.20.4/go.mod h1:YlwGoIUDG/3kBQbdNOVs/xKZ9J01G8e/6D1mRBj9uTk= github.com/aws/aws-sdk-go-v2/service/signin v1.10.4/go.mod h1:3ibVKg5Ng82Zby8++jELTD2nHxiPk2DJRLEeW/LKp8M=
github.com/aws/aws-sdk-go-v2/service/s3 v1.114.0 h1:VMAdYqr4Jn/8ATs9BHC5riwrs0d6m1Z2ohFriSwZwm0= github.com/aws/aws-sdk-go-v2/service/sso v1.38.4 h1:ChCtagixSFOxltv0o6E3NT8F7ksvZtZGPwUBynO5Nmk=
github.com/aws/aws-sdk-go-v2/service/s3 v1.114.0/go.mod h1:9APRWGLFITKD+xzWSIyT9V7QV4bNlEuIieWlzXgGFlI= github.com/aws/aws-sdk-go-v2/service/sso v1.38.4/go.mod h1:+FEO9jrVMpc9oN3CdAxJbtlQEu3z8UddDPSedpeM3PY=
github.com/aws/aws-sdk-go-v2/service/signin v1.10.1 h1:DzCCWLzcIRQ77F3DEUljud7bEjTgFOIKXP52NmVRyhU= github.com/aws/aws-sdk-go-v2/service/ssooidc v1.43.4 h1:j6c+HA4AoS0EBEjArPjavFEBrucJEryfrQU0TffmACk=
github.com/aws/aws-sdk-go-v2/service/signin v1.10.1/go.mod h1:xpo/geVldu8payT375WekctUzopG/hBU7miiqItMUlw= github.com/aws/aws-sdk-go-v2/service/ssooidc v1.43.4/go.mod h1:RhghaXUk9q66VtOQUX1FdPddQuHnqQZzbB0fEYXmPRA=
github.com/aws/aws-sdk-go-v2/service/sso v1.38.1 h1:Umtl/0YZhng4xndfW3lKJrYYP7NLEjI6bGXVomwLcs0= github.com/aws/aws-sdk-go-v2/service/sts v1.51.4 h1:OKEfbf2tcfsF2pBk/S9QqNpo6alaAtiBs4hysCsBjPw=
github.com/aws/aws-sdk-go-v2/service/sso v1.38.1/go.mod h1:rRD/dnm7q0HYE/I5TMaPgkWyyUGLcwuxHLABsLnQ3e0= github.com/aws/aws-sdk-go-v2/service/sts v1.51.4/go.mod h1:mCd6qGo9b8hTtfjgsmNkFlzwjyce4owd7HDVFnCLXhM=
github.com/aws/aws-sdk-go-v2/service/ssooidc v1.43.1 h1:orIWdNiLgzrhu/11RcPPKO/SBzUUymbUQuZbSPImghg= github.com/aws/smithy-go v1.28.6 h1:Pj+/sUviNYjow8ELRtNwKHZ9ECeF+7pATX3+shjLIrw=
github.com/aws/aws-sdk-go-v2/service/ssooidc v1.43.1/go.mod h1:skwM/xsbR/1ReUTesv9BhpJp1VjajR7DWQnuVLwiXsQ= github.com/aws/smithy-go v1.28.6/go.mod h1:YE2RhdIuDbA5E5bTdciG9KrW3+TiEONeUWCqxX9i1Fc=
github.com/aws/aws-sdk-go-v2/service/sts v1.51.1 h1:0HOqZXRvMytH6bFHVIc0oJX07sZjfhz0zXtjs6gdE8s=
github.com/aws/aws-sdk-go-v2/service/sts v1.51.1/go.mod h1:26zA0GhDrLo+yiLI2yXWxqB1PdsShfLikoI7GOEgugM=
github.com/aws/smithy-go v1.28.1 h1:R/nXH00c8qcfCzQVELtRw+eLQWtzv+VAIEFJ1/xxXlQ=
github.com/aws/smithy-go v1.28.1/go.mod h1:YE2RhdIuDbA5E5bTdciG9KrW3+TiEONeUWCqxX9i1Fc=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/decred/dcrd/dcrec/secp256k1/v4 v4.4.1 h1:5RVFMOWjMyRy8cARdy79nAmgYw3hK/4HUq48LQ6Wwqo= github.com/dustin/go-humanize v1.1.0 h1:dbKTrvD0klcbBV/h4AWJdMuZogJACoMlvWIWZ5b2xWg=
github.com/decred/dcrd/dcrec/secp256k1/v4 v4.4.1/go.mod h1:ZXNYxsqcloTdSy/rNShjYzMhyjf0LaoftYK0p+A3h40= github.com/dustin/go-humanize v1.1.0/go.mod h1:hc1CvRkJMsgxqjmjMQF3QNRAZBwY8AXBAzKYoSX9sFI=
github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY= github.com/ebitengine/purego v0.11.2 h1:WWiTx8rD8zYdOwSj8O/NiNbsOvSAgJMTlyV1XlbUSeU=
github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto= github.com/ebitengine/purego v0.11.2/go.mod h1:DCHPP08djqhNSoTfImcnHYQRZmd0qhakvrozqaEYhGQ=
github.com/ebitengine/purego v0.10.1 h1:dewVBCBT2GaMu1SrNTYxQhgQBethzfhiwvZiLGP/qyY= github.com/gabriel-vasile/mimetype v1.4.16 h1:5izNFuvA37st1dDRAcA7TtmngBmRgiIPDmTtiEvjx1E=
github.com/ebitengine/purego v0.10.1/go.mod h1:iIjxzd6CiRiOG0UyXP+V1+jWqUXVjPKLAI0mRfJZTmQ= github.com/gabriel-vasile/mimetype v1.4.16/go.mod h1:3oFFwxX8kTklZwzIl2aQEDZT0lKY8xH92ST88bAwba4=
github.com/fatih/color v1.18.0 h1:S8gINlzdQ840/4pfAwic/ZE0djQEH3wM94VfqLTZcOM=
github.com/fatih/color v1.18.0/go.mod h1:4FelSpRwEGDpQ12mAdzqdOukCy4u8WUtOY6lkT/6HfU=
github.com/gabriel-vasile/mimetype v1.4.11 h1:AQvxbp830wPhHTqc1u7nzoLT+ZFxGY7emj5DR5DYFik=
github.com/gabriel-vasile/mimetype v1.4.11/go.mod h1:d+9Oxyo1wTzWdyVUPMmXFvp4F9tea18J8ufA774AB3s=
github.com/gen2brain/webp v0.6.4 h1:SUDdmxADOAiPQ+5ylNmuHhuYf2dOi0KgKZHL5vpVCNU= github.com/gen2brain/webp v0.6.4 h1:SUDdmxADOAiPQ+5ylNmuHhuYf2dOi0KgKZHL5vpVCNU=
github.com/gen2brain/webp v0.6.4/go.mod h1:iGWMaCSw7t3I/Cv9llzEKmpnR36S8lS8VL/ZVjxU0JE= github.com/gen2brain/webp v0.6.4/go.mod h1:iGWMaCSw7t3I/Cv9llzEKmpnR36S8lS8VL/ZVjxU0JE=
github.com/glebarez/go-sqlite v1.22.0 h1:uAcMJhaA6r3LHMTFgP0SifzgXg46yJkgxqyuyec+ruQ= github.com/glebarez/go-sqlite v1.23.0 h1:FyhIq4jqmgphQAUlY79zPldYGwISEZikaDfhiGWkkaI=
github.com/glebarez/go-sqlite v1.22.0/go.mod h1:PlBIdHe0+aUEFn+r2/uthrWq4FxbzugL0L8Li6yQJbc= github.com/glebarez/go-sqlite v1.23.0/go.mod h1:IIYrOH3L0rHY3jb4IXOHoWdklNajSGUN2eJcvK8WrnI=
github.com/glebarez/sqlite v1.11.0 h1:wSG0irqzP6VurnMEpFGer5Li19RpIRi2qvQz++w0GMw= github.com/glebarez/sqlite v1.11.0 h1:wSG0irqzP6VurnMEpFGer5Li19RpIRi2qvQz++w0GMw=
github.com/glebarez/sqlite v1.11.0/go.mod h1:h8/o8j5wiAsqSPoWELDUdJXhjAhsVliSn7bWZjOhrgQ= github.com/glebarez/sqlite v1.11.0/go.mod h1:h8/o8j5wiAsqSPoWELDUdJXhjAhsVliSn7bWZjOhrgQ=
github.com/go-chi/chi/v5 v5.2.3 h1:WQIt9uxdsAbgIYgid+BpYc+liqQZGMHRaUwp0JUcvdE= github.com/go-chi/chi/v5 v5.5.0 h1:xdKQ1dJmVJsmgahrXSKhUx8NyVPzpwdlyrrQFpMPJgg=
github.com/go-chi/chi/v5 v5.2.3/go.mod h1:L2yAIGWB3H+phAw1NxKwWM+7eUH/lU8pOMm5hHcoops= github.com/go-chi/chi/v5 v5.5.0/go.mod h1:d1IG7GtKPSjPyBP365PH8sAGVHk3qfB/IhjFNRH1wWM=
github.com/go-chi/cors v1.2.2 h1:Jmey33TE+b+rB7fT8MUy1u0I4L+NARQlK6LhzKPSyQE=
github.com/go-chi/cors v1.2.2/go.mod h1:sSbTewc+6wYHBBCW7ytsFSn836hqM7JxpglAy2Vzc58=
github.com/go-chi/jwtauth/v5 v5.4.0 h1:Ieh0xMJsFvqylqJ02/mQHKzbbKO9DYNBh4DPKCwTwYI=
github.com/go-chi/jwtauth/v5 v5.4.0/go.mod h1:w6yjqUUXz1b8+oiJel64Sz1KJwduQM6qUA5QNzO5+bQ=
github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s= github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s=
github.com/go-playground/assert/v2 v2.2.0/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4= github.com/go-playground/assert/v2 v2.2.0/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4=
github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA= github.com/go-playground/locales v0.14.2 h1:d8UmcrM6Nip0hfGZKLGpAvZH37XB4TS0xzK9B56YNCY=
github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY= github.com/go-playground/locales v0.14.2/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY=
github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY= github.com/go-playground/universal-translator v0.18.2 h1:LCsMLC9RzmbUMNUPVYD15dmcjwYAJhmX8mPZRW4rAVU=
github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY= github.com/go-playground/universal-translator v0.18.2/go.mod h1:67VZIMp5lQpDWlnStOct22q1bkdJGJqHghbOtmkawxk=
github.com/go-playground/validator/v10 v10.28.0 h1:Q7ibns33JjyW48gHkuFT91qX48KG0ktULL6FgHdG688= github.com/go-playground/validator/v10 v10.30.5 h1:YyCXvVShZbs2Sm3Mb53eNOlhRXctSOzW5QJAouCTZL4=
github.com/go-playground/validator/v10 v10.28.0/go.mod h1:GoI6I1SjPBh9p7ykNE/yj3fFYbyDOpwMn5KXd+m2hUU= github.com/go-playground/validator/v10 v10.30.5/go.mod h1:wEqiaov48pXX1kjhc3Da8y0M0Dtg/BK7gurFBLgwFrQ=
github.com/go-sql-driver/mysql v1.8.1 h1:LedoTUt/eveggdHS9qUFC1EFSa8bU2+1pZjSRpvNJ1Y= github.com/go-sql-driver/mysql v1.10.1 h1:arlSnNLq6a5yxGxV7qg9lF4j0C+KwD6NbQyKr9QL6ME=
github.com/go-sql-driver/mysql v1.8.1/go.mod h1:wEBSXgmK//2ZFJyE+qWnIsVGmvmEKlqwuVSjsCm7DZg= github.com/go-sql-driver/mysql v1.10.1/go.mod h1:M+cqaI7+xxXGG9swrdeUIoPG3Y3KCkF0pZej+SK+nWk=
github.com/goccy/go-json v0.10.6 h1:p8HrPJzOakx/mn/bQtjgNjdTcN+/S6FcG2CTtQOrHVU= github.com/google/pprof v0.0.0-20261016150608-1facf8f91b50 h1:PlNWJRxu5APSV0pWqfIsZ0qt9OOGHSWfZQ4zvx+WgWs=
github.com/goccy/go-json v0.10.6/go.mod h1:oq7eo15ShAhp70Anwd5lgX2pLfOS3QCiwU/PULtXL6M= github.com/google/pprof v0.0.0-20261016150608-1facf8f91b50/go.mod h1:yUo1AMMpsPIDFGuwDK8nLcf8+vvAd5l2O6JDZ6hpwrM=
github.com/google/pprof v0.0.0-20250317173921-a4b03ec1a45e h1:ijClszYn+mADRFY17kjQEVQ1XRhq2/JR1M3sGqeJoxs=
github.com/google/pprof v0.0.0-20250317173921-a4b03ec1a45e/go.mod h1:boTsfXsheKC2y+lKOCMpSfarhxDeIzfZG1jqGcPl3cA=
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/hashicorp/golang-lru/v2 v2.0.7 h1:a+bsQ5rvGLjzHuww6tVxozPZFVghXaHOwFs4luLUK2k= github.com/hashicorp/golang-lru/v2 v2.0.7 h1:a+bsQ5rvGLjzHuww6tVxozPZFVghXaHOwFs4luLUK2k=
github.com/hashicorp/golang-lru/v2 v2.0.7/go.mod h1:QeFd9opnmA6QUJc5vARoKUSoFhyfM2/ZepoAG6RGpeM= github.com/hashicorp/golang-lru/v2 v2.0.7/go.mod h1:QeFd9opnmA6QUJc5vARoKUSoFhyfM2/ZepoAG6RGpeM=
github.com/hokaccha/go-prettyjson v0.0.0-20211117102719-0474bc63780f h1:7LYC+Yfkj3CTRcShK0KOL/w6iTiKyqqBA9a41Wnggw8=
github.com/hokaccha/go-prettyjson v0.0.0-20211117102719-0474bc63780f/go.mod h1:pFlLw2CfqZiIBOx6BuCeRLCrfxBJipTY0nIOF/VbGcI=
github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM= github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM=
github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg= github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg=
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo= github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo=
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM= github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM=
github.com/jackc/pgx/v5 v5.10.0 h1:VhSvgU2jSli8o3AqIEOTJr7rZwAEUVo4E4XhR94Zfr0= github.com/jackc/pgx/v5 v5.11.0 h1:IzBBtyK9AHqf98cctWFifYSci2hgQR/cd56wB4p+ogg=
github.com/jackc/pgx/v5 v5.10.0/go.mod h1:mal1tBGAFfLHvZzaYh77YS/eC6IX9OWbRV1QIIM0Jn4= github.com/jackc/pgx/v5 v5.11.0/go.mod h1:mal1tBGAFfLHvZzaYh77YS/eC6IX9OWbRV1QIIM0Jn4=
github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo= github.com/jackc/puddle/v2 v2.2.3 h1:f8HoREISb3l5eO9coPgK7U3hKLhWGokOFVcThl5jrao=
github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4= github.com/jackc/puddle/v2 v2.2.3/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4=
github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E= github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E=
github.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc= github.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc=
github.com/jinzhu/now v1.1.5 h1:/o9tlHleP7gOFmsnYNz3RGnqzefHA47wQpKrrdTIwXQ= github.com/jinzhu/now v1.1.5 h1:/o9tlHleP7gOFmsnYNz3RGnqzefHA47wQpKrrdTIwXQ=
github.com/jinzhu/now v1.1.5/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8= github.com/jinzhu/now v1.1.5/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8=
github.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0= github.com/leodido/go-urn v1.5.0 h1:pLqT2kq1zpHW/1D18QMjMpdtX7cekxqtJJjg5ANyWw0=
github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4= github.com/leodido/go-urn v1.5.0/go.mod h1:9BORnCDhdPBJNDEX+w1bJisa8yOKYi116VeO96s4ifE=
github.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ= github.com/mattn/go-isatty v0.0.24 h1:tGZZoVgT/KiqK1c8ocVLeDS8BSWMRd47J3Lbz7vsReI=
github.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI= github.com/mattn/go-isatty v0.0.24/go.mod h1:nMCL3Zebbrt45jsMDgnfIwz6ydEQApk5oEI3HqDio6A=
github.com/lestrrat-go/blackmagic v1.0.4 h1:IwQibdnf8l2KoO+qC3uT4OaTWsW7tuRQXy9TRN9QanA=
github.com/lestrrat-go/blackmagic v1.0.4/go.mod h1:6AWFyKNNj0zEXQYfTMPfZrAXUWUfTIZ5ECEUEJaijtw=
github.com/lestrrat-go/dsig v1.4.0 h1:g7LUjK8cT74A5DzBXJI5HzsJuLhoYN0Wzj4nuOMIrH8=
github.com/lestrrat-go/dsig v1.4.0/go.mod h1:I8Nddg/vN2cUl/h8N7SRRApLnNNeyZPIqLYpvpOtGGo=
github.com/lestrrat-go/dsig-secp256k1 v1.0.0 h1:JpDe4Aybfl0soBvoVwjqDbp+9S1Y2OM7gcrVVMFPOzY=
github.com/lestrrat-go/dsig-secp256k1 v1.0.0/go.mod h1:CxUgAhssb8FToqbL8NjSPoGQlnO4w3LG1P0qPWQm/NU=
github.com/lestrrat-go/httpcc v1.0.1 h1:ydWCStUeJLkpYyjLDHihupbn2tYmZ7m22BGkcvZZrIE=
github.com/lestrrat-go/httpcc v1.0.1/go.mod h1:qiltp3Mt56+55GPVCbTdM9MlqhvzyuL6W/NMDA8vA5E=
github.com/lestrrat-go/httprc/v3 v3.0.6 h1:4FpLQ18KK/ypPbVU3NLWJNRvH3kcYiqKqWfKGqNWxxI=
github.com/lestrrat-go/httprc/v3 v3.0.6/go.mod h1:mSMtkZW92Z98M5YoNNztbRGxbXHql7tSitCvaxvo9l0=
github.com/lestrrat-go/jwx/v3 v3.3.0 h1:OXcYvQOQ7cxWzeZ/Q9sYk8ABe/kCSI371WmuACiCT+4=
github.com/lestrrat-go/jwx/v3 v3.3.0/go.mod h1:eIJhDcKHBwcgxqv8RiIylV67TVl1wJp/265IAHY1Db8=
github.com/lestrrat-go/option/v2 v2.0.0 h1:XxrcaJESE1fokHy3FpaQ/cXW8ZsIdWcdFzzLOcID3Ss=
github.com/lestrrat-go/option/v2 v2.0.0/go.mod h1:oSySsmzMoR0iRzCDCaUfsCzxQHUEuhOViQObyy7S6Vg=
github.com/mattn/go-colorable v0.1.14 h1:9A9LHSqF/7dyVVX6g0U9cwm9pG3kP9gSzcuIPHPsaIE=
github.com/mattn/go-colorable v0.1.14/go.mod h1:6LmQG8QLFO4G5z1gPvYEzlUgJ2wF+stgPZH1UqBm1s8=
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
github.com/mattn/go-sqlite3 v1.14.22 h1:2gZY6PC6kBnID23Tichd1K+Z0oS6nE/XwU+Vz/5o4kU= github.com/mattn/go-sqlite3 v1.14.22 h1:2gZY6PC6kBnID23Tichd1K+Z0oS6nE/XwU+Vz/5o4kU=
github.com/mattn/go-sqlite3 v1.14.22/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y= github.com/mattn/go-sqlite3 v1.14.22/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y=
github.com/ncruces/go-strftime v1.0.0 h1:HMFp8mLCTPp341M/ZnA4qaf7ZlsbTc+miZjCLOFAw7w= github.com/ncruces/go-strftime v1.1.0 h1:vtPmPWMkb539RGV9WpWT9EwJGvrOCKvMNI4obWL47Hk=
github.com/ncruces/go-strftime v1.0.0/go.mod h1:Fwc5htZGVVkseilnfgOVb9mKy6w1naJmn9CehxcKcls= github.com/ncruces/go-strftime v1.1.0/go.mod h1:yVaq7iwCN09vHRrKBrrflXT0M9tTMG2KmZ9Fj7xeG/g=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE= github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE=
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo= github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=
github.com/segmentio/asm v1.2.1 h1:DTNbBqs57ioxAD4PrArqftgypG4/qNpXoJx8TVXxPR0=
github.com/segmentio/asm v1.2.1/go.mod h1:BqMnlJP91P8d+4ibuonYZw9mfnzI9HfxselHZr5aAcs=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.12.1 h1:EuwCh5fleGS7H32xRwO3wRGT7DxrDhLAT6FF8MpWDWE= github.com/stretchr/testify v1.12.1 h1:EuwCh5fleGS7H32xRwO3wRGT7DxrDhLAT6FF8MpWDWE=
github.com/stretchr/testify v1.12.1/go.mod h1:MDEgiDPPsNp5cuIrHPPCyornHKgEVbtFUmoNlxoYthg= github.com/stretchr/testify v1.12.1/go.mod h1:MDEgiDPPsNp5cuIrHPPCyornHKgEVbtFUmoNlxoYthg=
github.com/valyala/fastjson v1.6.10 h1:/yjJg8jaVQdYR3arGxPE2X5z89xrlhS0eGXdv+ADTh4=
github.com/valyala/fastjson v1.6.10/go.mod h1:e6FubmQouUNP73jtMLmcbxS6ydWIpOfhz34TSfO3JaE=
go.yaml.in/yaml/v3 v3.0.5 h1:N6y/pJk8buWs9NY5ERU2HSMfm+IuD/OtfdAnq6kESPw= go.yaml.in/yaml/v3 v3.0.5 h1:N6y/pJk8buWs9NY5ERU2HSMfm+IuD/OtfdAnq6kESPw=
go.yaml.in/yaml/v3 v3.0.5/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg= go.yaml.in/yaml/v3 v3.0.5/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg=
golang.org/x/crypto v0.57.0 h1:3ZVCjf8Ggz7zneR/EHRVx68Ctf+2pmIMP2UFhh9cC6M= golang.org/x/crypto v0.58.0 h1:COkYLr4k7nDI4r6QtMML2AfzeIswWHAJthLS6K/M/54=
golang.org/x/crypto v0.57.0/go.mod h1:Fdz0i5U6CoizGwLda9DttjSk6qlZo25zYNtR+ycvuZA= golang.org/x/crypto v0.58.0/go.mod h1:Xh+kl5A+M0gMiWDytH2Hhr5Z7WbNCpv/eB/EFgfSk+w=
golang.org/x/exp v0.0.0-20251113190631-e25ba8c21ef6 h1:zfMcR1Cs4KNuomFFgGefv5N0czO2XZpUbxGUy8i8ug0= golang.org/x/image v0.47.0 h1:za/8gVz++PPZqmZJBNSISICN5Rrj5zixP/8K++fgmqo=
golang.org/x/exp v0.0.0-20251113190631-e25ba8c21ef6/go.mod h1:46edojNIoXTNOhySWIWdix628clX9ODXwPsQuG6hsK0= golang.org/x/image v0.47.0/go.mod h1:IkN5o4A7vq55vXN8FWjjnhg9Rs2GOtffqsSi9mWAKYE=
golang.org/x/image v0.46.0 h1:b1+oYj0Jbp6K5MDT4i4/eZpYlk3V8SJhhDKh6LBHAyQ= golang.org/x/mod v0.42.0 h1:ICeL3t2L30ljSPHHxDnR4fqVcBt/zR2zJAb9juavmQg=
golang.org/x/image v0.46.0/go.mod h1:3B3W05VGVQyuXucLINLjXKrqISASfi4Xj+iCVkLMwew= golang.org/x/mod v0.42.0/go.mod h1:u5fzIrRInkL8MaO1cbRkUHT64v303YIT5KEqpNr7jRs=
golang.org/x/mod v0.41.0 h1:qJmnOUb4YB+FsEuM3HcWucdZASCPGhsX6uljO6pog0c= golang.org/x/net v0.61.0 h1:RR+6j/BTBCrggOLugxa+66R8FvoN6MHlzDlZIbN9YFw=
golang.org/x/mod v0.41.0/go.mod h1:Ek9pY8RKWXwsWvd3rQiHYtMqkjSUV+s1Rj7j4H5Ur6o= golang.org/x/net v0.61.0/go.mod h1:WgDCOTH8iwtB66T4/GfI94AHo/hhdb7Hah9NDseQfiI=
golang.org/x/net v0.59.0 h1:5zfYln+w5XCxwrnMMJPufRgNoXEaGxl0wo5GqPXyues= golang.org/x/sync v0.24.0 h1:iqiDrGoDgyuvAKrhLQthUEzU/R378N78gXbBjxed7oA=
golang.org/x/net v0.59.0/go.mod h1:2DA/G1UfVbCpQPeWTmMPGY7Cs2PkBkwu743bVX5PIVg= golang.org/x/sync v0.24.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0=
golang.org/x/sync v0.23.0 h1:KameEIfc1IkluZyXWLn39Wd4tURc6GbCiISGiZm2bQk= golang.org/x/sys v0.49.0 h1:XbzkgYJHdqh/8m2Uu0W/dQv8nktxx4BFHp1M0gROTXA=
golang.org/x/sync v0.23.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0= golang.org/x/sys v0.49.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/text v0.43.0 h1:1QivrlhwAsnMOcqgOdl9my7s9OyZl8O5/UGUTJVXoWc=
golang.org/x/sys v0.48.0 h1:bbX/i/6MgT9BVLM9RT1thmxL04yeTAhbEz4SyadbXoo= golang.org/x/text v0.43.0/go.mod h1:hbSIYA/amXcRXTFSZqh8tWHEoqRvvbKPJ2uz/KU+a+s=
golang.org/x/sys v0.48.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og= golang.org/x/tools v0.52.0 h1:ryxg4U63oaUYk7uOLTF37n43f4qgtGvqV4Ioit1BaEs=
golang.org/x/text v0.42.0 h1:JbOZXgfeCPU9gacVtYliJqOhD+zhrEqK4LfdpmlUZqI= golang.org/x/tools v0.52.0/go.mod h1:ItcP5UNaVGG+Yc4eIYmaFLNJ4soEopkx5Y2d4lcEurs=
golang.org/x/text v0.42.0/go.mod h1:ojzP1Z+2QtioaF8DTtO8K5q7JWVVYwZKenzujK0Zd0E=
golang.org/x/tools v0.49.0 h1:3NI7VXzL9+1WZD52Dx2ttoPwD5DWrFGpl9mFZDlmisI=
golang.org/x/tools v0.49.0/go.mod h1:SJNXV9DBKT0UbdttsQjbfJlAE/q+y36++zo3uL3N0Oo=
gopkg.in/alexcesaro/quotedprintable.v3 v3.0.0-20150716171945-2caba252f4dc h1:2gGKlE2+asNV9m7xrywl36YYNnBG5ZQ0r/BOOxqPpmk=
gopkg.in/alexcesaro/quotedprintable.v3 v3.0.0-20150716171945-2caba252f4dc/go.mod h1:m7x9LTH6d71AHyAX77c9yqWCCa3UKHcVEj9y7hAtKDk=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/gomail.v2 v2.0.0-20160411212932-81ebce5c23df h1:n7WqCuqOuCbNr617RXOY0AWRXxgwEyPp2z+p0+hgMuE=
gopkg.in/gomail.v2 v2.0.0-20160411212932-81ebce5c23df/go.mod h1:LRQQ+SO6ZHR7tOkpBDuZnXENFzX8qRjMDMyPD6BRkCw=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gorm.io/driver/mysql v1.6.0 h1:eNbLmNTpPpTOVZi8MMxCi2aaIm0ZpInbORNXDwyLGvg= gorm.io/driver/mysql v1.6.0 h1:eNbLmNTpPpTOVZi8MMxCi2aaIm0ZpInbORNXDwyLGvg=
gorm.io/driver/mysql v1.6.0/go.mod h1:D/oCC2GWK3M/dqoLxnOlaNKmXz8WNTfcS9y5ovaSqKo= gorm.io/driver/mysql v1.6.0/go.mod h1:D/oCC2GWK3M/dqoLxnOlaNKmXz8WNTfcS9y5ovaSqKo=
@@ -169,30 +123,30 @@ gorm.io/driver/sqlite v1.6.0 h1:WHRRrIiulaPiPFmDcod6prc4l2VGVWHz80KspNsxSfQ=
gorm.io/driver/sqlite v1.6.0/go.mod h1:AO9V1qIQddBESngQUKWL9yoH93HIeA1X6V633rBwyT8= gorm.io/driver/sqlite v1.6.0/go.mod h1:AO9V1qIQddBESngQUKWL9yoH93HIeA1X6V633rBwyT8=
gorm.io/gorm v1.31.2 h1:3o8FXNo9v9S858gil+3LlZA1LkCOzgb4g5BL64FgaCo= gorm.io/gorm v1.31.2 h1:3o8FXNo9v9S858gil+3LlZA1LkCOzgb4g5BL64FgaCo=
gorm.io/gorm v1.31.2/go.mod h1:XyQVbO2k6YkOis7C2437jSit3SsDK72s7n7rsSHd+Gs= gorm.io/gorm v1.31.2/go.mod h1:XyQVbO2k6YkOis7C2437jSit3SsDK72s7n7rsSHd+Gs=
modernc.org/cc/v4 v4.27.1 h1:9W30zRlYrefrDV2JE2O8VDtJ1yPGownxciz5rrbQZis= modernc.org/cc/v4 v4.30.3 h1:aDq8gIX1X7+VFgO/JYYji6pLWL2H4tv3g8WatT3KCys=
modernc.org/cc/v4 v4.27.1/go.mod h1:uVtb5OGqUKpoLWhqwNQo/8LwvoiEBLvZXIQ/SmO6mL0= modernc.org/cc/v4 v4.30.3/go.mod h1:OnovgIhbbMXMu1aISnJ0wvVD1KnW+cAUJkIrAWh+kVI=
modernc.org/ccgo/v4 v4.30.1 h1:4r4U1J6Fhj98NKfSjnPUN7Ze2c6MnAdL0hWw6+LrJpc= modernc.org/ccgo/v4 v4.37.0 h1:BAuJCUtIHIxFIYaFhqXIw5YaoMBlNCUlFovejHfMip4=
modernc.org/ccgo/v4 v4.30.1/go.mod h1:bIOeI1JL54Utlxn+LwrFyjCx2n2RDiYEaJVSrgdrRfM= modernc.org/ccgo/v4 v4.37.0/go.mod h1:/8627VhwWtAbqUXmPORxFQU5SgLrAx2jl9seLw9GBhY=
modernc.org/fileutil v1.3.40 h1:ZGMswMNc9JOCrcrakF1HrvmergNLAmxOPjizirpfqBA= modernc.org/fileutil v1.4.0 h1:j6ZzNTftVS054gi281TyLjHPp6CPHr2KCxEXjEbD6SM=
modernc.org/fileutil v1.3.40/go.mod h1:HxmghZSZVAz/LXcMNwZPA/DRrQZEVP9VX0V4LQGQFOc= modernc.org/fileutil v1.4.0/go.mod h1:EqdKFDxiByqxLk8ozOxObDSfcVOv/54xDs/DUHdvCUU=
modernc.org/gc/v2 v2.6.5 h1:nyqdV8q46KvTpZlsw66kWqwXRHdjIlJOhG6kxiV/9xI= modernc.org/gc/v2 v2.6.5 h1:nyqdV8q46KvTpZlsw66kWqwXRHdjIlJOhG6kxiV/9xI=
modernc.org/gc/v2 v2.6.5/go.mod h1:YgIahr1ypgfe7chRuJi2gD7DBQiKSLMPgBQe9oIiito= modernc.org/gc/v2 v2.6.5/go.mod h1:YgIahr1ypgfe7chRuJi2gD7DBQiKSLMPgBQe9oIiito=
modernc.org/gc/v3 v3.1.1 h1:k8T3gkXWY9sEiytKhcgyiZ2L0DTyCQ/nvX+LoCljoRE= modernc.org/gc/v3 v3.2.0 h1:/Y3LGDMQaoYf55PebP1qsZ5FDGgAZyG1RYKEHeQzh1o=
modernc.org/gc/v3 v3.1.1/go.mod h1:HFK/6AGESC7Ex+EZJhJ2Gni6cTaYpSMmU/cT9RmlfYY= modernc.org/gc/v3 v3.2.0/go.mod h1:HFK/6AGESC7Ex+EZJhJ2Gni6cTaYpSMmU/cT9RmlfYY=
modernc.org/goabi0 v0.2.0 h1:HvEowk7LxcPd0eq6mVOAEMai46V+i7Jrj13t4AzuNks= modernc.org/goabi0 v0.2.0 h1:HvEowk7LxcPd0eq6mVOAEMai46V+i7Jrj13t4AzuNks=
modernc.org/goabi0 v0.2.0/go.mod h1:CEFRnnJhKvWT1c1JTI3Avm+tgOWbkOu5oPA8eH8LnMI= modernc.org/goabi0 v0.2.0/go.mod h1:CEFRnnJhKvWT1c1JTI3Avm+tgOWbkOu5oPA8eH8LnMI=
modernc.org/libc v1.67.0 h1:QzL4IrKab2OFmxA3/vRYl0tLXrIamwrhD6CKD4WBVjQ= modernc.org/libc v1.79.0 h1:9Dvvv++bAMSkSuBzuOFAatbTV5OIoq6Y6FohmD3e7q8=
modernc.org/libc v1.67.0/go.mod h1:QvvnnJ5P7aitu0ReNpVIEyesuhmDLQ8kaEoyMjIFZJA= modernc.org/libc v1.79.0/go.mod h1:uT3kR61NsbeKJSLqq83GJwSnZMVLlSjyAz4DfTaBy1M=
modernc.org/mathutil v1.7.1 h1:GCZVGXdaN8gTqB1Mf/usp1Y/hSqgI2vAGGP4jZMCxOU= modernc.org/mathutil v1.7.1 h1:GCZVGXdaN8gTqB1Mf/usp1Y/hSqgI2vAGGP4jZMCxOU=
modernc.org/mathutil v1.7.1/go.mod h1:4p5IwJITfppl0G4sUEDtCr4DthTaT47/N3aT6MhfgJg= modernc.org/mathutil v1.7.1/go.mod h1:4p5IwJITfppl0G4sUEDtCr4DthTaT47/N3aT6MhfgJg=
modernc.org/memory v1.11.0 h1:o4QC8aMQzmcwCK3t3Ux/ZHmwFPzE6hf2Y5LbkRs+hbI= modernc.org/memory v1.12.1 h1:nFMiWrpStgZczNl6XI9GnIk/rWhYIyHGUaR04pGbp9g=
modernc.org/memory v1.11.0/go.mod h1:/JP4VbVC+K5sU2wZi9bHoq2MAkCnrt2r98UGeSK7Mjw= modernc.org/memory v1.12.1/go.mod h1:/JP4VbVC+K5sU2wZi9bHoq2MAkCnrt2r98UGeSK7Mjw=
modernc.org/opt v0.1.4 h1:2kNGMRiUjrp4LcaPuLY2PzUfqM/w9N23quVwhKt5Qm8= modernc.org/opt v0.2.0 h1:tGyef5ApycA7FSEOMraay9SaTk5zmbx7Tu+cJs4QKZg=
modernc.org/opt v0.1.4/go.mod h1:03fq9lsNfvkYSfxrfUhZCWPk1lm4cq4N+Bh//bEtgns= modernc.org/opt v0.2.0/go.mod h1:03fq9lsNfvkYSfxrfUhZCWPk1lm4cq4N+Bh//bEtgns=
modernc.org/sortutil v1.2.1 h1:+xyoGf15mM3NMlPDnFqrteY07klSFxLElE2PVuWIJ7w= modernc.org/sortutil v1.2.1 h1:+xyoGf15mM3NMlPDnFqrteY07klSFxLElE2PVuWIJ7w=
modernc.org/sortutil v1.2.1/go.mod h1:7ZI3a3REbai7gzCLcotuw9AC4VZVpYMjDzETGsSMqJE= modernc.org/sortutil v1.2.1/go.mod h1:7ZI3a3REbai7gzCLcotuw9AC4VZVpYMjDzETGsSMqJE=
modernc.org/sqlite v1.40.1 h1:VfuXcxcUWWKRBuP8+BR9L7VnmusMgBNNnBYGEe9w/iY= modernc.org/sqlite v1.61.0 h1:sQi63oLQ9uquAUA4CzOisH35Q3pEszkPBuHM0tFL8CY=
modernc.org/sqlite v1.40.1/go.mod h1:9fjQZ0mB1LLP0GYrp39oOJXx/I2sxEnZtzCmEQIKvGE= modernc.org/sqlite v1.61.0/go.mod h1:f4gr5tbpx2umklaT/QVtbi/50hNdM+4ng+2zMo8KXJ0=
modernc.org/strutil v1.2.1 h1:UneZBkQA+DX2Rp35KcM69cSsNES9ly8mQWD71HKlOA0= modernc.org/strutil v1.2.1 h1:UneZBkQA+DX2Rp35KcM69cSsNES9ly8mQWD71HKlOA0=
modernc.org/strutil v1.2.1/go.mod h1:EHkiggD70koQxjVdSBM3JKM7k6L0FbGE5eymy9i3B9A= modernc.org/strutil v1.2.1/go.mod h1:EHkiggD70koQxjVdSBM3JKM7k6L0FbGE5eymy9i3B9A=
modernc.org/token v1.1.0 h1:Xl7Ap9dKaEs5kLoOQeQmPWevfnk/DM5qcLcYlA8ys6Y= modernc.org/token v1.1.0 h1:Xl7Ap9dKaEs5kLoOQeQmPWevfnk/DM5qcLcYlA8ys6Y=
@@ -25,6 +25,7 @@ const (
TypeBoolean FieldType = "boolean" TypeBoolean FieldType = "boolean"
TypeDate FieldType = "date" TypeDate FieldType = "date"
TypeSelect FieldType = "select" TypeSelect FieldType = "select"
TypeMedia FieldType = "media"
) )
const ( const (
+30
View File
@@ -20,6 +20,36 @@ var kinds = map[FieldType]kind{
TypeBoolean: {accepts: isBoolean}, TypeBoolean: {accepts: isBoolean},
TypeDate: {accepts: isDate, measure: dateDays, bound: dateDays, unique: true}, TypeDate: {accepts: isDate, measure: dateDays, bound: dateDays, unique: true},
TypeSelect: {accepts: isString, unique: true}, TypeSelect: {accepts: isString, unique: true},
TypeMedia: {accepts: isMediaID},
}
func MediaID(value any) (uint32, bool) {
switch typed := value.(type) {
case uint32:
return typed, typed >= 1
case int:
return mediaIDFromInt(int64(typed))
case int64:
return mediaIDFromInt(typed)
case float64:
if typed != math.Trunc(typed) || typed < 1 || typed > math.MaxUint32 {
return 0, false
}
return uint32(typed), true
}
return 0, false
}
func mediaIDFromInt(number int64) (uint32, bool) {
if number < 1 || number > math.MaxUint32 {
return 0, false
}
return uint32(number), true
}
func isMediaID(value any) bool {
_, ok := MediaID(value)
return ok
} }
func isString(value any) bool { func isString(value any) bool {
@@ -109,5 +109,33 @@ func (f Field) validDefault() bool {
if f.Default == nil { if f.Default == nil {
return true return true
} }
if f.Type == TypeMedia {
return false
}
return !f.Unique && f.Violation(f.Default) == "" return !f.Unique && f.Violation(f.Default) == ""
} }
type MediaRef struct {
Field Field
ID uint32
}
func MediaRefs(fields []Field, data map[string]any) []MediaRef {
var refs []MediaRef
for _, field := range MediaFields(fields) {
if id, set := MediaID(data[field.Key]); set {
refs = append(refs, MediaRef{Field: field, ID: id})
}
}
return refs
}
func MediaFields(fields []Field) []Field {
var media []Field
for _, field := range fields {
if field.Type == TypeMedia {
media = append(media, field)
}
}
return media
}
+18 -3
View File
@@ -51,12 +51,12 @@ func validateField(field contenttype.Field, data map[string]any) error {
value := data[field.Key] value := data[field.Key]
if value == nil { if value == nil {
if field.Required { if field.Required {
return invalidField(field.Key, RuleRequired) return InvalidField(field.Key, RuleRequired)
} }
return nil return nil
} }
if rule := field.Violation(value); rule != "" { if rule := field.Violation(value); rule != "" {
return invalidField(field.Key, rule) return InvalidField(field.Key, rule)
} }
return nil return nil
} }
@@ -76,7 +76,7 @@ func firstUnknownField(fields []contenttype.Field, data map[string]any) error {
return nil return nil
} }
sort.Strings(unknown) sort.Strings(unknown)
return invalidField(unknown[0], RuleUnknownField) return InvalidField(unknown[0], RuleUnknownField)
} }
func UniqueValues(fields []contenttype.Field, data map[string]any) []UniqueValue { func UniqueValues(fields []contenttype.Field, data map[string]any) []UniqueValue {
@@ -88,3 +88,18 @@ func UniqueValues(fields []contenttype.Field, data map[string]any) []UniqueValue
} }
return values return values
} }
func MediaIDs(fields []contenttype.Field, data map[string]any) map[string]uint32 {
ids := map[string]uint32{}
for _, ref := range contenttype.MediaRefs(fields, data) {
ids[ref.Field.Key] = ref.ID
}
return ids
}
func MissingMedia(field contenttype.Field, unchanged bool) error {
if unchanged {
return InvalidField(field.Key, RuleRequired)
}
return InvalidField(field.Key, contenttype.RuleType)
}
+1 -1
View File
@@ -55,7 +55,7 @@ func (e FieldError) Unwrap() error {
return e.Cause return e.Cause
} }
func invalidField(key string, rule string) error { func InvalidField(key string, rule string) error {
return FieldError{Key: key, Rule: rule, Cause: ErrInvalidEntry} return FieldError{Key: key, Rule: rule, Cause: ErrInvalidEntry}
} }
+49
View File
@@ -246,3 +246,52 @@ type Image struct {
CreatedAt time.Time `json:"created_at"` CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"` UpdatedAt time.Time `json:"updated_at"`
} }
func isStoredNameByte(char byte) bool {
return char == '-' || char == '_' || char == '.' || char >= '0' && char <= '9' || char >= 'a' && char <= 'z' || char >= 'A' && char <= 'Z'
}
func continuesName(body string, end int) bool {
if end >= len(body) || !isStoredNameByte(body[end]) {
return false
}
return body[end] != '.' || end+1 < len(body) && isStoredNameByte(body[end+1])
}
func storedNameMatches(body string, name string) []int {
var starts []int
if name == "" {
return starts
}
for from := 0; from < len(body); {
found := strings.Index(body[from:], name)
if found < 0 {
break
}
start := from + found
end := start + len(name)
from = start + 1
if start > 0 && isStoredNameByte(body[start-1]) || continuesName(body, end) {
continue
}
starts = append(starts, start)
from = end
}
return starts
}
func ContainsStoredName(body string, name string) bool {
return len(storedNameMatches(body, name)) > 0
}
func ReplaceStoredName(body string, from string, to string) string {
var rewritten strings.Builder
last := 0
for _, start := range storedNameMatches(body, from) {
rewritten.WriteString(body[last:start])
rewritten.WriteString(to)
last = start + len(from)
}
rewritten.WriteString(body[last:])
return rewritten.String()
}
@@ -0,0 +1,22 @@
package transaction
import (
"RenewCMS/internal/domain/article"
"RenewCMS/internal/domain/author"
"RenewCMS/internal/domain/entry"
"RenewCMS/internal/domain/image"
"RenewCMS/internal/domain/site"
"context"
)
type Repositories struct {
Articles article.Repository
Sites site.Repository
Authors author.Repository
Entries entry.Repository
Images image.Repository
}
type Transactor interface {
Run(ctx context.Context, work func(Repositories) error) error
}
+142
View File
@@ -0,0 +1,142 @@
package config
import (
"bufio"
"fmt"
"io"
"os"
"strings"
)
const (
dotenvExportPrefix = "export "
dotenvCommentMarker = "#"
dotenvInlineComment = " #"
dotenvByteOrderMark = "\xef\xbb\xbf"
dotenvMaxLineBytes = 1 << 20
dotenvAssignment = "="
dotenvDoubleQuote = '"'
dotenvSingleQuote = '\''
dotenvEscapeBackslash = '\\'
)
var dotenvDoubleQuoteEscapes = map[byte]byte{
'n': '\n',
'r': '\r',
't': '\t',
'"': '"',
'\\': '\\',
}
func LoadDotenv(path string) error {
file, err := os.Open(path)
if err != nil {
return err
}
defer func() { _ = file.Close() }()
values, err := ParseDotenv(file)
if err != nil {
return fmt.Errorf("%s: %w", path, err)
}
for name, value := range values {
if _, isSet := os.LookupEnv(name); !isSet {
if err := os.Setenv(name, value); err != nil {
return err
}
}
}
return nil
}
func ParseDotenv(reader io.Reader) (map[string]string, error) {
scanner := bufio.NewScanner(reader)
scanner.Buffer(make([]byte, 0, bufio.MaxScanTokenSize), dotenvMaxLineBytes)
values := map[string]string{}
for lineNumber := 1; scanner.Scan(); lineNumber++ {
line := strings.TrimSpace(strings.TrimPrefix(scanner.Text(), dotenvByteOrderMark))
if line == "" || strings.HasPrefix(line, dotenvCommentMarker) {
continue
}
name, value, err := parseDotenvAssignment(line)
if err != nil {
return nil, fmt.Errorf("line %d: %w", lineNumber, err)
}
values[name] = value
}
return values, scanner.Err()
}
func parseDotenvAssignment(line string) (string, string, error) {
line = strings.TrimSpace(strings.TrimPrefix(line, dotenvExportPrefix))
name, raw, found := strings.Cut(line, dotenvAssignment)
name = strings.TrimSpace(name)
if !found || !isDotenvName(name) {
return "", "", fmt.Errorf("expected NAME=value")
}
value, err := parseDotenvValue(strings.TrimSpace(raw))
return name, value, err
}
func isDotenvName(name string) bool {
if name == "" {
return false
}
for _, r := range name {
isLetter := r >= 'a' && r <= 'z' || r >= 'A' && r <= 'Z'
isDigit := r >= '0' && r <= '9'
if !isLetter && !isDigit && r != '_' && r != '.' {
return false
}
}
return true
}
func parseDotenvValue(raw string) (string, error) {
if raw == "" {
return "", nil
}
switch raw[0] {
case dotenvDoubleQuote:
return parseDoubleQuoted(raw)
case dotenvSingleQuote:
return parseSingleQuoted(raw)
}
if comment := strings.Index(raw, dotenvInlineComment); comment >= 0 {
raw = raw[:comment]
}
return strings.TrimSpace(raw), nil
}
func parseSingleQuoted(raw string) (string, error) {
end := strings.IndexByte(raw[1:], dotenvSingleQuote)
if end < 0 {
return "", fmt.Errorf("unterminated single quote")
}
return raw[1 : 1+end], nil
}
func parseDoubleQuoted(raw string) (string, error) {
var value strings.Builder
for i := 1; i < len(raw); i++ {
switch raw[i] {
case dotenvDoubleQuote:
return value.String(), nil
case dotenvEscapeBackslash:
i++
if i >= len(raw) {
return "", fmt.Errorf("unterminated double quote")
}
if unescaped, known := dotenvDoubleQuoteEscapes[raw[i]]; known {
value.WriteByte(unescaped)
} else {
value.WriteByte(dotenvEscapeBackslash)
value.WriteByte(raw[i])
}
default:
value.WriteByte(raw[i])
}
}
return "", fmt.Errorf("unterminated double quote")
}
+47
View File
@@ -0,0 +1,47 @@
package mailer
import (
"RenewCMS/internal/infrastructure/config"
"errors"
"net/smtp"
"strings"
)
type loginAuth struct {
username string
password string
}
func (a *loginAuth) Start(server *smtp.ServerInfo) (string, []byte, error) {
if !server.TLS && !isLoopback(server.Name) {
return "", nil, errors.New("refusing to send credentials over an unencrypted connection")
}
return "LOGIN", nil, nil
}
func (a *loginAuth) Next(fromServer []byte, more bool) ([]byte, error) {
if !more {
return nil, nil
}
switch strings.ToLower(strings.TrimSpace(string(fromServer))) {
case "username:":
return []byte(a.username), nil
case "password:":
return []byte(a.password), nil
}
return nil, errors.New("unexpected server challenge")
}
func isLoopback(host string) bool {
return host == "localhost" || host == "127.0.0.1" || host == "::1"
}
func selectAuth(mechanisms string, settings config.SmtpSettings) smtp.Auth {
advertised := strings.Fields(strings.ToUpper(mechanisms))
for _, mechanism := range advertised {
if mechanism == "PLAIN" {
return smtp.PlainAuth("", settings.Login, settings.Password, settings.Host)
}
}
return &loginAuth{username: settings.Login, password: settings.Password}
}
@@ -4,22 +4,47 @@ import (
domain "RenewCMS/internal/domain/mail" domain "RenewCMS/internal/domain/mail"
"RenewCMS/internal/infrastructure/config" "RenewCMS/internal/infrastructure/config"
"bytes" "bytes"
"crypto/tls"
"embed" "embed"
"html/template" "html/template"
"log" "log"
"time"
"gopkg.in/gomail.v2"
) )
type MailRepository struct { type MailRepository struct {
smtp config.SmtpSettings transport transport
sender string
now func() time.Time
}
type Option func(*options)
type options struct {
tlsConfig *tls.Config
now func() time.Time
}
func WithTLSConfig(tlsConfig *tls.Config) Option {
return func(o *options) { o.tlsConfig = tlsConfig }
}
func WithClock(now func() time.Time) Option {
return func(o *options) { o.now = now }
} }
//go:embed templates/* //go:embed templates/*
var mailTemplateFiles embed.FS var mailTemplateFiles embed.FS
func NewMailRepository(smtp config.SmtpSettings) *MailRepository { func NewMailRepository(smtp config.SmtpSettings, opts ...Option) *MailRepository {
return &MailRepository{smtp: smtp} configured := options{now: time.Now}
for _, opt := range opts {
opt(&configured)
}
return &MailRepository{
transport: newTransport(smtp, configured.tlsConfig),
sender: smtp.Sender,
now: configured.now,
}
} }
const defaultSubject = "RenewCMS | Action required" const defaultSubject = "RenewCMS | Action required"
@@ -60,28 +85,23 @@ func (m MailRepository) Render(templateName string, data any) (string, string, e
} }
func (m MailRepository) Send(receiverAddress string, templateName string, data any) error { func (m MailRepository) Send(receiverAddress string, templateName string, data any) error {
login := m.smtp.Login
sender := m.smtp.Sender
password := m.smtp.Password
smtpHost := m.smtp.Host
smtpPort := m.smtp.Port
d := gomail.NewDialer(smtpHost, smtpPort, login, password)
subject, body, err := m.Render(templateName, data) subject, body, err := m.Render(templateName, data)
if err != nil { if err != nil {
return err return err
} }
msg := gomail.NewMessage() msg, err := newMessage(m.sender, receiverAddress, subject, body, m.now())
msg.SetHeaders(map[string][]string{ if err != nil {
"From": {"RenewCMS <" + sender + ">"}, log.Println("error when building email:", err)
"To": {receiverAddress}, return err
"Subject": {subject}, }
}) payload, err := msg.bytes()
msg.SetBody("text/html", body) if err != nil {
log.Println("error when encoding email:", err)
return err
}
if err := d.DialAndSend(msg); err != nil { if err := m.transport.deliver(msg.from.Address, msg.to.Address, payload); err != nil {
log.Println("error when sending email:", err) log.Println("error when sending email:", err)
return err return err
} }
+90
View File
@@ -0,0 +1,90 @@
package mailer
import (
"bytes"
"crypto/rand"
"encoding/hex"
"errors"
"fmt"
"mime"
"mime/quotedprintable"
"net/mail"
"strings"
"time"
)
const (
senderDisplayName = "RenewCMS"
messageIDBytes = 16
lineBreak = "\r\n"
)
type message struct {
from mail.Address
to mail.Address
subject string
body string
sentAt time.Time
}
func newMessage(sender string, receiver string, subject string, body string, sentAt time.Time) (message, error) {
from, err := mail.ParseAddress(sender)
if err != nil {
return message{}, fmt.Errorf("invalid sender address: %w", err)
}
to, err := mail.ParseAddress(receiver)
if err != nil {
return message{}, fmt.Errorf("invalid receiver address: %w", err)
}
if strings.ContainsAny(subject, "\r\n") {
return message{}, errors.New("subject contains a line break")
}
return message{
from: mail.Address{Name: senderDisplayName, Address: from.Address},
to: *to,
subject: subject,
body: body,
sentAt: sentAt,
}, nil
}
func (m message) messageID() (string, error) {
_, domain, _ := strings.Cut(m.from.Address, "@")
random := make([]byte, messageIDBytes)
if _, err := rand.Read(random); err != nil {
return "", err
}
return "<" + hex.EncodeToString(random) + "@" + domain + ">", nil
}
func (m message) bytes() ([]byte, error) {
id, err := m.messageID()
if err != nil {
return nil, err
}
var out bytes.Buffer
headers := []struct{ name, value string }{
{"From", m.from.String()},
{"To", m.to.String()},
{"Subject", mime.QEncoding.Encode("utf-8", m.subject)},
{"Date", m.sentAt.Format(time.RFC1123Z)},
{"Message-ID", id},
{"MIME-Version", "1.0"},
{"Content-Type", "text/html; charset=UTF-8"},
{"Content-Transfer-Encoding", "quoted-printable"},
}
for _, h := range headers {
out.WriteString(h.name + ": " + h.value + lineBreak)
}
out.WriteString(lineBreak)
encoder := quotedprintable.NewWriter(&out)
if _, err := encoder.Write([]byte(m.body)); err != nil {
return nil, err
}
if err := encoder.Close(); err != nil {
return nil, err
}
return out.Bytes(), nil
}
+116
View File
@@ -0,0 +1,116 @@
package mailer
import (
"RenewCMS/internal/infrastructure/config"
"crypto/tls"
"errors"
"net"
"net/smtp"
"strconv"
"time"
)
const (
implicitTLSPort = 465
dialTimeout = 10 * time.Second
sessionTimeout = 30 * time.Second
)
type transport struct {
settings config.SmtpSettings
tlsConfig *tls.Config
}
func newTransport(settings config.SmtpSettings, tlsConfig *tls.Config) transport {
if tlsConfig == nil {
tlsConfig = &tls.Config{}
}
tlsConfig = tlsConfig.Clone()
if tlsConfig.ServerName == "" {
tlsConfig.ServerName = settings.Host
}
if tlsConfig.MinVersion == 0 {
tlsConfig.MinVersion = tls.VersionTLS12
}
return transport{settings: settings, tlsConfig: tlsConfig}
}
func (t transport) deliver(sender string, receiver string, payload []byte) error {
client, err := t.connect()
if err != nil {
return err
}
defer func() { _ = client.Close() }()
if err := t.negotiate(client); err != nil {
return err
}
if err := client.Mail(sender); err != nil {
return err
}
if err := client.Rcpt(receiver); err != nil {
return err
}
if err := writeData(client, payload); err != nil {
return err
}
return client.Quit()
}
func (t transport) connect() (*smtp.Client, error) {
address := net.JoinHostPort(t.settings.Host, strconv.Itoa(t.settings.Port))
dialer := &net.Dialer{Timeout: dialTimeout}
connection, err := dialer.Dial("tcp", address)
if err != nil {
return nil, err
}
if err := connection.SetDeadline(time.Now().Add(sessionTimeout)); err != nil {
_ = connection.Close()
return nil, err
}
if t.settings.Port == implicitTLSPort {
connection = tls.Client(connection, t.tlsConfig)
}
client, err := smtp.NewClient(connection, t.settings.Host)
if err != nil {
_ = connection.Close()
return nil, err
}
return client, nil
}
func (t transport) negotiate(client *smtp.Client) error {
if t.settings.Port != implicitTLSPort {
if supported, _ := client.Extension("STARTTLS"); supported {
if err := client.StartTLS(t.tlsConfig); err != nil {
return err
}
}
}
return t.authenticate(client)
}
func (t transport) authenticate(client *smtp.Client) error {
if t.settings.Login == "" {
return nil
}
advertised, mechanisms := client.Extension("AUTH")
if !advertised {
return errors.New("smtp server does not support authentication")
}
return client.Auth(selectAuth(mechanisms, t.settings))
}
func writeData(client *smtp.Client, payload []byte) error {
writer, err := client.Data()
if err != nil {
return err
}
if _, err := writer.Write(payload); err != nil {
_ = writer.Close()
return err
}
return writer.Close()
}
@@ -0,0 +1,30 @@
package persistence
import (
domain "RenewCMS/internal/domain/transaction"
"context"
"gorm.io/gorm"
)
var _ domain.Transactor = &Transactor{}
type Transactor struct {
db *gorm.DB
}
func NewTransactor(db *gorm.DB) *Transactor {
return &Transactor{db}
}
func (t *Transactor) Run(ctx context.Context, work func(domain.Repositories) error) error {
return t.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
return work(domain.Repositories{
Articles: NewArticleRepository(tx),
Sites: NewSiteRepository(tx),
Authors: NewAuthorRepository(tx),
Entries: NewEntryRepository(tx),
Images: NewImageRepository(tx),
})
})
}
+6 -6
View File
@@ -16,7 +16,7 @@ const (
) )
type Job interface { type Job interface {
Tick(now time.Time) (purge.RunResult, bool, error) Tick(ctx context.Context, now time.Time) (purge.RunResult, bool, error)
} }
type CleanupJob interface { type CleanupJob interface {
@@ -24,15 +24,15 @@ type CleanupJob interface {
} }
type task interface { type task interface {
tick(now time.Time) (summary string, ran bool, err error) tick(ctx context.Context, now time.Time) (summary string, ran bool, err error)
} }
type purgeTask struct { type purgeTask struct {
job Job job Job
} }
func (p purgeTask) tick(now time.Time) (string, bool, error) { func (p purgeTask) tick(ctx context.Context, now time.Time) (string, bool, error) {
result, ran, err := p.job.Tick(now) result, ran, err := p.job.Tick(ctx, now)
if errors.Is(err, purge.ErrPurgeBusy) { if errors.Is(err, purge.ErrPurgeBusy) {
return "", false, nil return "", false, nil
} }
@@ -44,7 +44,7 @@ type cleanupTask struct {
job CleanupJob job CleanupJob
} }
func (c cleanupTask) tick(now time.Time) (string, bool, error) { func (c cleanupTask) tick(_ context.Context, now time.Time) (string, bool, error) {
result, ran, err := c.job.Tick(now) result, ran, err := c.job.Tick(now)
return fmt.Sprintf("removed=%d", result.Removed), ran, err return fmt.Sprintf("removed=%d", result.Removed), ran, err
} }
@@ -119,7 +119,7 @@ func (r *Runner) tick(ctx context.Context) {
if ctx.Err() != nil { if ctx.Err() != nil {
return return
} }
summary, ran, err := r.task.tick(r.now()) summary, ran, err := r.task.tick(ctx, r.now())
if err != nil { if err != nil {
r.logger.Printf("scheduler: %s failed: %v", r.label, err) r.logger.Printf("scheduler: %s failed: %v", r.label, err)
return return
@@ -3,12 +3,14 @@ package useCases
import ( import (
"RenewCMS/internal/domain/contenttype" "RenewCMS/internal/domain/contenttype"
"RenewCMS/internal/domain/entry" "RenewCMS/internal/domain/entry"
"RenewCMS/internal/domain/image"
"time" "time"
) )
type CreateEntryUseCase struct { type CreateEntryUseCase struct {
contentTypes contenttype.Repository contentTypes contenttype.Repository
entries entry.Repository entries entry.Repository
images image.Repository
now func() time.Time now func() time.Time
} }
@@ -18,8 +20,8 @@ type CreateEntryCommand struct {
UserID uint32 UserID uint32
} }
func NewCreateEntryUseCase(contentTypes contenttype.Repository, entries entry.Repository, now func() time.Time) *CreateEntryUseCase { func NewCreateEntryUseCase(contentTypes contenttype.Repository, entries entry.Repository, images image.Repository, now func() time.Time) *CreateEntryUseCase {
return &CreateEntryUseCase{contentTypes, entries, now} return &CreateEntryUseCase{contentTypes, entries, images, now}
} }
func (u *CreateEntryUseCase) Create(command CreateEntryCommand) (TypedEntry, error) { func (u *CreateEntryUseCase) Create(command CreateEntryCommand) (TypedEntry, error) {
@@ -31,6 +33,9 @@ func (u *CreateEntryUseCase) Create(command CreateEntryCommand) (TypedEntry, err
if err := entry.Validate(owner.Fields, data); err != nil { if err := entry.Validate(owner.Fields, data); err != nil {
return TypedEntry{}, err return TypedEntry{}, err
} }
if err := ensureMediaExists(u.images, owner, data, nil); err != nil {
return TypedEntry{}, err
}
if err := ensureUnique(u.entries, owner, data, 0); err != nil { if err := ensureUnique(u.entries, owner, data, 0); err != nil {
return TypedEntry{}, err return TypedEntry{}, err
} }
@@ -46,5 +51,5 @@ func (u *CreateEntryUseCase) Create(command CreateEntryCommand) (TypedEntry, err
if err != nil { if err != nil {
return TypedEntry{}, err return TypedEntry{}, err
} }
return typedEntry(owner, stored), nil return typedEntry(owner, stored, newMediaResolver(u.images))
} }
+5 -3
View File
@@ -3,15 +3,17 @@ package useCases
import ( import (
"RenewCMS/internal/domain/contenttype" "RenewCMS/internal/domain/contenttype"
"RenewCMS/internal/domain/entry" "RenewCMS/internal/domain/entry"
"RenewCMS/internal/domain/image"
) )
type GetEntryUseCase struct { type GetEntryUseCase struct {
contentTypes contenttype.Repository contentTypes contenttype.Repository
entries entry.Repository entries entry.Repository
images image.Repository
} }
func NewGetEntryUseCase(contentTypes contenttype.Repository, entries entry.Repository) *GetEntryUseCase { func NewGetEntryUseCase(contentTypes contenttype.Repository, entries entry.Repository, images image.Repository) *GetEntryUseCase {
return &GetEntryUseCase{contentTypes, entries} return &GetEntryUseCase{contentTypes, entries, images}
} }
func (u *GetEntryUseCase) Get(contentTypeKey string, id uint32) (TypedEntry, error) { func (u *GetEntryUseCase) Get(contentTypeKey string, id uint32) (TypedEntry, error) {
@@ -23,5 +25,5 @@ func (u *GetEntryUseCase) Get(contentTypeKey string, id uint32) (TypedEntry, err
if err != nil { if err != nil {
return TypedEntry{}, err return TypedEntry{}, err
} }
return typedEntry(owner, found), nil return typedEntry(owner, found, newMediaResolver(u.images))
} }
@@ -3,16 +3,18 @@ package useCases
import ( import (
"RenewCMS/internal/domain/article" "RenewCMS/internal/domain/article"
"RenewCMS/internal/domain/author" "RenewCMS/internal/domain/author"
"RenewCMS/internal/domain/contenttype"
"RenewCMS/internal/domain/entry"
"RenewCMS/internal/domain/image" "RenewCMS/internal/domain/image"
"RenewCMS/internal/domain/site" "RenewCMS/internal/domain/site"
"slices" "slices"
"strings"
) )
const ( const (
UsageTypeArticle = "article" UsageTypeArticle = "article"
UsageTypeAuthor = "author" UsageTypeAuthor = "author"
UsageTypeSite = "site" UsageTypeSite = "site"
UsageTypeEntry = "entry"
UsageFieldBody = "body" UsageFieldBody = "body"
UsageFieldCover = "cover" UsageFieldCover = "cover"
@@ -27,6 +29,16 @@ type MediaUsage struct {
Title string Title string
Published *bool Published *bool
Fields []string Fields []string
ContentTypeKey string
ContentTypeName string
FirstField *UsageFirstField
}
type UsageFirstField struct {
Key string
Type contenttype.FieldType
Value any
} }
type GetMediaUsageUseCase struct { type GetMediaUsageUseCase struct {
@@ -34,10 +46,11 @@ type GetMediaUsageUseCase struct {
articleRepository article.Repository articleRepository article.Repository
sites site.Repository sites site.Repository
authors author.Repository authors author.Repository
entries *entryMediaScanner
} }
func NewGetMediaUsageUseCase(imageRepository image.Repository, articleRepository article.Repository, sites site.Repository, authors author.Repository) *GetMediaUsageUseCase { func NewGetMediaUsageUseCase(imageRepository image.Repository, articleRepository article.Repository, sites site.Repository, authors author.Repository, contentTypes contenttype.Repository, entries entry.Repository) *GetMediaUsageUseCase {
return &GetMediaUsageUseCase{imageRepository: imageRepository, articleRepository: articleRepository, sites: sites, authors: authors} return &GetMediaUsageUseCase{imageRepository: imageRepository, articleRepository: articleRepository, sites: sites, authors: authors, entries: newEntryMediaScanner(contentTypes, entries)}
} }
func (u *GetMediaUsageUseCase) Usage(id uint32) ([]MediaUsage, error) { func (u *GetMediaUsageUseCase) Usage(id uint32) ([]MediaUsage, error) {
@@ -57,7 +70,32 @@ func (u *GetMediaUsageUseCase) Usage(id uint32) ([]MediaUsage, error) {
if err != nil { if err != nil {
return nil, err return nil, err
} }
return slices.Concat(usages, authorUsages, siteUsages), nil entryUsages, err := u.entryUsages(img)
if err != nil {
return nil, err
}
return slices.Concat(usages, authorUsages, siteUsages, entryUsages), nil
}
func (u *GetMediaUsageUseCase) entryUsages(img image.Image) ([]MediaUsage, error) {
referencing, err := u.entries.referencing(img.ID)
if err != nil {
return nil, err
}
targets := map[uint32]bool{img.ID: true}
usages := make([]MediaUsage, 0, len(referencing))
for _, found := range referencing {
first := found.owner.Fields[0]
usages = append(usages, MediaUsage{
Type: UsageTypeEntry,
ID: found.record.ID,
Fields: found.keysPointingAt(targets),
ContentTypeKey: found.owner.Key,
ContentTypeName: found.owner.Name,
FirstField: &UsageFirstField{Key: first.Key, Type: first.Type, Value: found.record.Data[first.Key]},
})
}
return usages, nil
} }
func (u *GetMediaUsageUseCase) articleUsages(img image.Image) ([]MediaUsage, error) { func (u *GetMediaUsageUseCase) articleUsages(img image.Image) ([]MediaUsage, error) {
@@ -72,7 +110,7 @@ func (u *GetMediaUsageUseCase) articleUsages(img image.Image) ([]MediaUsage, err
} }
byID := map[uint32]*MediaUsage{} byID := map[uint32]*MediaUsage{}
for _, found := range inBody { for _, found := range inBody {
if !strings.Contains(found.Body, storedName) { if !image.ContainsStoredName(found.Body, storedName) {
continue continue
} }
entry := usageFor(byID, found) entry := usageFor(byID, found)
@@ -133,5 +171,5 @@ func (u *GetMediaUsageUseCase) siteUsages(img image.Image) ([]MediaUsage, error)
} }
func articleMentionsImage(a article.Article, img image.Image) bool { func articleMentionsImage(a article.Article, img image.Image) bool {
return strings.Contains(a.Body, image.StoredName(img.Path)) || a.UsesImage(img.ID) return image.ContainsStoredName(a.Body, image.StoredName(img.Path)) || a.UsesImage(img.ID)
} }
@@ -3,11 +3,13 @@ package useCases
import ( import (
"RenewCMS/internal/domain/contenttype" "RenewCMS/internal/domain/contenttype"
"RenewCMS/internal/domain/entry" "RenewCMS/internal/domain/entry"
"RenewCMS/internal/domain/image"
) )
type ListEntriesUseCase struct { type ListEntriesUseCase struct {
contentTypes contenttype.Repository contentTypes contenttype.Repository
entries entry.Repository entries entry.Repository
images image.Repository
} }
type ListEntriesCommand struct { type ListEntriesCommand struct {
@@ -24,8 +26,8 @@ type EntryPage struct {
Size int Size int
} }
func NewListEntriesUseCase(contentTypes contenttype.Repository, entries entry.Repository) *ListEntriesUseCase { func NewListEntriesUseCase(contentTypes contenttype.Repository, entries entry.Repository, images image.Repository) *ListEntriesUseCase {
return &ListEntriesUseCase{contentTypes, entries} return &ListEntriesUseCase{contentTypes, entries, images}
} }
func (u *ListEntriesUseCase) ListPage(command ListEntriesCommand) (EntryPage, error) { func (u *ListEntriesUseCase) ListPage(command ListEntriesCommand) (EntryPage, error) {
@@ -44,8 +46,13 @@ func (u *ListEntriesUseCase) ListPage(command ListEntriesCommand) (EntryPage, er
return EntryPage{}, err return EntryPage{}, err
} }
items := make([]TypedEntry, 0, len(found.Items)) items := make([]TypedEntry, 0, len(found.Items))
resolver := newMediaResolver(u.images)
for _, record := range found.Items { for _, record := range found.Items {
items = append(items, typedEntry(owner, record)) typed, err := typedEntry(owner, record, resolver)
if err != nil {
return EntryPage{}, err
}
items = append(items, typed)
} }
return EntryPage{Items: items, Total: found.Total, Page: command.Page, Size: command.Size}, nil return EntryPage{Items: items, Total: found.Total, Page: command.Page, Size: command.Size}, nil
} }
@@ -3,6 +3,8 @@ package useCases
import ( import (
"RenewCMS/internal/domain/article" "RenewCMS/internal/domain/article"
"RenewCMS/internal/domain/author" "RenewCMS/internal/domain/author"
"RenewCMS/internal/domain/contenttype"
"RenewCMS/internal/domain/entry"
"RenewCMS/internal/domain/image" "RenewCMS/internal/domain/image"
"RenewCMS/internal/domain/site" "RenewCMS/internal/domain/site"
"RenewCMS/internal/domain/user" "RenewCMS/internal/domain/user"
@@ -41,10 +43,11 @@ type ListMediaUseCase struct {
variantFiles image.VariantFileRepository variantFiles image.VariantFileRepository
sites site.Repository sites site.Repository
authors author.Repository authors author.Repository
entries *entryMediaScanner
} }
func NewListMediaUseCase(imageRepository image.Repository, articleRepository article.Repository, userRepository user.Repository, variantFiles image.VariantFileRepository, sites site.Repository, authors author.Repository) *ListMediaUseCase { func NewListMediaUseCase(imageRepository image.Repository, articleRepository article.Repository, userRepository user.Repository, variantFiles image.VariantFileRepository, sites site.Repository, authors author.Repository, contentTypes contenttype.Repository, entries entry.Repository) *ListMediaUseCase {
return &ListMediaUseCase{imageRepository: imageRepository, articleRepository: articleRepository, userRepository: userRepository, variantFiles: variantFiles, sites: sites, authors: authors} return &ListMediaUseCase{imageRepository: imageRepository, articleRepository: articleRepository, userRepository: userRepository, variantFiles: variantFiles, sites: sites, authors: authors, entries: newEntryMediaScanner(contentTypes, entries)}
} }
func (l *ListMediaUseCase) List(query image.ListQuery) (MediaPage, error) { func (l *ListMediaUseCase) List(query image.ListQuery) (MediaPage, error) {
@@ -118,7 +121,7 @@ func (l *ListMediaUseCase) Describe(img image.Image) (MediaItem, error) {
if err != nil { if err != nil {
return MediaItem{}, err return MediaItem{}, err
} }
siteUsage, err := imageUsageCount(l.sites, l.authors) siteUsage, err := imageUsageCount(l.sites, l.authors, l.entries)
if err != nil { if err != nil {
return MediaItem{}, err return MediaItem{}, err
} }
@@ -169,7 +172,7 @@ func (l *ListMediaUseCase) usageCounter() (func(image.Image) int, error) {
if err != nil { if err != nil {
return nil, err return nil, err
} }
siteUsage, err := imageUsageCount(l.sites, l.authors) siteUsage, err := imageUsageCount(l.sites, l.authors, l.entries)
if err != nil { if err != nil {
return nil, err return nil, err
} }
+92 -82
View File
@@ -3,15 +3,14 @@ package useCases
import ( import (
"RenewCMS/internal/domain/article" "RenewCMS/internal/domain/article"
"RenewCMS/internal/domain/audit" "RenewCMS/internal/domain/audit"
"RenewCMS/internal/domain/author" "RenewCMS/internal/domain/contenttype"
"RenewCMS/internal/domain/entry"
"RenewCMS/internal/domain/image" "RenewCMS/internal/domain/image"
"RenewCMS/internal/domain/site" "RenewCMS/internal/domain/transaction"
"cmp"
"context" "context"
"errors" "errors"
"log"
"slices" "slices"
"strconv"
"strings"
) )
type MergeMediaResult struct { type MergeMediaResult struct {
@@ -19,6 +18,7 @@ type MergeMediaResult struct {
Merged int Merged int
SitesUpdated int SitesUpdated int
AuthorsUpdated int AuthorsUpdated int
EntriesUpdated int
UpdatedArticleIDs []uint32 UpdatedArticleIDs []uint32
} }
@@ -27,12 +27,13 @@ type MergeMediaUseCase struct {
articleRepository article.Repository articleRepository article.Repository
remover mediaRemover remover mediaRemover
recorder audit.Recorder recorder audit.Recorder
sites site.Repository entries *entryMediaScanner
authors author.Repository transactor transaction.Transactor
logger *log.Logger
} }
func NewMergeMediaUseCase(imageRepository image.Repository, articleRepository article.Repository, storage image.Storage, variantFiles image.VariantFileRepository, recorder audit.Recorder, sites site.Repository, authors author.Repository) *MergeMediaUseCase { func NewMergeMediaUseCase(imageRepository image.Repository, articleRepository article.Repository, storage image.Storage, variantFiles image.VariantFileRepository, recorder audit.Recorder, contentTypes contenttype.Repository, entries entry.Repository, transactor transaction.Transactor, logger *log.Logger) *MergeMediaUseCase {
return &MergeMediaUseCase{imageRepository: imageRepository, articleRepository: articleRepository, remover: newMediaRemover(imageRepository, storage, variantFiles), recorder: recorder, sites: sites, authors: authors} return &MergeMediaUseCase{imageRepository: imageRepository, articleRepository: articleRepository, remover: newMediaRemover(imageRepository, storage, variantFiles), recorder: recorder, entries: newEntryMediaScanner(contentTypes, entries), transactor: transactor, logger: logger}
} }
func copyIdsOf(copies []image.Image) []uint32 { func copyIdsOf(copies []image.Image) []uint32 {
@@ -43,22 +44,8 @@ func copyIdsOf(copies []image.Image) []uint32 {
return copyIds return copyIds
} }
func (u *MergeMediaUseCase) repointSites(copies []image.Image, keptId uint32) (int, error) {
return u.sites.RepointImage(copyIdsOf(copies), keptId)
}
func (u *MergeMediaUseCase) repointAuthors(copies []image.Image, keptId uint32) (int, error) {
return u.authors.RepointAvatar(copyIdsOf(copies), keptId)
}
type bodyRewrite struct {
articleId uint32
original string
rewritten string
}
func (u *MergeMediaUseCase) Merge(ctx context.Context, keepId uint32, mergeIds []uint32) (MergeMediaResult, error) { func (u *MergeMediaUseCase) Merge(ctx context.Context, keepId uint32, mergeIds []uint32) (MergeMediaResult, error) {
result, err := u.merge(keepId, mergeIds) result, err := u.merge(ctx, keepId, mergeIds, nil)
event := audit.NewEvent(audit.ActionMediaMerge, audit.CategoryMedia) event := audit.NewEvent(audit.ActionMediaMerge, audit.CategoryMedia)
if kept, found := u.keptImage(keepId); found { if kept, found := u.keptImage(keepId); found {
event.Target = imageTarget(kept) event.Target = imageTarget(kept)
@@ -80,7 +67,7 @@ func (u *MergeMediaUseCase) keptImage(keepId uint32) (image.Image, bool) {
return kept, err == nil return kept, err == nil
} }
func (u *MergeMediaUseCase) merge(keepId uint32, mergeIds []uint32) (MergeMediaResult, error) { func (u *MergeMediaUseCase) merge(ctx context.Context, keepId uint32, mergeIds []uint32, index *entryMediaIndex) (MergeMediaResult, error) {
if err := validateMergeRequest(keepId, mergeIds); err != nil { if err := validateMergeRequest(keepId, mergeIds); err != nil {
return MergeMediaResult{}, err return MergeMediaResult{}, err
} }
@@ -94,45 +81,94 @@ func (u *MergeMediaUseCase) merge(keepId uint32, mergeIds []uint32) (MergeMediaR
return MergeMediaResult{}, err return MergeMediaResult{}, err
} }
rewrites, err := u.planRewrites(kept, copies) planned, err := u.planRewrites(copies)
if err != nil { if err != nil {
return MergeMediaResult{}, err return MergeMediaResult{}, err
} }
if err := u.applyRewrites(rewrites); err != nil { if index == nil {
if index, err = u.entries.index(); err != nil {
return MergeMediaResult{}, err return MergeMediaResult{}, err
} }
repointedArticles, err := u.articleRepository.RepointImage(copyIdsOf(copies), kept.ID)
if err != nil {
u.restoreBodies(rewrites)
return MergeMediaResult{}, err
}
sitesUpdated, err := u.repointSites(copies, kept.ID)
if err != nil {
u.restoreBodies(rewrites)
return MergeMediaResult{}, err
} }
authorsUpdated, err := u.repointAuthors(copies, kept.ID) result, err := u.applyMerge(ctx, kept, copies, planned, index.referencing(copyIdsOf(copies)))
if err != nil { if err != nil {
u.restoreBodies(rewrites)
return MergeMediaResult{}, err return MergeMediaResult{}, err
} }
u.discardCopies(copies)
return result, nil
}
func (u *MergeMediaUseCase) applyMerge(ctx context.Context, kept image.Image, copies []image.Image, planned []uint32, candidates []mediaEntry) (MergeMediaResult, error) {
var result MergeMediaResult
copyIds := copyIdsOf(copies)
err := u.transactor.Run(ctx, func(tx transaction.Repositories) error {
rewritten, err := rewriteBodies(tx.Articles, planned, copies, kept)
if err != nil {
return err
}
repointedArticles, err := tx.Articles.RepointImage(copyIds, kept.ID)
if err != nil {
return err
}
if result.SitesUpdated, err = tx.Sites.RepointImage(copyIds, kept.ID); err != nil {
return err
}
if result.AuthorsUpdated, err = tx.Authors.RepointAvatar(copyIds, kept.ID); err != nil {
return err
}
if result.EntriesUpdated, err = repointEntries(tx.Entries, candidates, copyIds, kept.ID); err != nil {
return err
}
for _, duplicate := range copies { for _, duplicate := range copies {
if err := u.remover.remove(duplicate); err != nil { if err := tx.Images.Delete(duplicate.ID); err != nil {
return MergeMediaResult{}, err return err
}
}
result.UpdatedArticleIDs = updatedArticleIds(rewritten, repointedArticles)
result.ArticlesUpdated = len(result.UpdatedArticleIDs)
result.Merged = len(copies)
return nil
})
return result, err
}
func (u *MergeMediaUseCase) discardCopies(copies []image.Image) {
for _, duplicate := range copies {
if err := u.remover.discardFiles(duplicate); err != nil {
u.logger.Printf("media merge: could not remove the files of %s: %v", image.StoredName(duplicate.Path), err)
}
} }
} }
updatedIds := updatedArticleIds(rewrites, repointedArticles) func rewriteBodies(articles article.Repository, planned []uint32, copies []image.Image, kept image.Image) ([]uint32, error) {
return MergeMediaResult{ArticlesUpdated: len(updatedIds), Merged: len(copies), SitesUpdated: sitesUpdated, AuthorsUpdated: authorsUpdated, UpdatedArticleIDs: updatedIds}, nil keptName := image.StoredName(kept.Path)
var rewritten []uint32
for _, id := range planned {
current, err := articles.Get(id)
if errors.Is(err, article.ErrArticleNotFound) {
continue
}
if err != nil {
return nil, err
}
body := current.Body
for _, duplicate := range copies {
body = image.ReplaceStoredName(body, image.StoredName(duplicate.Path), keptName)
}
if body == current.Body {
continue
}
if _, err := articles.UpdateBody(id, body); err != nil {
return nil, err
}
rewritten = append(rewritten, id)
}
return rewritten, nil
} }
func updatedArticleIds(rewrites []bodyRewrite, repointed []uint32) []uint32 { func updatedArticleIds(rewritten []uint32, repointed []uint32) []uint32 {
ids := slices.Clone(repointed) ids := append(slices.Clone(repointed), rewritten...)
for _, plan := range rewrites {
ids = append(ids, plan.articleId)
}
slices.Sort(ids) slices.Sort(ids)
return slices.Compact(ids) return slices.Compact(ids)
} }
@@ -169,10 +205,8 @@ func (u *MergeMediaUseCase) loadCopies(kept image.Image, mergeIds []uint32) ([]i
return copies, nil return copies, nil
} }
func (u *MergeMediaUseCase) planRewrites(kept image.Image, copies []image.Image) ([]bodyRewrite, error) { func (u *MergeMediaUseCase) planRewrites(copies []image.Image) ([]uint32, error) {
keptName := image.StoredName(kept.Path) seen := map[uint32]bool{}
rewritten := map[uint32]*bodyRewrite{}
for _, duplicate := range copies { for _, duplicate := range copies {
copyName := image.StoredName(duplicate.Path) copyName := image.StoredName(duplicate.Path)
articles, err := u.articleRepository.FindByBodyContaining(copyName) articles, err := u.articleRepository.FindByBodyContaining(copyName)
@@ -180,39 +214,15 @@ func (u *MergeMediaUseCase) planRewrites(kept image.Image, copies []image.Image)
return nil, err return nil, err
} }
for _, a := range articles { for _, a := range articles {
if !strings.Contains(a.Body, copyName) { if image.ContainsStoredName(a.Body, copyName) {
continue seen[a.ID] = true
}
plan, ok := rewritten[a.ID]
if !ok {
plan = &bodyRewrite{articleId: a.ID, original: a.Body, rewritten: a.Body}
rewritten[a.ID] = plan
}
plan.rewritten = strings.ReplaceAll(plan.rewritten, copyName, keptName)
} }
} }
plans := make([]bodyRewrite, 0, len(rewritten))
for _, plan := range rewritten {
plans = append(plans, *plan)
} }
slices.SortFunc(plans, func(a, b bodyRewrite) int { return cmp.Compare(a.articleId, b.articleId) }) planned := make([]uint32, 0, len(seen))
return plans, nil for id := range seen {
} planned = append(planned, id)
func (u *MergeMediaUseCase) applyRewrites(rewrites []bodyRewrite) error {
for applied, plan := range rewrites {
if _, err := u.articleRepository.UpdateBody(plan.articleId, plan.rewritten); err != nil {
u.restoreBodies(rewrites[:applied])
return err
}
}
return nil
}
func (u *MergeMediaUseCase) restoreBodies(applied []bodyRewrite) {
for _, plan := range applied {
_, err := u.articleRepository.UpdateBody(plan.articleId, plan.original)
logCompensation("restore article body "+strconv.FormatUint(uint64(plan.articleId), 10), err)
} }
slices.Sort(planned)
return planned, nil
} }
@@ -3,6 +3,8 @@ package useCases
import ( import (
"RenewCMS/internal/domain/article" "RenewCMS/internal/domain/article"
"RenewCMS/internal/domain/author" "RenewCMS/internal/domain/author"
"RenewCMS/internal/domain/contenttype"
"RenewCMS/internal/domain/entry"
"RenewCMS/internal/domain/image" "RenewCMS/internal/domain/image"
"RenewCMS/internal/domain/site" "RenewCMS/internal/domain/site"
) )
@@ -30,8 +32,8 @@ type PreviewPurgeUseCase struct {
planner *purgePlanner planner *purgePlanner
} }
func NewPreviewPurgeUseCase(imageRepository image.Repository, articleRepository article.Repository, sites site.Repository, authors author.Repository) *PreviewPurgeUseCase { func NewPreviewPurgeUseCase(imageRepository image.Repository, articleRepository article.Repository, sites site.Repository, authors author.Repository, contentTypes contenttype.Repository, entries entry.Repository) *PreviewPurgeUseCase {
return &PreviewPurgeUseCase{&purgePlanner{imageRepository: imageRepository, articleRepository: articleRepository, sites: sites, authors: authors}} return &PreviewPurgeUseCase{&purgePlanner{imageRepository: imageRepository, articleRepository: articleRepository, sites: sites, authors: authors, entries: newEntryMediaScanner(contentTypes, entries)}}
} }
func (u *PreviewPurgeUseCase) Preview() (PurgePreview, error) { func (u *PreviewPurgeUseCase) Preview() (PurgePreview, error) {
@@ -9,7 +9,7 @@ import (
) )
type PurgeRunner interface { type PurgeRunner interface {
Execute(fingerprint *string) (purge.RunResult, error) Execute(ctx context.Context, fingerprint *string) (purge.RunResult, error)
} }
type PurgeSchedulerUseCase struct { type PurgeSchedulerUseCase struct {
@@ -22,7 +22,7 @@ func NewPurgeSchedulerUseCase(repository purge.Repository, runner PurgeRunner, r
return &PurgeSchedulerUseCase{repository, runner, recorder} return &PurgeSchedulerUseCase{repository, runner, recorder}
} }
func (u *PurgeSchedulerUseCase) Tick(now time.Time) (purge.RunResult, bool, error) { func (u *PurgeSchedulerUseCase) Tick(ctx context.Context, now time.Time) (purge.RunResult, bool, error) {
settings, err := u.repository.Get() settings, err := u.repository.Get()
if err != nil { if err != nil {
return purge.RunResult{}, false, err return purge.RunResult{}, false, err
@@ -31,7 +31,7 @@ func (u *PurgeSchedulerUseCase) Tick(now time.Time) (purge.RunResult, bool, erro
if next == nil || now.Before(*next) { if next == nil || now.Before(*next) {
return purge.RunResult{}, false, nil return purge.RunResult{}, false, nil
} }
result, err := u.runner.Execute(nil) result, err := u.runner.Execute(ctx, nil)
if err != nil { if err != nil {
u.recordFailedRun(err) u.recordFailedRun(err)
return purge.RunResult{}, false, err return purge.RunResult{}, false, err
+13 -7
View File
@@ -26,7 +26,7 @@ type RunPurgeUseCase struct {
func NewRunPurgeUseCase(imageRepository image.Repository, articleRepository article.Repository, merge *MergeMediaUseCase, repository purge.Repository, now func() time.Time, logger *log.Logger, recorder audit.Recorder, sites site.Repository, authors author.Repository) *RunPurgeUseCase { func NewRunPurgeUseCase(imageRepository image.Repository, articleRepository article.Repository, merge *MergeMediaUseCase, repository purge.Repository, now func() time.Time, logger *log.Logger, recorder audit.Recorder, sites site.Repository, authors author.Repository) *RunPurgeUseCase {
return &RunPurgeUseCase{ return &RunPurgeUseCase{
planner: &purgePlanner{imageRepository: imageRepository, articleRepository: articleRepository, sites: sites, authors: authors}, planner: &purgePlanner{imageRepository: imageRepository, articleRepository: articleRepository, sites: sites, authors: authors, entries: merge.entries},
merge: merge, merge: merge,
repository: repository, repository: repository,
now: now, now: now,
@@ -36,7 +36,7 @@ func NewRunPurgeUseCase(imageRepository image.Repository, articleRepository arti
} }
func (u *RunPurgeUseCase) Run(ctx context.Context, fingerprint *string) (purge.RunResult, error) { func (u *RunPurgeUseCase) Run(ctx context.Context, fingerprint *string) (purge.RunResult, error) {
result, err := u.Execute(fingerprint) result, err := u.Execute(ctx, fingerprint)
event := audit.NewEvent(audit.ActionMediaPurge, audit.CategoryMedia) event := audit.NewEvent(audit.ActionMediaPurge, audit.CategoryMedia)
if err != nil { if err != nil {
recordFailure(ctx, u.recorder, event, err) recordFailure(ctx, u.recorder, event, err)
@@ -55,7 +55,7 @@ func purgeParams(result purge.RunResult) map[string]any {
return params return params
} }
func (u *RunPurgeUseCase) Execute(fingerprint *string) (purge.RunResult, error) { func (u *RunPurgeUseCase) Execute(ctx context.Context, fingerprint *string) (purge.RunResult, error) {
if !u.guard.TryLock() { if !u.guard.TryLock() {
return purge.RunResult{}, purge.ErrPurgeBusy return purge.RunResult{}, purge.ErrPurgeBusy
} }
@@ -69,7 +69,10 @@ func (u *RunPurgeUseCase) Execute(fingerprint *string) (purge.RunResult, error)
return purge.RunResult{}, purge.ErrPurgeConflict return purge.RunResult{}, purge.ErrPurgeConflict
} }
result := u.mergeGroups(plan) result, err := u.mergeGroups(ctx, plan)
if err != nil {
return purge.RunResult{}, err
}
if err := u.recordRun(result); err != nil { if err := u.recordRun(result); err != nil {
u.logger.Printf("purge: could not record the run result: %v", err) u.logger.Printf("purge: could not record the run result: %v", err)
return purge.RunResult{}, err return purge.RunResult{}, err
@@ -77,11 +80,14 @@ func (u *RunPurgeUseCase) Execute(fingerprint *string) (purge.RunResult, error)
return result, nil return result, nil
} }
func (u *RunPurgeUseCase) mergeGroups(plan purgePlan) purge.RunResult { func (u *RunPurgeUseCase) mergeGroups(ctx context.Context, plan purgePlan) (purge.RunResult, error) {
result := purge.RunResult{GroupsTotal: len(plan.groups)} result := purge.RunResult{GroupsTotal: len(plan.groups)}
updated := map[uint32]bool{} updated := map[uint32]bool{}
for _, group := range plan.groups { for _, group := range plan.groups {
merged, err := u.merge.merge(group.kept.ID, slices.Clone(group.mergedIds)) if err := ctx.Err(); err != nil {
return purge.RunResult{}, err
}
merged, err := u.merge.merge(ctx, group.kept.ID, slices.Clone(group.mergedIds), plan.entries)
if err != nil { if err != nil {
result.FailedGroups++ result.FailedGroups++
continue continue
@@ -95,7 +101,7 @@ func (u *RunPurgeUseCase) mergeGroups(plan purgePlan) purge.RunResult {
} }
} }
result.ArticlesUpdated = len(updated) result.ArticlesUpdated = len(updated)
return result return result, nil
} }
func (u *RunPurgeUseCase) recordRun(result purge.RunResult) error { func (u *RunPurgeUseCase) recordRun(result purge.RunResult) error {
@@ -11,8 +11,6 @@ import (
"slices" "slices"
"strings" "strings"
"time" "time"
"golang.org/x/sync/singleflight"
) )
const ( const (
@@ -54,7 +52,7 @@ type ServeVariantUseCase struct {
maxSourceBytes int64 maxSourceBytes int64
maxSourcePixels int64 maxSourcePixels int64
renderSlots chan struct{} renderSlots chan struct{}
flights singleflight.Group flights flightGroup
tracker image.VariantUsageTracker tracker image.VariantUsageTracker
} }
@@ -214,11 +212,11 @@ func (u *ServeVariantUseCase) lookupCached(variantName string, storedName string
func (u *ServeVariantUseCase) generated(ctx context.Context, variant image.Variant, storedName string, fingerprint string, previous image.VariantFile) (image.VariantFile, error) { func (u *ServeVariantUseCase) generated(ctx context.Context, variant image.Variant, storedName string, fingerprint string, previous image.VariantFile) (image.VariantFile, error) {
key := strings.Join([]string{variant.Name, fingerprint, storedName}, flightKeySep) key := strings.Join([]string{variant.Name, fingerprint, storedName}, flightKeySep)
for { for {
file, err, _ := u.flights.Do(key, func() (any, error) { file, err := u.flights.do(key, func() (image.VariantFile, error) {
return u.generate(ctx, variant, storedName, fingerprint, previous) return u.generate(ctx, variant, storedName, fingerprint, previous)
}) })
if err == nil { if err == nil {
return file.(image.VariantFile), nil return file, nil
} }
if ctx.Err() != nil || !errors.Is(err, context.Canceled) { if ctx.Err() != nil || !errors.Is(err, context.Canceled) {
return image.VariantFile{}, err return image.VariantFile{}, err
@@ -3,12 +3,14 @@ package useCases
import ( import (
"RenewCMS/internal/domain/contenttype" "RenewCMS/internal/domain/contenttype"
"RenewCMS/internal/domain/entry" "RenewCMS/internal/domain/entry"
"RenewCMS/internal/domain/image"
"time" "time"
) )
type UpdateEntryUseCase struct { type UpdateEntryUseCase struct {
contentTypes contenttype.Repository contentTypes contenttype.Repository
entries entry.Repository entries entry.Repository
images image.Repository
now func() time.Time now func() time.Time
} }
@@ -19,8 +21,8 @@ type UpdateEntryCommand struct {
UserID uint32 UserID uint32
} }
func NewUpdateEntryUseCase(contentTypes contenttype.Repository, entries entry.Repository, now func() time.Time) *UpdateEntryUseCase { func NewUpdateEntryUseCase(contentTypes contenttype.Repository, entries entry.Repository, images image.Repository, now func() time.Time) *UpdateEntryUseCase {
return &UpdateEntryUseCase{contentTypes, entries, now} return &UpdateEntryUseCase{contentTypes, entries, images, now}
} }
func (u *UpdateEntryUseCase) Update(command UpdateEntryCommand) (TypedEntry, error) { func (u *UpdateEntryUseCase) Update(command UpdateEntryCommand) (TypedEntry, error) {
@@ -35,6 +37,9 @@ func (u *UpdateEntryUseCase) Update(command UpdateEntryCommand) (TypedEntry, err
if err := entry.Validate(owner.Fields, command.Data); err != nil { if err := entry.Validate(owner.Fields, command.Data); err != nil {
return TypedEntry{}, err return TypedEntry{}, err
} }
if err := ensureMediaExists(u.images, owner, command.Data, current.Data); err != nil {
return TypedEntry{}, err
}
if err := ensureUnique(u.entries, owner, command.Data, current.ID); err != nil { if err := ensureUnique(u.entries, owner, command.Data, current.ID); err != nil {
return TypedEntry{}, err return TypedEntry{}, err
} }
@@ -45,5 +50,5 @@ func (u *UpdateEntryUseCase) Update(command UpdateEntryCommand) (TypedEntry, err
if err != nil { if err != nil {
return TypedEntry{}, err return TypedEntry{}, err
} }
return typedEntry(owner, stored), nil return typedEntry(owner, stored, newMediaResolver(u.images))
} }
@@ -0,0 +1,204 @@
package useCases
import (
"RenewCMS/internal/domain/contenttype"
"RenewCMS/internal/domain/entry"
"RenewCMS/internal/domain/image"
"cmp"
"errors"
"maps"
"slices"
)
type EntryMedia struct {
ID uint32
Missing bool
Filename string
Width *int
Height *int
Size int64
ThumbnailURL string
}
type mediaResolver struct {
images image.Repository
cache map[uint32]EntryMedia
}
func newMediaResolver(images image.Repository) *mediaResolver {
return &mediaResolver{images: images, cache: map[uint32]EntryMedia{}}
}
func (r *mediaResolver) resolve(owner contenttype.ContentType, record entry.Entry) (map[string]EntryMedia, error) {
resolved := map[string]EntryMedia{}
for _, ref := range contenttype.MediaRefs(owner.Fields, record.Data) {
media, err := r.lookup(ref.ID)
if err != nil {
return nil, err
}
resolved[ref.Field.Key] = media
}
return resolved, nil
}
func (r *mediaResolver) lookup(id uint32) (EntryMedia, error) {
if cached, found := r.cache[id]; found {
return cached, nil
}
found, err := r.images.Get(id)
if errors.Is(err, image.ErrImageNotFound) {
r.cache[id] = EntryMedia{ID: id, Missing: true}
return r.cache[id], nil
}
if err != nil {
return EntryMedia{}, err
}
media := EntryMedia{ID: found.ID, Filename: found.Filename, Width: knownDimension(found.Width), Height: knownDimension(found.Height), Size: found.Size, ThumbnailURL: found.Path}
r.cache[id] = media
return media, nil
}
func knownDimension(value int) *int {
if value <= 0 {
return nil
}
return &value
}
type mediaEntry struct {
owner contenttype.ContentType
record entry.Entry
}
func (m mediaEntry) keysPointingAt(ids map[uint32]bool) []string {
keys := []string{}
for _, ref := range contenttype.MediaRefs(m.owner.Fields, m.record.Data) {
if ids[ref.ID] {
keys = append(keys, ref.Field.Key)
}
}
return keys
}
func compareMediaEntries(a, b mediaEntry) int {
return cmp.Or(cmp.Compare(a.owner.Name, b.owner.Name), cmp.Compare(a.owner.ID, b.owner.ID), cmp.Compare(a.record.ID, b.record.ID))
}
type entryMediaIndex struct {
byImage map[uint32][]mediaEntry
}
func newEntryMediaIndex(found []mediaEntry) *entryMediaIndex {
index := &entryMediaIndex{byImage: map[uint32][]mediaEntry{}}
for _, candidate := range found {
distinct := map[uint32]bool{}
for _, ref := range contenttype.MediaRefs(candidate.owner.Fields, candidate.record.Data) {
distinct[ref.ID] = true
}
for id := range distinct {
index.byImage[id] = append(index.byImage[id], candidate)
}
}
return index
}
func (i *entryMediaIndex) usageCounts() map[uint32]int {
counts := make(map[uint32]int, len(i.byImage))
for id, found := range i.byImage {
counts[id] = len(found)
}
return counts
}
func (i *entryMediaIndex) referencing(imageIDs []uint32) []mediaEntry {
type entryKey struct{ typeID, entryID uint32 }
seen := map[entryKey]bool{}
var found []mediaEntry
for _, id := range imageIDs {
for _, candidate := range i.byImage[id] {
key := entryKey{candidate.owner.ID, candidate.record.ID}
if !seen[key] {
seen[key] = true
found = append(found, candidate)
}
}
}
slices.SortFunc(found, compareMediaEntries)
return found
}
type entryMediaScanner struct {
contentTypes contenttype.Repository
entries entry.Repository
}
func newEntryMediaScanner(contentTypes contenttype.Repository, entries entry.Repository) *entryMediaScanner {
return &entryMediaScanner{contentTypes: contentTypes, entries: entries}
}
func (s *entryMediaScanner) index() (*entryMediaIndex, error) {
types, err := s.contentTypes.List()
if err != nil {
return nil, err
}
var found []mediaEntry
for _, owner := range types {
if len(contenttype.MediaFields(owner.Fields)) == 0 {
continue
}
page, err := s.entries.ListPage(entry.Filters{ContentTypeID: owner.ID, Unpaged: true, Sort: entry.DefaultSort()})
if err != nil {
return nil, err
}
for _, record := range page.Items {
found = append(found, mediaEntry{owner: owner, record: record})
}
}
return newEntryMediaIndex(found), nil
}
func (s *entryMediaScanner) usageCounts() (map[uint32]int, error) {
index, err := s.index()
if err != nil {
return nil, err
}
return index.usageCounts(), nil
}
func (s *entryMediaScanner) referencing(imageID uint32) ([]mediaEntry, error) {
index, err := s.index()
if err != nil {
return nil, err
}
return index.referencing([]uint32{imageID}), nil
}
func repointEntries(entries entry.Repository, candidates []mediaEntry, copyIDs []uint32, keptID uint32) (int, error) {
copies := map[uint32]bool{}
for _, id := range copyIDs {
copies[id] = true
}
updated := 0
for _, candidate := range candidates {
current, err := entries.Get(candidate.owner.ID, candidate.record.ID)
if errors.Is(err, entry.ErrEntryNotFound) {
continue
}
if err != nil {
return updated, err
}
keys := mediaEntry{owner: candidate.owner, record: current}.keysPointingAt(copies)
if len(keys) == 0 {
continue
}
current.Data = maps.Clone(current.Data)
for _, key := range keys {
current.Data[key] = float64(keptID)
}
if _, err := entries.Update(current); err != nil {
return updated, err
}
updated++
}
return updated, nil
}
@@ -3,16 +3,49 @@ package useCases
import ( import (
"RenewCMS/internal/domain/contenttype" "RenewCMS/internal/domain/contenttype"
"RenewCMS/internal/domain/entry" "RenewCMS/internal/domain/entry"
"RenewCMS/internal/domain/image"
"errors"
) )
type TypedEntry struct { type TypedEntry struct {
entry.Entry entry.Entry
ContentTypeKey string ContentTypeKey string
Media map[string]EntryMedia
} }
func typedEntry(owner contenttype.ContentType, record entry.Entry) TypedEntry { func typedEntry(owner contenttype.ContentType, record entry.Entry, resolver *mediaResolver) (TypedEntry, error) {
record.Data = entry.Project(owner.Fields, record.Data) record.Data = entry.Project(owner.Fields, record.Data)
return TypedEntry{Entry: record, ContentTypeKey: owner.Key} media, err := resolver.resolve(owner, record)
if err != nil {
return TypedEntry{}, err
}
return TypedEntry{Entry: record, ContentTypeKey: owner.Key, Media: media}, nil
}
func ensureMediaExists(images image.Repository, owner contenttype.ContentType, data map[string]any, stored map[string]any) error {
storedIDs := entry.MediaIDs(owner.Fields, stored)
for _, ref := range contenttype.MediaRefs(owner.Fields, data) {
unchanged := stored != nil && storedIDs[ref.Field.Key] == ref.ID
if unchanged && !ref.Field.Required {
continue
}
exists, err := imageExists(images, ref.ID)
if err != nil {
return err
}
if !exists {
return entry.MissingMedia(ref.Field, unchanged)
}
}
return nil
}
func imageExists(images image.Repository, id uint32) (bool, error) {
_, err := images.Get(id)
if errors.Is(err, image.ErrImageNotFound) {
return false, nil
}
return err == nil, err
} }
func ensureUnique(entries entry.Repository, owner contenttype.ContentType, data map[string]any, excludeID uint32) error { func ensureUnique(entries entry.Repository, owner contenttype.ContentType, data map[string]any, excludeID uint32) error {
@@ -0,0 +1,45 @@
package useCases
import (
"RenewCMS/internal/domain/image"
"errors"
"sync"
)
var errFlightAbandoned = errors.New("shared call ended without a result")
type flightCall struct {
done chan struct{}
value image.VariantFile
err error
}
type flightGroup struct {
mu sync.Mutex
calls map[string]*flightCall
}
func (g *flightGroup) do(key string, work func() (image.VariantFile, error)) (image.VariantFile, error) {
g.mu.Lock()
if existing, running := g.calls[key]; running {
g.mu.Unlock()
<-existing.done
return existing.value, existing.err
}
if g.calls == nil {
g.calls = map[string]*flightCall{}
}
call := &flightCall{done: make(chan struct{}), err: errFlightAbandoned}
g.calls[key] = call
g.mu.Unlock()
defer func() {
g.mu.Lock()
delete(g.calls, key)
g.mu.Unlock()
close(call.done)
}()
call.value, call.err = work()
return call.value, call.err
}
@@ -1,6 +1,9 @@
package useCases package useCases
import "RenewCMS/internal/domain/image" import (
"RenewCMS/internal/domain/image"
"errors"
)
type mediaRemover struct { type mediaRemover struct {
imageRepository image.Repository imageRepository image.Repository
@@ -22,3 +25,8 @@ func (r mediaRemover) remove(img image.Image) error {
} }
return r.imageRepository.Delete(img.ID) return r.imageRepository.Delete(img.ID)
} }
func (r mediaRemover) discardFiles(img image.Image) error {
storedName := image.StoredName(img.Path)
return errors.Join(r.generated.purgeSource(storedName), r.storage.Delete(storedName))
}
+12 -2
View File
@@ -23,6 +23,7 @@ type purgePlan struct {
copies int copies int
articles int articles int
fingerprint string fingerprint string
entries *entryMediaIndex
} }
type purgePlanner struct { type purgePlanner struct {
@@ -30,6 +31,7 @@ type purgePlanner struct {
articleRepository article.Repository articleRepository article.Repository
sites site.Repository sites site.Repository
authors author.Repository authors author.Repository
entries *entryMediaScanner
} }
func (p *purgePlanner) plan() (purgePlan, error) { func (p *purgePlanner) plan() (purgePlan, error) {
@@ -42,7 +44,15 @@ func (p *purgePlanner) plan() (purgePlan, error) {
return purgePlan{}, err return purgePlan{}, err
} }
siteUsage, err := imageUsageCount(p.sites, p.authors) var entryIndex *entryMediaIndex
siteUsage, err := combinedImageUsage(p.sites, p.authors, func() (map[uint32]int, error) {
built, err := p.entries.index()
if err != nil {
return nil, err
}
entryIndex = built
return built.usageCounts(), nil
})
if err != nil { if err != nil {
return purgePlan{}, err return purgePlan{}, err
} }
@@ -63,7 +73,7 @@ func (p *purgePlanner) plan() (purgePlan, error) {
} }
slices.SortFunc(groups, func(a, b purgeGroup) int { return int(a.kept.ID) - int(b.kept.ID) }) slices.SortFunc(groups, func(a, b purgeGroup) int { return int(a.kept.ID) - int(b.kept.ID) })
return purgePlan{groups: groups, copies: copies, articles: len(touched), fingerprint: fingerprintOf(groups)}, nil return purgePlan{groups: groups, copies: copies, articles: len(touched), fingerprint: fingerprintOf(groups), entries: entryIndex}, nil
} }
func groupByHash(images []image.Image) [][]image.Image { func groupByHash(images []image.Image) [][]image.Image {
@@ -19,7 +19,11 @@ func siteImageUsage(sites site.Repository) (map[uint32]int, error) {
return usage, nil return usage, nil
} }
func imageUsageCount(sites site.Repository, authors author.Repository) (map[uint32]int, error) { func imageUsageCount(sites site.Repository, authors author.Repository, entries *entryMediaScanner) (map[uint32]int, error) {
return combinedImageUsage(sites, authors, entries.usageCounts)
}
func combinedImageUsage(sites site.Repository, authors author.Repository, entryCounts func() (map[uint32]int, error)) (map[uint32]int, error) {
usage, err := siteImageUsage(sites) usage, err := siteImageUsage(sites)
if err != nil { if err != nil {
return nil, err return nil, err
@@ -31,5 +35,12 @@ func imageUsageCount(sites site.Repository, authors author.Repository) (map[uint
for imageID, total := range avatars { for imageID, total := range avatars {
usage[imageID] += total usage[imageID] += total
} }
counts, err := entryCounts()
if err != nil {
return nil, err
}
for imageID, total := range counts {
usage[imageID] += total
}
return usage, nil return usage, nil
} }
+2 -2
View File
@@ -16,9 +16,9 @@ import (
"testing" "testing"
"time" "time"
"RenewCMS/api/pkg/authtoken"
"github.com/glebarez/sqlite" "github.com/glebarez/sqlite"
"github.com/go-chi/chi/v5" "github.com/go-chi/chi/v5"
"github.com/go-chi/jwtauth/v5"
"gorm.io/gorm" "gorm.io/gorm"
"gorm.io/gorm/logger" "gorm.io/gorm/logger"
) )
@@ -117,7 +117,7 @@ func newAtomicAcceptFixture(t *testing.T, wrap func(db *gorm.DB, repo invite.Rep
handler := auth.NewAcceptInviteHandler( handler := auth.NewAcceptInviteHandler(
useCases.NewGetInviteUseCase(invites, hasher), useCases.NewGetInviteUseCase(invites, hasher),
useCases.NewAcceptInviteUseCase(users, invites, hasher, discardRecorder), useCases.NewAcceptInviteUseCase(users, invites, hasher, discardRecorder),
jwtauth.New("HS256", []byte("test-secret"), nil), authtoken.New([]byte("test-secret")),
true, true,
) )
router := chi.NewRouter() router := chi.NewRouter()
+9 -14
View File
@@ -17,9 +17,8 @@ import (
"testing" "testing"
"time" "time"
"RenewCMS/api/pkg/authtoken"
"github.com/go-chi/chi/v5" "github.com/go-chi/chi/v5"
"github.com/go-chi/jwtauth/v5"
"github.com/lestrrat-go/jwx/v3/transform"
) )
const ( const (
@@ -39,7 +38,7 @@ type acceptInviteFixture struct {
mail *mockMailRepo mail *mockMailRepo
hasher *stubHasher hasher *stubHasher
router *chi.Mux router *chi.Mux
token *jwtauth.JWTAuth token *authtoken.Auth
} }
func newAcceptInviteFixture(t *testing.T, maxAttempts int) *acceptInviteFixture { func newAcceptInviteFixture(t *testing.T, maxAttempts int) *acceptInviteFixture {
@@ -50,7 +49,7 @@ func newAcceptInviteFixture(t *testing.T, maxAttempts int) *acceptInviteFixture
invites: newInviteFakeRepo(), invites: newInviteFakeRepo(),
mail: newMockMailRepo(), mail: newMockMailRepo(),
hasher: &stubHasher{}, hasher: &stubHasher{},
token: jwtauth.New("HS256", []byte("test-secret"), nil), token: authtoken.New([]byte("test-secret")),
} }
f.invites.users = f.users f.invites.users = f.users
getUser := useCases.NewGetUserUseCase(f.users) getUser := useCases.NewGetUserUseCase(f.users)
@@ -85,15 +84,15 @@ func newAcceptInviteFixture(t *testing.T, maxAttempts int) *acceptInviteFixture
r.Post("/invite/accept", acceptHandler.AcceptInvite) r.Post("/invite/accept", acceptHandler.AcceptInvite)
}) })
r.Group(func(r chi.Router) { r.Group(func(r chi.Router) {
r.Use(jwtauth.Verifier(f.token)) r.Use(authtoken.Verifier(f.token))
r.Use(jwtauth.Authenticator(f.token)) r.Use(authtoken.Authenticator)
r.Use(middleware.RequireCurrentToken(getUser)) r.Use(middleware.RequireCurrentToken(getUser))
r.Get("/me", meHandler.Me) r.Get("/me", meHandler.Me)
}) })
}) })
f.router.Route("/v1/user", func(r chi.Router) { f.router.Route("/v1/user", func(r chi.Router) {
r.Use(jwtauth.Verifier(f.token)) r.Use(authtoken.Verifier(f.token))
r.Use(jwtauth.Authenticator(f.token)) r.Use(authtoken.Authenticator)
r.Use(middleware.RequireCurrentToken(getUser)) r.Use(middleware.RequireCurrentToken(getUser))
r.Use(middleware.RequireVerifiedUser(getUser)) r.Use(middleware.RequireVerifiedUser(getUser))
r.Get("/", listHandler.ListUsers) r.Get("/", listHandler.ListUsers)
@@ -258,12 +257,10 @@ func TestAcceptInvitationHttp(t *testing.T) {
if lifetime := time.Until(cookie.Expires); lifetime < 23*time.Hour || lifetime > 24*time.Hour+time.Minute { if lifetime := time.Until(cookie.Expires); lifetime < 23*time.Hour || lifetime > 24*time.Hour+time.Minute {
t.Errorf("expected a 24 hour cookie, got %v", lifetime) t.Errorf("expected a 24 hour cookie, got %v", lifetime)
} }
decoded, err := f.token.Decode(cookie.Value) claims, err := f.token.Decode(cookie.Value)
if err != nil { if err != nil {
t.Fatalf("cookie does not decode: %v", err) t.Fatalf("cookie does not decode: %v", err)
} }
claims := map[string]interface{}{}
_ = transform.AsMap(decoded, claims)
if claims["user_id"] != float64(created.ID) || claims["token_version"] != float64(created.TokenVersion) { if claims["user_id"] != float64(created.ID) || claims["token_version"] != float64(created.TokenVersion) {
t.Errorf("unexpected claims %v", claims) t.Errorf("unexpected claims %v", claims)
} }
@@ -414,12 +411,10 @@ func TestAcceptInvitationHttp(t *testing.T) {
} }
created, _ := f.userNamed("lea") created, _ := f.userNamed("lea")
cookie := jwtCookieOf(rec) cookie := jwtCookieOf(rec)
decoded, err := f.token.Decode(cookie.Value) claims, err := f.token.Decode(cookie.Value)
if err != nil { if err != nil {
t.Fatalf("cookie does not decode: %v", err) t.Fatalf("cookie does not decode: %v", err)
} }
claims := map[string]interface{}{}
_ = transform.AsMap(decoded, claims)
if claims["user_id"] != float64(created.ID) || created.ID == 7 { if claims["user_id"] != float64(created.ID) || created.ID == 7 {
t.Errorf("cookie must carry the new user's id, got %v", claims["user_id"]) t.Errorf("cookie must carry the new user's id, got %v", claims["user_id"])
} }
+9 -9
View File
@@ -13,11 +13,11 @@ import (
"testing" "testing"
"time" "time"
"RenewCMS/api/pkg/authtoken"
"github.com/go-chi/chi/v5" "github.com/go-chi/chi/v5"
"github.com/go-chi/jwtauth/v5"
) )
func newAccountVerificationRouter(userRepo *mockUserRepo, token *jwtauth.JWTAuth) *chi.Mux { func newAccountVerificationRouter(userRepo *mockUserRepo, token *authtoken.Auth) *chi.Mux {
hasher := &stubHasher{} hasher := &stubHasher{}
verificationHandler := auth.NewVerificationHandler( verificationHandler := auth.NewVerificationHandler(
useCases.NewVerifyUserUseCase(userRepo, hasher, discardRecorder), useCases.NewVerifyUserUseCase(userRepo, hasher, discardRecorder),
@@ -29,8 +29,8 @@ func newAccountVerificationRouter(userRepo *mockUserRepo, token *jwtauth.JWTAuth
r.Route("/v1", func(r chi.Router) { r.Route("/v1", func(r chi.Router) {
r.Route("/auth", func(r chi.Router) { r.Route("/auth", func(r chi.Router) {
r.Group(func(r chi.Router) { r.Group(func(r chi.Router) {
r.Use(jwtauth.Verifier(token)) r.Use(authtoken.Verifier(token))
r.Use(jwtauth.Authenticator(token)) r.Use(authtoken.Authenticator)
r.Post("/verify", verificationHandler.Verify) r.Post("/verify", verificationHandler.Verify)
}) })
}) })
@@ -51,11 +51,11 @@ func newAccountVerificationTestUserRepo() *mockUserRepo {
return repo return repo
} }
func sendVerifyRequest(router *chi.Mux, token *jwtauth.JWTAuth, claims map[string]any, code string) *httptest.ResponseRecorder { func sendVerifyRequest(router *chi.Mux, token *authtoken.Auth, claims map[string]any, code string) *httptest.ResponseRecorder {
body, _ := json.Marshal(map[string]string{"code": code}) body, _ := json.Marshal(map[string]string{"code": code})
req := httptest.NewRequest(http.MethodPost, "/v1/auth/verify", bytes.NewReader(body)) req := httptest.NewRequest(http.MethodPost, "/v1/auth/verify", bytes.NewReader(body))
if claims != nil { if claims != nil {
_, tokenString, _ := token.Encode(claims) tokenString, _ := token.Encode(claims)
req.AddCookie(&http.Cookie{Name: "jwt", Value: tokenString}) req.AddCookie(&http.Cookie{Name: "jwt", Value: tokenString})
} }
rec := httptest.NewRecorder() rec := httptest.NewRecorder()
@@ -65,7 +65,7 @@ func sendVerifyRequest(router *chi.Mux, token *jwtauth.JWTAuth, claims map[strin
func TestAccountVerificationHttp(t *testing.T) { func TestAccountVerificationHttp(t *testing.T) {
validator.InitValidator() validator.InitValidator()
token := jwtauth.New("HS256", []byte("test-secret"), nil) token := authtoken.New([]byte("test-secret"))
t.Run("A logged-in user verifies their account with the correct emailed code", func(t *testing.T) { t.Run("A logged-in user verifies their account with the correct emailed code", func(t *testing.T) {
repo := newAccountVerificationTestUserRepo() repo := newAccountVerificationTestUserRepo()
@@ -200,7 +200,7 @@ func TestAccountVerificationHttp(t *testing.T) {
router := newAccountVerificationRouter(repo, token) router := newAccountVerificationRouter(repo, token)
req := httptest.NewRequest(http.MethodPost, "/v1/auth/verify", bytes.NewReader([]byte("not-json"))) req := httptest.NewRequest(http.MethodPost, "/v1/auth/verify", bytes.NewReader([]byte("not-json")))
_, tokenString, _ := token.Encode(map[string]any{"user_id": uint32(7)}) tokenString, _ := token.Encode(map[string]any{"user_id": uint32(7)})
req.AddCookie(&http.Cookie{Name: "jwt", Value: tokenString}) req.AddCookie(&http.Cookie{Name: "jwt", Value: tokenString})
rec := httptest.NewRecorder() rec := httptest.NewRecorder()
router.ServeHTTP(rec, req) router.ServeHTTP(rec, req)
@@ -224,7 +224,7 @@ func TestAccountVerificationHttp(t *testing.T) {
} }
}) })
t.Run("A request with no jwt cookie is answered 401 by jwtauth itself", func(t *testing.T) { t.Run("A request with no jwt cookie is answered 401 by the authenticator itself", func(t *testing.T) {
repo := newAccountVerificationTestUserRepo() repo := newAccountVerificationTestUserRepo()
router := newAccountVerificationRouter(repo, token) router := newAccountVerificationRouter(repo, token)
+5 -5
View File
@@ -23,8 +23,8 @@ import (
"testing" "testing"
"time" "time"
"RenewCMS/api/pkg/authtoken"
"github.com/go-chi/chi/v5" "github.com/go-chi/chi/v5"
"github.com/go-chi/jwtauth/v5"
) )
const ( const (
@@ -44,7 +44,7 @@ type activityHTTPEnv struct {
keys *mockAPIKeyRepo keys *mockAPIKeyRepo
articles *mockArticleRepo articles *mockArticleRepo
mail *mockMailRepo mail *mockMailRepo
token *jwtauth.JWTAuth token *authtoken.Auth
generator *hashing.SHA256KeyGenerator generator *hashing.SHA256KeyGenerator
router http.Handler router http.Handler
} }
@@ -59,7 +59,7 @@ func newActivityHTTPEnv(t *testing.T, attempts int) *activityHTTPEnv {
keys: newMockAPIKeyRepo(), keys: newMockAPIKeyRepo(),
articles: newMockArticleRepo(), articles: newMockArticleRepo(),
mail: newMockMailRepo(), mail: newMockMailRepo(),
token: jwtauth.New("HS256", []byte("test-secret"), nil), token: authtoken.New([]byte("test-secret")),
generator: hashing.NewSHA256KeyGenerator(), generator: hashing.NewSHA256KeyGenerator(),
} }
e.users.users[activityOwnerID] = user.User{ID: activityOwnerID, Username: "marta", DisplayName: "Marta Alves", Email: "marta@example.com", Password: "hashed:" + activityPassword, IsVerified: true, Role: user.RoleOwner} e.users.users[activityOwnerID] = user.User{ID: activityOwnerID, Username: "marta", DisplayName: "Marta Alves", Email: "marta@example.com", Password: "hashed:" + activityPassword, IsVerified: true, Role: user.RoleOwner}
@@ -99,7 +99,7 @@ type activityRequest func(*http.Request)
func asUser(e *activityHTTPEnv, id uint32) activityRequest { func asUser(e *activityHTTPEnv, id uint32) activityRequest {
return func(r *http.Request) { return func(r *http.Request) {
_, tokenString, _ := e.token.Encode(map[string]any{"user_id": id, "token_version": 0}) tokenString, _ := e.token.Encode(map[string]any{"user_id": id, "token_version": 0})
r.AddCookie(&http.Cookie{Name: "jwt", Value: tokenString}) r.AddCookie(&http.Cookie{Name: "jwt", Value: tokenString})
} }
} }
@@ -1037,7 +1037,7 @@ func TestActivityLogBackendAuditContext(t *testing.T) {
t.Helper() t.Helper()
probe := &auditOriginProbe{} probe := &auditOriginProbe{}
r := chi.NewRouter() r := chi.NewRouter()
r.Use(jwtauth.Verifier(e.token)) r.Use(authtoken.Verifier(e.token))
r.Use(middleware.APIKeyAuth(useCases.NewAuthenticateAPIKeyUseCase(e.keys, e.generator, e.users, e.clock), 100, time.Minute)) r.Use(middleware.APIKeyAuth(useCases.NewAuthenticateAPIKeyUseCase(e.keys, e.generator, e.users, e.clock), 100, time.Minute))
r.Use(middleware.AuditContext(useCases.NewGetUserUseCase(e.users), trusted)) r.Use(middleware.AuditContext(useCases.NewGetUserUseCase(e.users), trusted))
r.Get("/probe", func(w http.ResponseWriter, req *http.Request) { r.Get("/probe", func(w http.ResponseWriter, req *http.Request) {
+8 -8
View File
@@ -58,7 +58,7 @@ type producerPurgeRunner struct {
var _ useCases.PurgeRunner = &producerPurgeRunner{} var _ useCases.PurgeRunner = &producerPurgeRunner{}
func (r *producerPurgeRunner) Execute(*string) (purge.RunResult, error) { func (r *producerPurgeRunner) Execute(context.Context, *string) (purge.RunResult, error) {
r.calls++ r.calls++
return r.result, r.err return r.result, r.err
} }
@@ -245,7 +245,7 @@ func TestActivityLogProducersFailureReasons(t *testing.T) {
t.Helper() t.Helper()
h := newActivityHarness(t) h := newActivityHarness(t)
scheduler := useCases.NewPurgeSchedulerUseCase(dueSettings(), &producerPurgeRunner{err: err}, h.recorder) scheduler := useCases.NewPurgeSchedulerUseCase(dueSettings(), &producerPurgeRunner{err: err}, h.recorder)
if _, _, tickErr := scheduler.Tick(*purgeTime("2026-10-05T09:00:00Z")); !errors.Is(tickErr, err) { if _, _, tickErr := scheduler.Tick(testCtx, *purgeTime("2026-10-05T09:00:00Z")); !errors.Is(tickErr, err) {
t.Fatalf("tick err = %v", tickErr) t.Fatalf("tick err = %v", tickErr)
} }
return onlyEvent(t, h) return onlyEvent(t, h)
@@ -322,7 +322,7 @@ func TestActivityLogProducersScheduledPurge(t *testing.T) {
runner := &producerPurgeRunner{result: purge.RunResult{GroupsTotal: 2, GroupsPurged: 2, Merged: 3, ArticlesUpdated: 5}} runner := &producerPurgeRunner{result: purge.RunResult{GroupsTotal: 2, GroupsPurged: 2, Merged: 3, ArticlesUpdated: 5}}
scheduler := useCases.NewPurgeSchedulerUseCase(due(), runner, h.recorder) scheduler := useCases.NewPurgeSchedulerUseCase(due(), runner, h.recorder)
if _, ran, err := scheduler.Tick(now); err != nil || !ran { if _, ran, err := scheduler.Tick(testCtx, now); err != nil || !ran {
t.Fatalf("ran = %v, err = %v", ran, err) t.Fatalf("ran = %v, err = %v", ran, err)
} }
@@ -341,7 +341,7 @@ func TestActivityLogProducersScheduledPurge(t *testing.T) {
runner := &producerPurgeRunner{result: purge.RunResult{GroupsTotal: 3, GroupsPurged: 2, FailedGroups: 1, Merged: 2, ArticlesUpdated: 2}} runner := &producerPurgeRunner{result: purge.RunResult{GroupsTotal: 3, GroupsPurged: 2, FailedGroups: 1, Merged: 2, ArticlesUpdated: 2}}
scheduler := useCases.NewPurgeSchedulerUseCase(due(), runner, h.recorder) scheduler := useCases.NewPurgeSchedulerUseCase(due(), runner, h.recorder)
if _, _, err := scheduler.Tick(now); err != nil { if _, _, err := scheduler.Tick(testCtx, now); err != nil {
t.Fatal(err) t.Fatal(err)
} }
@@ -356,10 +356,10 @@ func TestActivityLogProducersScheduledPurge(t *testing.T) {
h := newActivityHarness(t) h := newActivityHarness(t)
notDue := newMockPurgeSettingsRepo() notDue := newMockPurgeSettingsRepo()
runner := &producerPurgeRunner{} runner := &producerPurgeRunner{}
if _, ran, err := useCases.NewPurgeSchedulerUseCase(notDue, runner, h.recorder).Tick(now); err != nil || ran { if _, ran, err := useCases.NewPurgeSchedulerUseCase(notDue, runner, h.recorder).Tick(testCtx, now); err != nil || ran {
t.Fatalf("ran = %v, err = %v", ran, err) t.Fatalf("ran = %v, err = %v", ran, err)
} }
if _, ran, err := useCases.NewPurgeSchedulerUseCase(due(), runner, h.recorder).Tick(now); err != nil || !ran { if _, ran, err := useCases.NewPurgeSchedulerUseCase(due(), runner, h.recorder).Tick(testCtx, now); err != nil || !ran {
t.Fatalf("ran = %v, err = %v", ran, err) t.Fatalf("ran = %v, err = %v", ran, err)
} }
assertNoEvents(t, h) assertNoEvents(t, h)
@@ -369,7 +369,7 @@ func TestActivityLogProducersScheduledPurge(t *testing.T) {
h := newActivityHarness(t) h := newActivityHarness(t)
runner := &producerPurgeRunner{err: errRepositoryFailure} runner := &producerPurgeRunner{err: errRepositoryFailure}
if _, _, err := useCases.NewPurgeSchedulerUseCase(due(), runner, h.recorder).Tick(now); err == nil { if _, _, err := useCases.NewPurgeSchedulerUseCase(due(), runner, h.recorder).Tick(testCtx, now); err == nil {
t.Fatal("expected an error") t.Fatal("expected an error")
} }
@@ -383,7 +383,7 @@ func TestActivityLogProducersScheduledPurge(t *testing.T) {
images := &producerBlockingImageRepo{mockImageRepo: newMockImageRepo(), entered: make(chan struct{}, 2), release: make(chan struct{})} images := &producerBlockingImageRepo{mockImageRepo: newMockImageRepo(), entered: make(chan struct{}, 2), release: make(chan struct{})}
articles := newMockArticleRepo() articles := newMockArticleRepo()
storage := newMockImageStorage() storage := newMockImageStorage()
merge := useCases.NewMergeMediaUseCase(images, articles, storage, newMockVariantFileRepo(), h.recorder, plainSites(), plainAuthors()) merge := newTestMergeMedia(images, articles, storage, newMockVariantFileRepo(), h.recorder, plainSites(), plainAuthors(), newMockContentTypeRepo(), newMockEntryRepo())
run := useCases.NewRunPurgeUseCase(images, articles, merge, newMockPurgeSettingsRepo(), func() time.Time { return now }, log.New(io.Discard, "", 0), h.recorder, plainSites(), plainAuthors()) run := useCases.NewRunPurgeUseCase(images, articles, merge, newMockPurgeSettingsRepo(), func() time.Time { return now }, log.New(io.Discard, "", 0), h.recorder, plainSites(), plainAuthors())
finished := make(chan struct{}) finished := make(chan struct{})
+7 -7
View File
@@ -27,8 +27,8 @@ import (
"testing" "testing"
"time" "time"
"RenewCMS/api/pkg/authtoken"
"github.com/go-chi/chi/v5" "github.com/go-chi/chi/v5"
"github.com/go-chi/jwtauth/v5"
) )
const ( const (
@@ -51,7 +51,7 @@ type apiKeyEnv struct {
mail *mockMailRepo mail *mockMailRepo
feed *fakeReleaseFeed feed *fakeReleaseFeed
updates *fakeUpdateStore updates *fakeUpdateStore
token *jwtauth.JWTAuth token *authtoken.Auth
generator *hashing.SHA256KeyGenerator generator *hashing.SHA256KeyGenerator
now time.Time now time.Time
settings config.Settings settings config.Settings
@@ -76,7 +76,7 @@ func newAPIKeyEnvRecording(t *testing.T, recorder audit.Recorder) *apiKeyEnv {
images: newMockImageRepo(), images: newMockImageRepo(),
invites: newInviteFakeRepo(), invites: newInviteFakeRepo(),
updates: &fakeUpdateStore{}, updates: &fakeUpdateStore{},
token: jwtauth.New("HS256", []byte("test-secret"), nil), token: authtoken.New([]byte("test-secret")),
generator: hashing.NewSHA256KeyGenerator(), generator: hashing.NewSHA256KeyGenerator(),
now: time.Date(2026, time.October, 4, 12, 0, 0, 0, time.UTC), now: time.Date(2026, time.October, 4, 12, 0, 0, 0, time.UTC),
settings: config.Settings{AuthRateLimit: config.AuthRateLimitSettings{MaxAttempts: 1000, Window: time.Minute}}, settings: config.Settings{AuthRateLimit: config.AuthRateLimitSettings{MaxAttempts: 1000, Window: time.Minute}},
@@ -100,7 +100,7 @@ func newAPIKeyEnvRecording(t *testing.T, recorder audit.Recorder) *apiKeyEnv {
mail := newMockMailRepo() mail := newMockMailRepo()
env.mail = mail env.mail = mail
renderer := &fakeBodyRenderer{} renderer := &fakeBodyRenderer{}
mergeMedia := useCases.NewMergeMediaUseCase(env.images, env.articles, newMockImageStorage(), newMockVariantFileRepo(), recorder, plainSites(), plainAuthors()) mergeMedia := newTestMergeMedia(env.images, env.articles, newMockImageStorage(), newMockVariantFileRepo(), recorder, plainSites(), plainAuthors(), newMockContentTypeRepo(), newMockEntryRepo())
purgeSettings := newMockPurgeSettingsRepo() purgeSettings := newMockPurgeSettingsRepo()
restartJobs := &fakeJobStore{} restartJobs := &fakeJobStore{}
env.container = &api.UseCases{ env.container = &api.UseCases{
@@ -127,13 +127,13 @@ func newAPIKeyEnvRecording(t *testing.T, recorder audit.Recorder) *apiKeyEnv {
AcceptInviteUseCase: useCases.NewAcceptInviteUseCase(env.users, env.invites, hasher, recorder), AcceptInviteUseCase: useCases.NewAcceptInviteUseCase(env.users, env.invites, hasher, recorder),
CreateImageUseCase: useCases.NewCreateImageUseCase(env.images, newMockImageStorage(), recorder), CreateImageUseCase: useCases.NewCreateImageUseCase(env.images, newMockImageStorage(), recorder),
GenerateVariantsOnUploadUseCase: newInertGenerateOnUploadUseCase(), GenerateVariantsOnUploadUseCase: newInertGenerateOnUploadUseCase(),
ListMediaUseCase: useCases.NewListMediaUseCase(env.images, env.articles, env.users, newMockVariantFileRepo(), plainSites(), plainAuthors()), ListMediaUseCase: useCases.NewListMediaUseCase(env.images, env.articles, env.users, newMockVariantFileRepo(), plainSites(), plainAuthors(), newMockContentTypeRepo(), newMockEntryRepo()),
RenameMediaUseCase: useCases.NewRenameMediaUseCase(env.images, recorder), RenameMediaUseCase: useCases.NewRenameMediaUseCase(env.images, recorder),
DeleteMediaUseCase: useCases.NewDeleteMediaUseCase(env.images, newMockImageStorage(), newMockVariantFileRepo(), recorder, plainSites(), plainAuthors(), env.articles), DeleteMediaUseCase: useCases.NewDeleteMediaUseCase(env.images, newMockImageStorage(), newMockVariantFileRepo(), recorder, plainSites(), plainAuthors(), env.articles),
MergeMediaUseCase: mergeMedia, MergeMediaUseCase: mergeMedia,
RunPurgeUseCase: useCases.NewRunPurgeUseCase(env.images, env.articles, mergeMedia, purgeSettings, clock, log.New(io.Discard, "", 0), recorder, plainSites(), plainAuthors()), RunPurgeUseCase: useCases.NewRunPurgeUseCase(env.images, env.articles, mergeMedia, purgeSettings, clock, log.New(io.Discard, "", 0), recorder, plainSites(), plainAuthors()),
RequestRestartUseCase: useCases.NewRequestRestartUseCase(env.updates, restartJobs, &fakeHelperDetector{installed: true}, &fakeResultStore{}, &fakeRestartRequestStore{}, apiKeyRunningVersion, clock, recorder), RequestRestartUseCase: useCases.NewRequestRestartUseCase(env.updates, restartJobs, &fakeHelperDetector{installed: true}, &fakeResultStore{}, &fakeRestartRequestStore{}, apiKeyRunningVersion, clock, recorder),
GetMediaUsageUseCase: useCases.NewGetMediaUsageUseCase(env.images, env.articles, plainSites(), plainAuthors()), GetMediaUsageUseCase: useCases.NewGetMediaUsageUseCase(env.images, env.articles, plainSites(), plainAuthors(), newMockContentTypeRepo(), newMockEntryRepo()),
GetSettingsUseCase: useCases.NewGetSettingsUseCase(apiKeyRunningVersion), GetSettingsUseCase: useCases.NewGetSettingsUseCase(apiKeyRunningVersion),
GetActivityRetentionUseCase: useCases.NewGetActivityRetentionUseCase(newActivitySettingsFake(), newSizeEvents(t), time.Now), GetActivityRetentionUseCase: useCases.NewGetActivityRetentionUseCase(newActivitySettingsFake(), newSizeEvents(t), time.Now),
GetUpdateStatusUseCase: newUpdateStatusUseCase(env.updates, &fakeJobStore{}, &fakeHelperDetector{}, apiKeyRunningVersion), GetUpdateStatusUseCase: newUpdateStatusUseCase(env.updates, &fakeJobStore{}, &fakeHelperDetector{}, apiKeyRunningVersion),
@@ -172,7 +172,7 @@ type apiKeyRequest struct {
func (e *apiKeyEnv) cookie(t *testing.T, userId uint32, tokenVersion uint32) *http.Cookie { func (e *apiKeyEnv) cookie(t *testing.T, userId uint32, tokenVersion uint32) *http.Cookie {
t.Helper() t.Helper()
_, tokenString, err := e.token.Encode(map[string]any{"user_id": userId, "token_version": tokenVersion}) tokenString, err := e.token.Encode(map[string]any{"user_id": userId, "token_version": tokenVersion})
if err != nil { if err != nil {
t.Fatalf("failed to encode jwt: %v", err) t.Fatalf("failed to encode jwt: %v", err)
} }
+5 -5
View File
@@ -15,8 +15,8 @@ import (
"net/http/httptest" "net/http/httptest"
"testing" "testing"
"RenewCMS/api/pkg/authtoken"
"github.com/go-chi/chi/v5" "github.com/go-chi/chi/v5"
"github.com/go-chi/jwtauth/v5"
) )
type fakeBodyRenderer struct { type fakeBodyRenderer struct {
@@ -40,7 +40,7 @@ const (
bodyFormatArticleOneJSON = `[{"type":"heading","level":2,"children":[{"type":"text","text":"Plan","marks":[]}]},{"type":"paragraph","children":[{"type":"text","text":"Replace the ","marks":[]},{"type":"text","text":"old","marks":[{"type":"bold"}]},{"type":"text","text":" deck.","marks":[]}]}]` bodyFormatArticleOneJSON = `[{"type":"heading","level":2,"children":[{"type":"text","text":"Plan","marks":[]}]},{"type":"paragraph","children":[{"type":"text","text":"Replace the ","marks":[]},{"type":"text","text":"old","marks":[{"type":"bold"}]},{"type":"text","text":" deck.","marks":[]}]}]`
) )
func newBodyFormatRouter(articleRepo *mockArticleRepo, userRepo *mockUserRepo, renderer domainArticle.BodyRenderer, token *jwtauth.JWTAuth) *chi.Mux { func newBodyFormatRouter(articleRepo *mockArticleRepo, userRepo *mockUserRepo, renderer domainArticle.BodyRenderer, token *authtoken.Auth) *chi.Mux {
getUserUseCase := useCases.NewGetUserUseCase(userRepo) getUserUseCase := useCases.NewGetUserUseCase(userRepo)
articleHandler := article.NewHandler( articleHandler := article.NewHandler(
useCases.NewCreateArticleUseCase(articleRepo, renderer, discardRecorder, plainSites(), plainAuthors()), useCases.NewCreateArticleUseCase(articleRepo, renderer, discardRecorder, plainSites(), plainAuthors()),
@@ -54,11 +54,11 @@ func newBodyFormatRouter(articleRepo *mockArticleRepo, userRepo *mockUserRepo, r
r := chi.NewRouter() r := chi.NewRouter()
r.Route("/v1", func(r chi.Router) { r.Route("/v1", func(r chi.Router) {
r.Route("/article", func(r chi.Router) { r.Route("/article", func(r chi.Router) {
r.Use(jwtauth.Verifier(token)) r.Use(authtoken.Verifier(token))
r.Get("/", articleHandler.ListArticles) r.Get("/", articleHandler.ListArticles)
r.Get("/{id}", articleHandler.GetArticle) r.Get("/{id}", articleHandler.GetArticle)
r.Group(func(r chi.Router) { r.Group(func(r chi.Router) {
r.Use(jwtauth.Authenticator(token)) r.Use(authtoken.Authenticator)
r.Use(middleware.RequireVerifiedUser(getUserUseCase)) r.Use(middleware.RequireVerifiedUser(getUserUseCase))
r.Post("/", articleHandler.PostArticle) r.Post("/", articleHandler.PostArticle)
r.Patch("/{id}", articleHandler.UpdateArticleBody) r.Patch("/{id}", articleHandler.UpdateArticleBody)
@@ -145,7 +145,7 @@ func assertSameJSON(t *testing.T, actual, expected string) {
func TestArticleBodyFormatHttp(t *testing.T) { func TestArticleBodyFormatHttp(t *testing.T) {
validator.InitValidator() validator.InitValidator()
token := jwtauth.New("HS256", []byte("test-secret"), nil) token := authtoken.New([]byte("test-secret"))
newRouter := func(repo *mockArticleRepo, users *mockUserRepo, renderer domainArticle.BodyRenderer) *chi.Mux { newRouter := func(repo *mockArticleRepo, users *mockUserRepo, renderer domainArticle.BodyRenderer) *chi.Mux {
return newBodyFormatRouter(repo, users, renderer, token) return newBodyFormatRouter(repo, users, renderer, token)
} }
+6 -6
View File
@@ -14,11 +14,11 @@ import (
"strings" "strings"
"testing" "testing"
"RenewCMS/api/pkg/authtoken"
"github.com/go-chi/chi/v5" "github.com/go-chi/chi/v5"
"github.com/go-chi/jwtauth/v5"
) )
func newUnlimitedBodyRouter(articleRepo *mockArticleRepo, token *jwtauth.JWTAuth) *chi.Mux { func newUnlimitedBodyRouter(articleRepo *mockArticleRepo, token *authtoken.Auth) *chi.Mux {
getUserUseCase := useCases.NewGetUserUseCase(newVerifiedUserRepo()) getUserUseCase := useCases.NewGetUserUseCase(newVerifiedUserRepo())
renderer := markdown.NewConverter() renderer := markdown.NewConverter()
articleHandler := article.NewHandler( articleHandler := article.NewHandler(
@@ -34,9 +34,9 @@ func newUnlimitedBodyRouter(articleRepo *mockArticleRepo, token *jwtauth.JWTAuth
r.Route("/v1", func(r chi.Router) { r.Route("/v1", func(r chi.Router) {
r.Route("/article", func(r chi.Router) { r.Route("/article", func(r chi.Router) {
r.Group(func(r chi.Router) { r.Group(func(r chi.Router) {
r.Use(jwtauth.Verifier(token)) r.Use(authtoken.Verifier(token))
r.Group(func(r chi.Router) { r.Group(func(r chi.Router) {
r.Use(jwtauth.Authenticator(token)) r.Use(authtoken.Authenticator)
r.Use(middleware.RequireVerifiedUser(getUserUseCase)) r.Use(middleware.RequireVerifiedUser(getUserUseCase))
r.Post("/", articleHandler.PostArticle) r.Post("/", articleHandler.PostArticle)
r.Get("/{id}", articleHandler.GetArticle) r.Get("/{id}", articleHandler.GetArticle)
@@ -48,7 +48,7 @@ func newUnlimitedBodyRouter(articleRepo *mockArticleRepo, token *jwtauth.JWTAuth
return r return r
} }
func serveUnlimitedBody(t *testing.T, router *chi.Mux, token *jwtauth.JWTAuth, method, target, payload string) *httptest.ResponseRecorder { func serveUnlimitedBody(t *testing.T, router *chi.Mux, token *authtoken.Auth, method, target, payload string) *httptest.ResponseRecorder {
t.Helper() t.Helper()
req := newEditArticleBodyRequest(method, target, payload) req := newEditArticleBodyRequest(method, target, payload)
setEditArticleBodyJwtCookie(t, req, token) setEditArticleBodyJwtCookie(t, req, token)
@@ -59,7 +59,7 @@ func serveUnlimitedBody(t *testing.T, router *chi.Mux, token *jwtauth.JWTAuth, m
func TestArticleBodyUnlimitedHttp(t *testing.T) { func TestArticleBodyUnlimitedHttp(t *testing.T) {
validator.InitValidator() validator.InitValidator()
token := jwtauth.New("HS256", []byte("test-secret"), nil) token := authtoken.New([]byte("test-secret"))
const title = "Choosing tiles for a small bathroom" const title = "Choosing tiles for a small bathroom"
createCases := []struct { createCases := []struct {
+7 -7
View File
@@ -14,11 +14,11 @@ import (
"net/http/httptest" "net/http/httptest"
"testing" "testing"
"RenewCMS/api/pkg/authtoken"
"github.com/go-chi/chi/v5" "github.com/go-chi/chi/v5"
"github.com/go-chi/jwtauth/v5"
) )
func newArticlePublishingRouter(articleRepo *mockArticleRepo, token *jwtauth.JWTAuth) *chi.Mux { func newArticlePublishingRouter(articleRepo *mockArticleRepo, token *authtoken.Auth) *chi.Mux {
userRepo := newVerifiedUserRepo() userRepo := newVerifiedUserRepo()
getUserUseCase := useCases.NewGetUserUseCase(userRepo) getUserUseCase := useCases.NewGetUserUseCase(userRepo)
@@ -35,10 +35,10 @@ func newArticlePublishingRouter(articleRepo *mockArticleRepo, token *jwtauth.JWT
r.Route("/v1", func(r chi.Router) { r.Route("/v1", func(r chi.Router) {
r.Route("/article", func(r chi.Router) { r.Route("/article", func(r chi.Router) {
r.Group(func(r chi.Router) { r.Group(func(r chi.Router) {
r.Use(jwtauth.Verifier(token)) r.Use(authtoken.Verifier(token))
r.Get("/", articleHandler.ListArticles) r.Get("/", articleHandler.ListArticles)
r.Group(func(r chi.Router) { r.Group(func(r chi.Router) {
r.Use(jwtauth.Authenticator(token)) r.Use(authtoken.Authenticator)
r.Use(middleware.RequireVerifiedUser(getUserUseCase)) r.Use(middleware.RequireVerifiedUser(getUserUseCase))
r.Get("/{id}", articleHandler.GetArticle) r.Get("/{id}", articleHandler.GetArticle)
r.Post("/", articleHandler.PostArticle) r.Post("/", articleHandler.PostArticle)
@@ -59,9 +59,9 @@ func newPublishingTestArticleRepo() *mockArticleRepo {
return repo return repo
} }
func setPublishingJwtCookie(t *testing.T, req *http.Request, token *jwtauth.JWTAuth) { func setPublishingJwtCookie(t *testing.T, req *http.Request, token *authtoken.Auth) {
t.Helper() t.Helper()
_, tokenString, err := token.Encode(map[string]any{"user_id": uint32(1)}) tokenString, err := token.Encode(map[string]any{"user_id": uint32(1)})
if err != nil { if err != nil {
t.Fatalf("failed to encode jwt: %v", err) t.Fatalf("failed to encode jwt: %v", err)
} }
@@ -70,7 +70,7 @@ func setPublishingJwtCookie(t *testing.T, req *http.Request, token *jwtauth.JWTA
func TestArticlePublishingHttp(t *testing.T) { func TestArticlePublishingHttp(t *testing.T) {
validator.InitValidator() validator.InitValidator()
token := jwtauth.New("HS256", []byte("test-secret"), nil) token := authtoken.New([]byte("test-secret"))
t.Run("Publishing an offline article makes it online", func(t *testing.T) { t.Run("Publishing an offline article makes it online", func(t *testing.T) {
repo := newPublishingTestArticleRepo() repo := newPublishingTestArticleRepo()
+6
View File
@@ -25,6 +25,8 @@ type mockArticleRepo struct {
authors *mockAuthorRepo authors *mockAuthorRepo
reportSlugRace bool reportSlugRace bool
createAlwaysRaces bool createAlwaysRaces bool
afterFindByBody func()
updateBodyIDs []uint32
} }
func newMockArticleRepo() *mockArticleRepo { func newMockArticleRepo() *mockArticleRepo {
@@ -315,6 +317,7 @@ func (m *mockArticleRepo) Create(a article.Article) (article.Article, error) {
} }
func (m *mockArticleRepo) UpdateBody(id uint32, body string) (article.Article, error) { func (m *mockArticleRepo) UpdateBody(id uint32, body string) (article.Article, error) {
m.updateBodyIDs = append(m.updateBodyIDs, id)
if err := m.fail.trigger("UpdateBody"); err != nil { if err := m.fail.trigger("UpdateBody"); err != nil {
return article.Article{}, err return article.Article{}, err
} }
@@ -427,6 +430,9 @@ func (m *mockArticleRepo) FindByBodyContaining(filename string) ([]article.Artic
result = append(result, a) result = append(result, a)
} }
} }
if m.afterFindByBody != nil {
defer m.afterFindByBody()
}
return result, nil return result, nil
} }
+6 -6
View File
@@ -17,11 +17,11 @@ import (
"strings" "strings"
"testing" "testing"
"RenewCMS/api/pkg/authtoken"
"github.com/go-chi/chi/v5" "github.com/go-chi/chi/v5"
"github.com/go-chi/jwtauth/v5"
) )
func newArticleTitleRulesRouter(repo *mockArticleRepo, token *jwtauth.JWTAuth) *chi.Mux { func newArticleTitleRulesRouter(repo *mockArticleRepo, token *authtoken.Auth) *chi.Mux {
userRepo := newVerifiedUserRepo() userRepo := newVerifiedUserRepo()
getUserUseCase := useCases.NewGetUserUseCase(userRepo) getUserUseCase := useCases.NewGetUserUseCase(userRepo)
@@ -37,8 +37,8 @@ func newArticleTitleRulesRouter(repo *mockArticleRepo, token *jwtauth.JWTAuth) *
r := chi.NewRouter() r := chi.NewRouter()
r.Route("/v1", func(r chi.Router) { r.Route("/v1", func(r chi.Router) {
r.Group(func(r chi.Router) { r.Group(func(r chi.Router) {
r.Use(jwtauth.Verifier(token)) r.Use(authtoken.Verifier(token))
r.Use(jwtauth.Authenticator(token)) r.Use(authtoken.Authenticator)
r.Use(middleware.RequireVerifiedUser(getUserUseCase)) r.Use(middleware.RequireVerifiedUser(getUserUseCase))
r.Route("/article", func(r chi.Router) { r.Route("/article", func(r chi.Router) {
r.Post("/", articleHandler.PostArticle) r.Post("/", articleHandler.PostArticle)
@@ -48,7 +48,7 @@ func newArticleTitleRulesRouter(repo *mockArticleRepo, token *jwtauth.JWTAuth) *
return r return r
} }
func postArticleRequest(t *testing.T, token *jwtauth.JWTAuth, title string, body string) *http.Request { func postArticleRequest(t *testing.T, token *authtoken.Auth, title string, body string) *http.Request {
t.Helper() t.Helper()
payload, err := json.Marshal(map[string]string{"title": title, "body": body}) payload, err := json.Marshal(map[string]string{"title": title, "body": body})
if err != nil { if err != nil {
@@ -122,7 +122,7 @@ func TestArticleTitleRunesInUseCase(t *testing.T) {
func TestArticleTitleRunesOverHttp(t *testing.T) { func TestArticleTitleRunesOverHttp(t *testing.T) {
validator.InitValidator() validator.InitValidator()
token := jwtauth.New("HS256", []byte("test-secret"), nil) token := authtoken.New([]byte("test-secret"))
cases := []struct { cases := []struct {
length int length int
+4 -4
View File
@@ -9,13 +9,13 @@ import (
"net/http/httptest" "net/http/httptest"
"testing" "testing"
"RenewCMS/api/pkg/authtoken"
"github.com/go-chi/chi/v5" "github.com/go-chi/chi/v5"
"github.com/go-chi/jwtauth/v5"
validator "RenewCMS/api/pkg/validator" validator "RenewCMS/api/pkg/validator"
) )
func newArticlesListRouter(articleRepo *mockArticleRepo, token *jwtauth.JWTAuth) *chi.Mux { func newArticlesListRouter(articleRepo *mockArticleRepo, token *authtoken.Auth) *chi.Mux {
userRepo := newVerifiedUserRepo() userRepo := newVerifiedUserRepo()
getUserUseCase := useCases.NewGetUserUseCase(userRepo) getUserUseCase := useCases.NewGetUserUseCase(userRepo)
@@ -31,7 +31,7 @@ func newArticlesListRouter(articleRepo *mockArticleRepo, token *jwtauth.JWTAuth)
r := chi.NewRouter() r := chi.NewRouter()
r.Route("/v1", func(r chi.Router) { r.Route("/v1", func(r chi.Router) {
r.Route("/article", func(r chi.Router) { r.Route("/article", func(r chi.Router) {
r.Use(jwtauth.Verifier(token)) r.Use(authtoken.Verifier(token))
r.Get("/", articleHandler.ListArticles) r.Get("/", articleHandler.ListArticles)
}) })
}) })
@@ -40,7 +40,7 @@ func newArticlesListRouter(articleRepo *mockArticleRepo, token *jwtauth.JWTAuth)
func TestArticlesListHttp(t *testing.T) { func TestArticlesListHttp(t *testing.T) {
validator.InitValidator() validator.InitValidator()
token := jwtauth.New("HS256", []byte("test-secret"), nil) token := authtoken.New([]byte("test-secret"))
t.Run("GET /v1/article/ items carry no images field now that images belong to the library", func(t *testing.T) { t.Run("GET /v1/article/ items carry no images field now that images belong to the library", func(t *testing.T) {
repo := newMockArticleRepo() repo := newMockArticleRepo()
+2 -2
View File
@@ -15,7 +15,7 @@ import (
"RenewCMS/internal/infrastructure/useCases" "RenewCMS/internal/infrastructure/useCases"
"errors" "errors"
"github.com/go-chi/jwtauth/v5" "RenewCMS/api/pkg/authtoken"
validator "RenewCMS/api/pkg/validator" validator "RenewCMS/api/pkg/validator"
) )
@@ -71,7 +71,7 @@ func itemIds(envelope paginationEnvelope) []int {
func TestArticlesPaginationApiHttp(t *testing.T) { func TestArticlesPaginationApiHttp(t *testing.T) {
validator.InitValidator() validator.InitValidator()
token := jwtauth.New("HS256", []byte("test-secret"), nil) token := authtoken.New([]byte("test-secret"))
get := func(t *testing.T, repo *mockArticleRepo, query string, verified bool) (*httptest.ResponseRecorder, paginationEnvelope) { get := func(t *testing.T, repo *mockArticleRepo, query string, verified bool) (*httptest.ResponseRecorder, paginationEnvelope) {
t.Helper() t.Helper()
+6 -3
View File
@@ -321,6 +321,9 @@ func (m *mockAuthorRepo) AssignAvatar(authorIDs []uint32, imageID uint32) error
} }
func (m *mockAuthorRepo) RepointAvatar(fromImageIDs []uint32, toImageID uint32) (int, error) { func (m *mockAuthorRepo) RepointAvatar(fromImageIDs []uint32, toImageID uint32) (int, error) {
if err := m.fail.trigger("RepointAvatar"); err != nil {
return 0, err
}
changed := 0 changed := 0
for id, a := range m.authors { for id, a := range m.authors {
if a.AvatarID != nil && containsID(fromImageIDs, *a.AvatarID) { if a.AvatarID != nil && containsID(fromImageIDs, *a.AvatarID) {
@@ -355,14 +358,14 @@ func newAuthorEnv(t *testing.T) *authorEnv {
sites := plainSites() sites := plainSites()
recorder := p.audit.recorder recorder := p.audit.recorder
renderer := &fakeBodyRenderer{} renderer := &fakeBodyRenderer{}
mergeMedia := useCases.NewMergeMediaUseCase(p.images, p.articles, newMockImageStorage(), newMockVariantFileRepo(), recorder, sites, authors) mergeMedia := newTestMergeMedia(p.images, p.articles, newMockImageStorage(), newMockVariantFileRepo(), recorder, sites, authors, newMockContentTypeRepo(), newMockEntryRepo())
c := p.container c := p.container
c.CreateArticleUseCase = useCases.NewCreateArticleUseCase(p.articles, renderer, recorder, sites, authors) c.CreateArticleUseCase = useCases.NewCreateArticleUseCase(p.articles, renderer, recorder, sites, authors)
c.UpdateArticleUseCase = useCases.NewUpdateArticleUseCase(p.articles, renderer, recorder, sites, authors, p.images) c.UpdateArticleUseCase = useCases.NewUpdateArticleUseCase(p.articles, renderer, recorder, sites, authors, p.images)
c.ListMediaUseCase = useCases.NewListMediaUseCase(p.images, p.articles, p.users, newMockVariantFileRepo(), sites, authors) c.ListMediaUseCase = useCases.NewListMediaUseCase(p.images, p.articles, p.users, newMockVariantFileRepo(), sites, authors, newMockContentTypeRepo(), newMockEntryRepo())
c.DeleteMediaUseCase = useCases.NewDeleteMediaUseCase(p.images, newMockImageStorage(), newMockVariantFileRepo(), recorder, sites, authors, p.articles) c.DeleteMediaUseCase = useCases.NewDeleteMediaUseCase(p.images, newMockImageStorage(), newMockVariantFileRepo(), recorder, sites, authors, p.articles)
c.MergeMediaUseCase = mergeMedia c.MergeMediaUseCase = mergeMedia
c.GetMediaUsageUseCase = useCases.NewGetMediaUsageUseCase(p.images, p.articles, sites, authors) c.GetMediaUsageUseCase = useCases.NewGetMediaUsageUseCase(p.images, p.articles, sites, authors, newMockContentTypeRepo(), newMockEntryRepo())
c.RunPurgeUseCase = useCases.NewRunPurgeUseCase(p.images, p.articles, mergeMedia, newMockPurgeSettingsRepo(), func() time.Time { return p.now }, log.New(io.Discard, "", 0), recorder, sites, authors) c.RunPurgeUseCase = useCases.NewRunPurgeUseCase(p.images, p.articles, mergeMedia, newMockPurgeSettingsRepo(), func() time.Time { return p.now }, log.New(io.Discard, "", 0), recorder, sites, authors)
c.ListActivityUseCase = useCases.NewListActivityUseCase(p.audit.store, p.users, p.articles, p.images, p.keys, p.audit.clock, sites, authors) c.ListActivityUseCase = useCases.NewListActivityUseCase(p.audit.store, p.users, p.articles, p.images, p.keys, p.audit.clock, sites, authors)
c.ListAuthorsUseCase = useCases.NewListAuthorsUseCase(authors, p.users) c.ListAuthorsUseCase = useCases.NewListAuthorsUseCase(authors, p.users)
+162
View File
@@ -0,0 +1,162 @@
package test
import (
"RenewCMS/api/pkg/apperr"
"RenewCMS/api/pkg/authtoken"
"net/http"
"net/http/httptest"
"testing"
)
type authTokenProbe struct {
reached bool
claims authtoken.Claims
err error
}
func authTokenRouter(auth *authtoken.Auth, probe *authTokenProbe, guarded bool) http.Handler {
final := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
probe.reached = true
probe.claims, probe.err = authtoken.FromContext(r.Context())
w.WriteHeader(http.StatusOK)
})
if guarded {
return authtoken.Verifier(auth)(authtoken.Authenticator(final))
}
return authtoken.Verifier(auth)(final)
}
func serveAuthToken(handler http.Handler, configure func(*http.Request)) *httptest.ResponseRecorder {
req := httptest.NewRequest(http.MethodGet, "/", nil)
configure(req)
rec := httptest.NewRecorder()
handler.ServeHTTP(rec, req)
return rec
}
func TestAuthTokenVerifierAndAuthenticator(t *testing.T) {
auth := authtoken.New([]byte("test-secret"))
valid, _ := auth.Encode(map[string]any{"user_id": uint32(5)})
other, _ := auth.Encode(map[string]any{"user_id": uint32(9)})
t.Run("A valid jwt cookie reaches the handler with its claims", func(t *testing.T) {
probe := &authTokenProbe{}
rec := serveAuthToken(authTokenRouter(auth, probe, true), func(r *http.Request) {
r.AddCookie(&http.Cookie{Name: "jwt", Value: valid})
})
if rec.Code != http.StatusOK || probe.claims["user_id"] != float64(5) {
t.Errorf("expected 200 with user 5, got %d and %v", rec.Code, probe.claims)
}
})
t.Run("A bearer header in any letter case is accepted", func(t *testing.T) {
for _, scheme := range []string{"Bearer ", "BEARER ", "bearer "} {
probe := &authTokenProbe{}
rec := serveAuthToken(authTokenRouter(auth, probe, true), func(r *http.Request) {
r.Header.Set("Authorization", scheme+valid)
})
if rec.Code != http.StatusOK {
t.Errorf("scheme %q: expected 200, got %d", scheme, rec.Code)
}
}
})
t.Run("The bearer header wins over the cookie", func(t *testing.T) {
probe := &authTokenProbe{}
serveAuthToken(authTokenRouter(auth, probe, true), func(r *http.Request) {
r.Header.Set("Authorization", "Bearer "+valid)
r.AddCookie(&http.Cookie{Name: "jwt", Value: other})
})
if probe.claims["user_id"] != float64(5) {
t.Errorf("expected the header token, got %v", probe.claims)
}
})
t.Run("A malformed Authorization header falls back to the cookie", func(t *testing.T) {
for _, header := range []string{"Bearer", "Bearer ", "Basic abc", "Token " + valid} {
probe := &authTokenProbe{}
rec := serveAuthToken(authTokenRouter(auth, probe, true), func(r *http.Request) {
r.Header.Set("Authorization", header)
r.AddCookie(&http.Cookie{Name: "jwt", Value: valid})
})
if rec.Code != http.StatusOK {
t.Errorf("header %q: expected the cookie to be used, got %d", header, rec.Code)
}
}
})
t.Run("The authenticator answers 401 with the standard message when no token is sent", func(t *testing.T) {
probe := &authTokenProbe{}
rec := serveAuthToken(authTokenRouter(auth, probe, true), func(*http.Request) {})
if rec.Code != http.StatusUnauthorized || probe.reached {
t.Fatalf("expected a blocked 401, got %d reached=%v", rec.Code, probe.reached)
}
if got := rec.Body.String(); got != apperr.UnauthorizedErrorMessage+"\n" {
t.Errorf("unexpected body %q", got)
}
})
t.Run("The authenticator rejects a forged token", func(t *testing.T) {
probe := &authTokenProbe{}
forged, _ := authtoken.New([]byte("another-secret")).Encode(map[string]any{"user_id": 1})
rec := serveAuthToken(authTokenRouter(auth, probe, true), func(r *http.Request) {
r.AddCookie(&http.Cookie{Name: "jwt", Value: forged})
})
if rec.Code != http.StatusUnauthorized || probe.reached {
t.Errorf("expected a blocked 401, got %d reached=%v", rec.Code, probe.reached)
}
})
t.Run("Without the authenticator the handler sees the verification error", func(t *testing.T) {
probe := &authTokenProbe{}
serveAuthToken(authTokenRouter(auth, probe, false), func(r *http.Request) {
r.AddCookie(&http.Cookie{Name: "jwt", Value: "garbage"})
})
if !probe.reached || probe.err == nil || probe.claims != nil {
t.Errorf("expected an error and no claims, got %v / %v", probe.claims, probe.err)
}
})
t.Run("A context that never passed the verifier reports no token", func(t *testing.T) {
req := httptest.NewRequest(http.MethodGet, "/", nil)
if _, err := authtoken.FromContext(req.Context()); err != authtoken.ErrNoToken {
t.Errorf("expected ErrNoToken, got %v", err)
}
})
t.Run("A context carrying nil claims and no error still reports no token", func(t *testing.T) {
ctx := authtoken.NewContext(httptest.NewRequest(http.MethodGet, "/", nil).Context(), nil, nil)
if _, err := authtoken.FromContext(ctx); err != authtoken.ErrNoToken {
t.Errorf("expected ErrNoToken, got %v", err)
}
})
t.Run("A context injected with claims is authenticated", func(t *testing.T) {
probe := &authTokenProbe{}
handler := authtoken.Authenticator(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { probe.reached = true }))
req := httptest.NewRequest(http.MethodGet, "/", nil)
req = req.WithContext(authtoken.NewContext(req.Context(), authtoken.Claims{"user_id": float64(1)}, nil))
handler.ServeHTTP(httptest.NewRecorder(), req)
if !probe.reached {
t.Error("expected the handler to be reached")
}
})
}
+181
View File
@@ -0,0 +1,181 @@
package test
import (
"RenewCMS/api/pkg/authtoken"
"crypto/hmac"
"crypto/sha256"
"encoding/base64"
"errors"
"strconv"
"strings"
"testing"
"time"
)
var authTokenEpoch = time.Date(2026, time.March, 1, 12, 0, 0, 0, time.UTC)
func authTokenAt(now time.Time) *authtoken.Auth {
return authtoken.New([]byte("test-secret"), authtoken.WithClock(func() time.Time { return now }))
}
func signedAuthTokenSegments(secret string, header string, payload string) string {
encode := base64.RawURLEncoding.EncodeToString
signingInput := encode([]byte(header)) + "." + encode([]byte(payload))
mac := hmac.New(sha256.New, []byte(secret))
mac.Write([]byte(signingInput))
return signingInput + "." + encode(mac.Sum(nil))
}
func TestAuthTokenEncodeDecode(t *testing.T) {
t.Run("A token round-trips its claims", func(t *testing.T) {
auth := authTokenAt(authTokenEpoch)
encoded, err := auth.Encode(map[string]any{"user_id": uint32(7), "token_version": uint32(3)})
if err != nil {
t.Fatalf("encode failed: %v", err)
}
claims, err := auth.Decode(encoded)
if err != nil {
t.Fatalf("decode failed: %v", err)
}
if claims["user_id"] != float64(7) || claims["token_version"] != float64(3) {
t.Errorf("unexpected claims %v", claims)
}
})
t.Run("Encoding stamps iat and an exp one session lifetime ahead", func(t *testing.T) {
auth := authTokenAt(authTokenEpoch)
encoded, _ := auth.Encode(map[string]any{"user_id": 1})
claims, _ := auth.Decode(encoded)
if claims["iat"] != float64(authTokenEpoch.Unix()) {
t.Errorf("expected iat %d, got %v", authTokenEpoch.Unix(), claims["iat"])
}
if claims["exp"] != float64(authTokenEpoch.Add(authtoken.SessionLifetime).Unix()) {
t.Errorf("unexpected exp %v", claims["exp"])
}
})
t.Run("Encoding keeps an explicit exp", func(t *testing.T) {
auth := authTokenAt(authTokenEpoch)
explicit := authTokenEpoch.Add(time.Minute).Unix()
encoded, _ := auth.Encode(map[string]any{"exp": explicit})
claims, _ := auth.Decode(encoded)
if claims["exp"] != float64(explicit) {
t.Errorf("expected exp %d, got %v", explicit, claims["exp"])
}
})
t.Run("Encoding does not mutate the caller's claims", func(t *testing.T) {
input := map[string]any{"user_id": 1}
_, _ = authTokenAt(authTokenEpoch).Encode(input)
if len(input) != 1 {
t.Errorf("input was mutated: %v", input)
}
})
t.Run("Encoding nil claims still yields a decodable token", func(t *testing.T) {
auth := authTokenAt(authTokenEpoch)
encoded, err := auth.Encode(nil)
if err != nil {
t.Fatalf("encode failed: %v", err)
}
if _, err := auth.Decode(encoded); err != nil {
t.Errorf("decode failed: %v", err)
}
})
t.Run("Encoding reports claims that cannot be serialized", func(t *testing.T) {
if _, err := authTokenAt(authTokenEpoch).Encode(map[string]any{"bad": make(chan int)}); err == nil {
t.Error("expected an error")
}
})
}
func TestAuthTokenDecodeRejections(t *testing.T) {
auth := authTokenAt(authTokenEpoch)
valid, _ := auth.Encode(map[string]any{"user_id": 1})
segments := strings.Split(valid, ".")
header := `{"alg":"HS256","typ":"JWT"}`
cases := map[string]struct {
token string
want error
}{
"empty": {"", authtoken.ErrNoToken},
"one segment": {"abc", authtoken.ErrInvalid},
"four segments": {valid + ".x", authtoken.ErrInvalid},
"not base64 header": {"!!!." + segments[1] + "." + segments[2], authtoken.ErrInvalid},
"signed with another secret": {signedAuthTokenSegments("other", header, `{"user_id":1}`), authtoken.ErrInvalid},
"alg none": {signedAuthTokenSegments("test-secret", `{"alg":"none"}`, `{"user_id":1}`), authtoken.ErrInvalid},
"alg HS512": {signedAuthTokenSegments("test-secret", `{"alg":"HS512"}`, `{"user_id":1}`), authtoken.ErrInvalid},
"alg missing": {signedAuthTokenSegments("test-secret", `{}`, `{"user_id":1}`), authtoken.ErrInvalid},
"tampered payload": {segments[0] + "." + base64.RawURLEncoding.EncodeToString([]byte(`{"user_id":2}`)) + "." + segments[2], authtoken.ErrInvalid},
"truncated signature": {segments[0] + "." + segments[1] + "." + segments[2][:10], authtoken.ErrInvalid},
"empty signature": {segments[0] + "." + segments[1] + ".", authtoken.ErrInvalid},
"payload not an object": {signedAuthTokenSegments("test-secret", header, `[1]`), authtoken.ErrInvalid},
"payload null": {signedAuthTokenSegments("test-secret", header, `null`), authtoken.ErrInvalid},
"exp not a number": {signedAuthTokenSegments("test-secret", header, `{"exp":"soon"}`), authtoken.ErrInvalid},
"nbf not a number": {signedAuthTokenSegments("test-secret", header, `{"nbf":"soon"}`), authtoken.ErrInvalid},
"expired": {signedAuthTokenSegments("test-secret", header, `{"exp":`+authTokenUnix(authTokenEpoch.Add(-time.Second).Unix())+`}`), authtoken.ErrExpired},
"expiring exactly now": {signedAuthTokenSegments("test-secret", header, `{"exp":`+authTokenUnix(authTokenEpoch.Unix())+`}`), authtoken.ErrExpired},
"not yet valid": {signedAuthTokenSegments("test-secret", header, `{"nbf":`+authTokenUnix(authTokenEpoch.Add(time.Second).Unix())+`}`), authtoken.ErrNotYetValid},
"larger than the size budget": {strings.Repeat("a", 5000), authtoken.ErrInvalid},
}
for name, tc := range cases {
t.Run("Rejects "+name, func(t *testing.T) {
claims, err := auth.Decode(tc.token)
if !errors.Is(err, tc.want) {
t.Errorf("expected %v, got %v", tc.want, err)
}
if claims != nil {
t.Errorf("expected no claims, got %v", claims)
}
})
}
t.Run("Accepts a token with no exp so sessions issued before expiry existed keep working", func(t *testing.T) {
legacy := signedAuthTokenSegments("test-secret", header, `{"user_id":4,"token_version":1}`)
claims, err := auth.Decode(legacy)
if err != nil || claims["user_id"] != float64(4) {
t.Errorf("expected legacy token accepted, got %v, %v", claims, err)
}
})
t.Run("Accepts a token whose nbf has passed", func(t *testing.T) {
token := signedAuthTokenSegments("test-secret", header, `{"nbf":`+authTokenUnix(authTokenEpoch.Add(-time.Second).Unix())+`}`)
if _, err := auth.Decode(token); err != nil {
t.Errorf("expected acceptance, got %v", err)
}
})
t.Run("A token expires once the clock passes its lifetime", func(t *testing.T) {
encoded, _ := auth.Encode(map[string]any{"user_id": 1})
justBefore := authTokenAt(authTokenEpoch.Add(authtoken.SessionLifetime - time.Second))
justAfter := authTokenAt(authTokenEpoch.Add(authtoken.SessionLifetime))
if _, err := justBefore.Decode(encoded); err != nil {
t.Errorf("expected valid before expiry, got %v", err)
}
if _, err := justAfter.Decode(encoded); !errors.Is(err, authtoken.ErrExpired) {
t.Errorf("expected expired, got %v", err)
}
})
}
func authTokenUnix(value int64) string {
return strconv.FormatInt(value, 10)
}
@@ -11,11 +11,11 @@ import (
"net/http/httptest" "net/http/httptest"
"testing" "testing"
"RenewCMS/api/pkg/authtoken"
"github.com/go-chi/chi/v5" "github.com/go-chi/chi/v5"
"github.com/go-chi/jwtauth/v5"
) )
func newCancelRegistrationRouter(userRepo *mockUserRepo, mailRepo *mockMailRepo, token *jwtauth.JWTAuth) *chi.Mux { func newCancelRegistrationRouter(userRepo *mockUserRepo, mailRepo *mockMailRepo, token *authtoken.Auth) *chi.Mux {
hasher := &stubHasher{} hasher := &stubHasher{}
loginHandler := auth.NewLoginHandler( loginHandler := auth.NewLoginHandler(
token, token,
@@ -34,8 +34,8 @@ func newCancelRegistrationRouter(userRepo *mockUserRepo, mailRepo *mockMailRepo,
r.Route("/auth", func(r chi.Router) { r.Route("/auth", func(r chi.Router) {
r.Post("/register", loginHandler.Register) r.Post("/register", loginHandler.Register)
r.Group(func(r chi.Router) { r.Group(func(r chi.Router) {
r.Use(jwtauth.Verifier(token)) r.Use(authtoken.Verifier(token))
r.Use(jwtauth.Authenticator(token)) r.Use(authtoken.Authenticator)
r.Post("/verify", verificationHandler.Verify) r.Post("/verify", verificationHandler.Verify)
r.Delete("/register", verificationHandler.CancelRegistration) r.Delete("/register", verificationHandler.CancelRegistration)
}) })
@@ -56,10 +56,10 @@ func newCancelRegistrationTestUserRepo(isVerified bool) *mockUserRepo {
return repo return repo
} }
func sendCancelRegistrationRequest(router *chi.Mux, token *jwtauth.JWTAuth, claims map[string]any) *httptest.ResponseRecorder { func sendCancelRegistrationRequest(router *chi.Mux, token *authtoken.Auth, claims map[string]any) *httptest.ResponseRecorder {
req := httptest.NewRequest(http.MethodDelete, "/v1/auth/register", nil) req := httptest.NewRequest(http.MethodDelete, "/v1/auth/register", nil)
if claims != nil { if claims != nil {
_, tokenString, _ := token.Encode(claims) tokenString, _ := token.Encode(claims)
req.AddCookie(&http.Cookie{Name: "jwt", Value: tokenString}) req.AddCookie(&http.Cookie{Name: "jwt", Value: tokenString})
} }
rec := httptest.NewRecorder() rec := httptest.NewRecorder()
@@ -83,7 +83,7 @@ func jwtSetCookie(t *testing.T, rec *httptest.ResponseRecorder) (*http.Cookie, b
func TestCancelPendingRegistrationHttp(t *testing.T) { func TestCancelPendingRegistrationHttp(t *testing.T) {
validator.InitValidator() validator.InitValidator()
token := jwtauth.New("HS256", []byte("test-secret"), nil) token := authtoken.New([]byte("test-secret"))
t.Run("An unverified user cancels their pending registration", func(t *testing.T) { t.Run("An unverified user cancels their pending registration", func(t *testing.T) {
repo := newCancelRegistrationTestUserRepo(false) repo := newCancelRegistrationTestUserRepo(false)
+6 -6
View File
@@ -7,12 +7,12 @@ import (
"net/http/httptest" "net/http/httptest"
"testing" "testing"
"github.com/go-chi/jwtauth/v5" "RenewCMS/api/pkg/authtoken"
) )
func requestWithJwtClaims(t *testing.T, token *jwtauth.JWTAuth, claimsToEncode map[string]any) *http.Request { func requestWithJwtClaims(t *testing.T, token *authtoken.Auth, claimsToEncode map[string]any) *http.Request {
t.Helper() t.Helper()
_, tokenString, err := token.Encode(claimsToEncode) tokenString, err := token.Encode(claimsToEncode)
if err != nil { if err != nil {
t.Fatalf("failed to encode jwt: %v", err) t.Fatalf("failed to encode jwt: %v", err)
} }
@@ -21,11 +21,11 @@ func requestWithJwtClaims(t *testing.T, token *jwtauth.JWTAuth, claimsToEncode m
t.Fatalf("failed to decode jwt: %v", err) t.Fatalf("failed to decode jwt: %v", err)
} }
req := httptest.NewRequest(http.MethodGet, "/", nil) req := httptest.NewRequest(http.MethodGet, "/", nil)
return req.WithContext(jwtauth.NewContext(req.Context(), decoded, nil)) return req.WithContext(authtoken.NewContext(req.Context(), decoded, nil))
} }
func TestClaimsTokenVersion(t *testing.T) { func TestClaimsTokenVersion(t *testing.T) {
token := jwtauth.New("HS256", []byte("test-secret"), nil) token := authtoken.New([]byte("test-secret"))
t.Run("returns the numeric token_version claim", func(t *testing.T) { t.Run("returns the numeric token_version claim", func(t *testing.T) {
req := requestWithJwtClaims(t, token, map[string]any{"user_id": uint32(7), "token_version": uint32(3)}) req := requestWithJwtClaims(t, token, map[string]any{"user_id": uint32(7), "token_version": uint32(3)})
@@ -68,7 +68,7 @@ func TestClaimsTokenVersion(t *testing.T) {
} }
func TestClaimsUserId(t *testing.T) { func TestClaimsUserId(t *testing.T) {
token := jwtauth.New("HS256", []byte("test-secret"), nil) token := authtoken.New([]byte("test-secret"))
t.Run("returns the numeric user_id claim", func(t *testing.T) { t.Run("returns the numeric user_id claim", func(t *testing.T) {
req := requestWithJwtClaims(t, token, map[string]any{"user_id": uint32(7)}) req := requestWithJwtClaims(t, token, map[string]any{"user_id": uint32(7)})
Loaded 100 of 233 files, more files were not shown because too many files have changed in this diff. Show more