Compare commits
25
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
07f5c5d1ee | ||
|
|
ea98c5ec05 | ||
|
|
e2812ee0b9 | ||
|
|
aa5d3582f8 | ||
|
|
c68e9a7858 | ||
|
|
cfcf108488 | ||
|
|
b43cc6861f | ||
|
|
074944c99a | ||
|
|
0fc3511e2b | ||
|
|
3e7fc9a4a5 | ||
|
|
a2d596f4ca | ||
|
|
ad5faf3d19 | ||
|
|
89051b3f1f | ||
|
|
fba20f83c5 | ||
|
|
91d916fb74 | ||
|
|
b4cbcb0395 | ||
|
|
5404291af2 | ||
|
|
76e9e1220c | ||
|
|
8e344b2500 | ||
|
|
083cc9e23e | ||
|
|
f514146fed | ||
|
|
3c67cd2314 | ||
|
|
73a75d5cb9 | ||
|
|
e6e088c963 | ||
|
|
58d58f5a04 |
No files matched your search
@@ -14,6 +14,7 @@ CORS_ALLOWED_ORIGINS=
|
|||||||
AUTH_RATE_LIMIT_MAX_ATTEMPTS=5
|
AUTH_RATE_LIMIT_MAX_ATTEMPTS=5
|
||||||
AUTH_RATE_LIMIT_WINDOW_SECONDS=60
|
AUTH_RATE_LIMIT_WINDOW_SECONDS=60
|
||||||
TRUSTED_PROXIES=
|
TRUSTED_PROXIES=
|
||||||
|
SMTP_ALLOW_INSECURE=false
|
||||||
UPDATE_FEED_URL=https://git.floriansylvain.fr
|
UPDATE_FEED_URL=https://git.floriansylvain.fr
|
||||||
RENEWCMS_CONTAINER=false
|
RENEWCMS_CONTAINER=false
|
||||||
IMAGE_VARIANT_MAX_SOURCE_BYTES=10485760
|
IMAGE_VARIANT_MAX_SOURCE_BYTES=10485760
|
||||||
|
|||||||
@@ -28,3 +28,4 @@ CLAUDE.md
|
|||||||
.agents/
|
.agents/
|
||||||
AGENTS.md
|
AGENTS.md
|
||||||
codex-workflow.md
|
codex-workflow.md
|
||||||
|
CODING_STANDARDS.md
|
||||||
@@ -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
@@ -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
|
||||||
|
|||||||
@@ -47,10 +47,12 @@ task dev # API with hot reload + Vite HMR → http://localhost:51
|
|||||||
| [docs/deployment.md](docs/deployment.md) | Building release binaries, running as a service, HTTPS, backups, upgrades |
|
| [docs/deployment.md](docs/deployment.md) | Building release binaries, running as a service, HTTPS, backups, upgrades |
|
||||||
| [docs/docker.md](docs/docker.md) | Running RenewCMS in Docker: image, Compose, data volume, backups, reverse proxy, tags, upgrades, publishing |
|
| [docs/docker.md](docs/docker.md) | Running RenewCMS in Docker: image, Compose, data volume, backups, reverse proxy, tags, upgrades, publishing |
|
||||||
| [docs/configuration.md](docs/configuration.md) | Every environment variable |
|
| [docs/configuration.md](docs/configuration.md) | Every environment variable |
|
||||||
|
| [docs/privacy.md](docs/privacy.md) | Personal data stored, retention, cookies, outbound connections and GDPR requests |
|
||||||
| [docs/architecture.md](docs/architecture.md) | Backend layering and how the SPA is embedded |
|
| [docs/architecture.md](docs/architecture.md) | Backend layering and how the SPA is embedded |
|
||||||
| [docs/performance.md](docs/performance.md) | Measured costs, such as the `?seo=` article filter |
|
| [docs/performance.md](docs/performance.md) | Measured costs, such as the `?seo=` article filter |
|
||||||
| [docs/api.md](docs/api.md) | API reference: authentication, API keys, routes and the activity log |
|
| [docs/api.md](docs/api.md) | API reference: authentication, API keys, routes and the activity log |
|
||||||
| [docs/api/articles.md](docs/api/articles.md) | Reading articles: pagination, search, `format` and body schemas |
|
| [docs/api/articles.md](docs/api/articles.md) | Reading articles: pagination, search, `format` and body schemas |
|
||||||
|
| [docs/custom-content-types.md](docs/custom-content-types.md) | Custom content types: layering, phase 1 limitations and their fix path |
|
||||||
| [docs/image-variants.md](docs/image-variants.md) | Image variants and their cache |
|
| [docs/image-variants.md](docs/image-variants.md) | Image variants and their cache |
|
||||||
| [docs/release-notes.md](docs/release-notes.md) | Release notes format, the published releases and how to publish one |
|
| [docs/release-notes.md](docs/release-notes.md) | Release notes format, the published releases and how to publish one |
|
||||||
|
|
||||||
|
|||||||
+49
-10
@@ -1,15 +1,20 @@
|
|||||||
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"
|
||||||
domainAuthor "RenewCMS/internal/domain/author"
|
domainAuthor "RenewCMS/internal/domain/author"
|
||||||
|
domainContentType "RenewCMS/internal/domain/contenttype"
|
||||||
|
domainEntry "RenewCMS/internal/domain/entry"
|
||||||
domainImage "RenewCMS/internal/domain/image"
|
domainImage "RenewCMS/internal/domain/image"
|
||||||
domainInvite "RenewCMS/internal/domain/invite"
|
domainInvite "RenewCMS/internal/domain/invite"
|
||||||
domainMail "RenewCMS/internal/domain/mail"
|
domainMail "RenewCMS/internal/domain/mail"
|
||||||
domainPurge "RenewCMS/internal/domain/purge"
|
domainPurge "RenewCMS/internal/domain/purge"
|
||||||
|
domainSession "RenewCMS/internal/domain/session"
|
||||||
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"
|
||||||
@@ -34,16 +39,15 @@ 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
|
||||||
|
RetentionScheduler *scheduler.Runner
|
||||||
CreateArticleUseCase *useCases.CreateArticleUseCase
|
CreateArticleUseCase *useCases.CreateArticleUseCase
|
||||||
GetArticleUseCase *useCases.GetArticleUseCase
|
GetArticleUseCase *useCases.GetArticleUseCase
|
||||||
ListArticlesUseCase *useCases.ListArticlesUseCase
|
ListArticlesUseCase *useCases.ListArticlesUseCase
|
||||||
@@ -63,6 +67,19 @@ type UseCases struct {
|
|||||||
UpdateSiteUseCase *useCases.UpdateSiteUseCase
|
UpdateSiteUseCase *useCases.UpdateSiteUseCase
|
||||||
SetDefaultSiteUseCase *useCases.SetDefaultSiteUseCase
|
SetDefaultSiteUseCase *useCases.SetDefaultSiteUseCase
|
||||||
DeleteSiteUseCase *useCases.DeleteSiteUseCase
|
DeleteSiteUseCase *useCases.DeleteSiteUseCase
|
||||||
|
CreateContentTypeUseCase *useCases.CreateContentTypeUseCase
|
||||||
|
ListContentTypesUseCase *useCases.ListContentTypesUseCase
|
||||||
|
GetContentTypeUseCase *useCases.GetContentTypeUseCase
|
||||||
|
UpdateContentTypeUseCase *useCases.UpdateContentTypeUseCase
|
||||||
|
DeleteContentTypeUseCase *useCases.DeleteContentTypeUseCase
|
||||||
|
ListBuiltinTypesUseCase *useCases.ListBuiltinTypesUseCase
|
||||||
|
GetBuiltinTypeUseCase *useCases.GetBuiltinTypeUseCase
|
||||||
|
LookupUserNamesUseCase *useCases.LookupUserNamesUseCase
|
||||||
|
CreateEntryUseCase *useCases.CreateEntryUseCase
|
||||||
|
GetEntryUseCase *useCases.GetEntryUseCase
|
||||||
|
ListEntriesUseCase *useCases.ListEntriesUseCase
|
||||||
|
UpdateEntryUseCase *useCases.UpdateEntryUseCase
|
||||||
|
DeleteEntryUseCase *useCases.DeleteEntryUseCase
|
||||||
GetUserUseCase *useCases.GetUserUseCase
|
GetUserUseCase *useCases.GetUserUseCase
|
||||||
CreateUserUseCase *useCases.CreateUserUseCase
|
CreateUserUseCase *useCases.CreateUserUseCase
|
||||||
AuthenticateUserUseCase *useCases.AuthenticateUserUseCase
|
AuthenticateUserUseCase *useCases.AuthenticateUserUseCase
|
||||||
@@ -124,7 +141,7 @@ type UseCases struct {
|
|||||||
|
|
||||||
func (c *UseCases) RunSchedulers(ctx context.Context) {
|
func (c *UseCases) RunSchedulers(ctx context.Context) {
|
||||||
var running sync.WaitGroup
|
var running sync.WaitGroup
|
||||||
for _, runner := range []*scheduler.Runner{c.PurgeScheduler, c.ActivityCleanupScheduler} {
|
for _, runner := range []*scheduler.Runner{c.PurgeScheduler, c.ActivityCleanupScheduler, c.RetentionScheduler} {
|
||||||
if runner == nil {
|
if runner == nil {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
@@ -140,9 +157,12 @@ func (c *UseCases) RunSchedulers(ctx context.Context) {
|
|||||||
type Repositories struct {
|
type Repositories struct {
|
||||||
ArticleRepo domainArticle.Repository
|
ArticleRepo domainArticle.Repository
|
||||||
SiteRepo domainSite.Repository
|
SiteRepo domainSite.Repository
|
||||||
|
ContentTypeRepo domainContentType.Repository
|
||||||
|
EntryRepo domainEntry.Repository
|
||||||
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
|
||||||
@@ -150,6 +170,7 @@ type Repositories struct {
|
|||||||
VariantRenderer domainImage.VariantRenderer
|
VariantRenderer domainImage.VariantRenderer
|
||||||
InviteRepo domainInvite.Repository
|
InviteRepo domainInvite.Repository
|
||||||
APIKeyRepo domainAPIKey.Repository
|
APIKeyRepo domainAPIKey.Repository
|
||||||
|
SessionRepo domainSession.Repository
|
||||||
PurgeSettingsRepo domainPurge.Repository
|
PurgeSettingsRepo domainPurge.Repository
|
||||||
AuditRepo domainAudit.Repository
|
AuditRepo domainAudit.Repository
|
||||||
AuditSettingsRepo domainAudit.SettingsRepository
|
AuditSettingsRepo domainAudit.SettingsRepository
|
||||||
@@ -280,9 +301,12 @@ func getRepositories(connection *database.Connection, settings config.Settings)
|
|||||||
return &Repositories{
|
return &Repositories{
|
||||||
ArticleRepo: persistence.NewArticleRepository(db),
|
ArticleRepo: persistence.NewArticleRepository(db),
|
||||||
SiteRepo: persistence.NewSiteRepository(db),
|
SiteRepo: persistence.NewSiteRepository(db),
|
||||||
|
ContentTypeRepo: persistence.NewContentTypeRepository(db),
|
||||||
|
EntryRepo: persistence.NewEntryRepository(db),
|
||||||
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,
|
||||||
@@ -290,6 +314,7 @@ func getRepositories(connection *database.Connection, settings config.Settings)
|
|||||||
VariantRenderer: imaging.NewVariantRenderer(),
|
VariantRenderer: imaging.NewVariantRenderer(),
|
||||||
InviteRepo: persistence.NewInviteRepository(db),
|
InviteRepo: persistence.NewInviteRepository(db),
|
||||||
APIKeyRepo: persistence.NewAPIKeyRepository(db),
|
APIKeyRepo: persistence.NewAPIKeyRepository(db),
|
||||||
|
SessionRepo: persistence.NewRevokedSessionRepository(db),
|
||||||
PurgeSettingsRepo: persistence.NewPurgeSettingsRepository(db),
|
PurgeSettingsRepo: persistence.NewPurgeSettingsRepository(db),
|
||||||
AuditRepo: persistence.NewAuditEventRepository(db),
|
AuditRepo: persistence.NewAuditEventRepository(db),
|
||||||
AuditSettingsRepo: persistence.NewAuditSettingsRepository(db),
|
AuditSettingsRepo: persistence.NewAuditSettingsRepository(db),
|
||||||
@@ -313,7 +338,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)
|
||||||
@@ -325,7 +350,8 @@ 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),
|
RetentionScheduler: scheduler.NewSystemRetentionRunner(useCases.NewEnforceRetentionUseCase(repos.UserRepo, repos.InviteRepo, repos.SessionRepo), log.Default()),
|
||||||
|
Token: authtoken.New([]byte(settings.JWTSecret), authtoken.WithRevocationStore(useCases.NewSessionRevocationUseCase(repos.SessionRepo, time.Now))),
|
||||||
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),
|
||||||
@@ -345,6 +371,19 @@ func getUseCases(repos *Repositories, imageStorage domainImage.Storage, settings
|
|||||||
UpdateSiteUseCase: useCases.NewUpdateSiteUseCase(repos.SiteRepo, repos.ImageRepo, recorder),
|
UpdateSiteUseCase: useCases.NewUpdateSiteUseCase(repos.SiteRepo, repos.ImageRepo, recorder),
|
||||||
SetDefaultSiteUseCase: useCases.NewSetDefaultSiteUseCase(repos.SiteRepo, recorder),
|
SetDefaultSiteUseCase: useCases.NewSetDefaultSiteUseCase(repos.SiteRepo, recorder),
|
||||||
DeleteSiteUseCase: useCases.NewDeleteSiteUseCase(repos.SiteRepo, recorder),
|
DeleteSiteUseCase: useCases.NewDeleteSiteUseCase(repos.SiteRepo, recorder),
|
||||||
|
CreateContentTypeUseCase: useCases.NewCreateContentTypeUseCase(repos.ContentTypeRepo, time.Now),
|
||||||
|
ListContentTypesUseCase: useCases.NewListContentTypesUseCase(repos.ContentTypeRepo),
|
||||||
|
GetContentTypeUseCase: useCases.NewGetContentTypeUseCase(repos.ContentTypeRepo),
|
||||||
|
UpdateContentTypeUseCase: useCases.NewUpdateContentTypeUseCase(repos.ContentTypeRepo, repos.EntryRepo, time.Now),
|
||||||
|
DeleteContentTypeUseCase: useCases.NewDeleteContentTypeUseCase(repos.ContentTypeRepo, repos.EntryRepo),
|
||||||
|
ListBuiltinTypesUseCase: useCases.NewListBuiltinTypesUseCase(),
|
||||||
|
GetBuiltinTypeUseCase: useCases.NewGetBuiltinTypeUseCase(),
|
||||||
|
LookupUserNamesUseCase: useCases.NewLookupUserNamesUseCase(repos.UserRepo),
|
||||||
|
CreateEntryUseCase: useCases.NewCreateEntryUseCase(repos.ContentTypeRepo, repos.EntryRepo, repos.ImageRepo, time.Now),
|
||||||
|
GetEntryUseCase: useCases.NewGetEntryUseCase(repos.ContentTypeRepo, repos.EntryRepo, repos.ImageRepo),
|
||||||
|
ListEntriesUseCase: useCases.NewListEntriesUseCase(repos.ContentTypeRepo, repos.EntryRepo, repos.ImageRepo),
|
||||||
|
UpdateEntryUseCase: useCases.NewUpdateEntryUseCase(repos.ContentTypeRepo, repos.EntryRepo, repos.ImageRepo, time.Now),
|
||||||
|
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),
|
||||||
AuthenticateUserUseCase: useCases.NewAuthenticateUserUseCase(repos.UserRepo, hasher, recorder),
|
AuthenticateUserUseCase: useCases.NewAuthenticateUserUseCase(repos.UserRepo, hasher, recorder),
|
||||||
@@ -361,16 +400,16 @@ func getUseCases(repos *Repositories, imageStorage domainImage.Storage, settings
|
|||||||
GetInviteUseCase: useCases.NewGetInviteUseCase(repos.InviteRepo, hasher),
|
GetInviteUseCase: useCases.NewGetInviteUseCase(repos.InviteRepo, hasher),
|
||||||
AcceptInviteUseCase: useCases.NewAcceptInviteUseCase(repos.UserRepo, repos.InviteRepo, hasher, recorder),
|
AcceptInviteUseCase: useCases.NewAcceptInviteUseCase(repos.UserRepo, repos.InviteRepo, hasher, recorder),
|
||||||
SendMailUseCase: useCases.NewSendMailUseCase(repos.MailRepo),
|
SendMailUseCase: useCases.NewSendMailUseCase(repos.MailRepo),
|
||||||
CreateImageUseCase: useCases.NewCreateImageUseCase(repos.ImageRepo, imageStorage, recorder),
|
CreateImageUseCase: useCases.NewCreateImageUseCase(repos.ImageRepo, imageStorage, recorder, imaging.NewMetadataStripper()),
|
||||||
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),
|
||||||
|
|||||||
@@ -506,6 +506,11 @@ func isVerifiedCaller(r *http.Request, getUser *useCases.GetUserUseCase) bool {
|
|||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
|
tokenVersion, ok := claims.TokenVersion(r)
|
||||||
|
if !ok || tokenVersion != currentUser.TokenVersion {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
return currentUser.IsVerified
|
return currentUser.IsVerified
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -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,
|
||||||
@@ -96,6 +95,8 @@ func writeAcceptInviteError(w http.ResponseWriter, err error) {
|
|||||||
http.Error(w, apperr.UsernameTakenErrorMessage, http.StatusConflict)
|
http.Error(w, apperr.UsernameTakenErrorMessage, http.StatusConflict)
|
||||||
case errors.Is(err, invite.ErrEmailHasAccount):
|
case errors.Is(err, invite.ErrEmailHasAccount):
|
||||||
http.Error(w, apperr.EmailHasAccountErrorMessage, http.StatusConflict)
|
http.Error(w, apperr.EmailHasAccountErrorMessage, http.StatusConflict)
|
||||||
|
case errors.Is(err, user.ErrPasswordTooLong):
|
||||||
|
http.Error(w, apperr.PasswordTooLongErrorMessage, http.StatusBadRequest)
|
||||||
default:
|
default:
|
||||||
http.Error(w, "Internal server error", http.StatusInternalServerError)
|
http.Error(w, "Internal server error", http.StatusInternalServerError)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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,
|
||||||
@@ -42,27 +41,29 @@ func NewLoginHandler(token *jwtauth.JWTAuth, create *useCases.CreateUserUseCase,
|
|||||||
|
|
||||||
func removeJwtCookie(w http.ResponseWriter, isProduction bool) {
|
func removeJwtCookie(w http.ResponseWriter, isProduction bool) {
|
||||||
http.SetCookie(w, &http.Cookie{
|
http.SetCookie(w, &http.Cookie{
|
||||||
Name: "jwt",
|
Name: authtoken.CookieName,
|
||||||
Value: "",
|
Value: "",
|
||||||
Expires: time.Now(),
|
Expires: time.Now(),
|
||||||
MaxAge: -1,
|
MaxAge: -1,
|
||||||
Secure: isProduction,
|
Secure: isProduction,
|
||||||
HttpOnly: true,
|
HttpOnly: true,
|
||||||
|
SameSite: http.SameSiteLaxMode,
|
||||||
Path: "/",
|
Path: "/",
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
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: authtoken.CookieName,
|
||||||
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,
|
||||||
|
SameSite: http.SameSiteLaxMode,
|
||||||
Path: "/",
|
Path: "/",
|
||||||
})
|
})
|
||||||
return nil
|
return nil
|
||||||
@@ -123,6 +124,10 @@ func (h *LoginHandler) Register(w http.ResponseWriter, r *http.Request) {
|
|||||||
http.Error(w, apperr.RegistrationClosedErrorMessage, http.StatusForbidden)
|
http.Error(w, apperr.RegistrationClosedErrorMessage, http.StatusForbidden)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
if errors.Is(err, user.ErrPasswordTooLong) {
|
||||||
|
http.Error(w, apperr.PasswordTooLongErrorMessage, http.StatusBadRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
http.Error(w, apperr.RegistrationFailedErrorMessage, http.StatusInternalServerError)
|
http.Error(w, apperr.RegistrationFailedErrorMessage, http.StatusInternalServerError)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -140,8 +145,14 @@ func (h *LoginHandler) RegistrationStatus(w http.ResponseWriter, _ *http.Request
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (h *LoginHandler) Logout(w http.ResponseWriter, r *http.Request) {
|
func (h *LoginHandler) Logout(w http.ResponseWriter, r *http.Request) {
|
||||||
h.AuthenticateUseCase.Logout(r.Context())
|
|
||||||
removeJwtCookie(w, h.IsProduction)
|
removeJwtCookie(w, h.IsProduction)
|
||||||
|
if claims, err := authtoken.FromContext(r.Context()); err == nil {
|
||||||
|
if err := h.Token.Revoke(claims); err != nil {
|
||||||
|
http.Error(w, "Internal server error", http.StatusInternalServerError)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
h.AuthenticateUseCase.Logout(r.Context())
|
||||||
message, _ := json.Marshal(map[string]any{"message": "User logged out! HTTPonly jwt cookie deleted"})
|
message, _ := json.Marshal(map[string]any{"message": "User logged out! HTTPonly jwt cookie deleted"})
|
||||||
_, _ = w.Write(message)
|
_, _ = w.Write(message)
|
||||||
}
|
}
|
||||||
@@ -72,6 +72,10 @@ func (h *PasswordResetHandler) ResetPassword(w http.ResponseWriter, r *http.Requ
|
|||||||
http.Error(w, apperr.PasswordResetFailedErrorMessage, http.StatusForbidden)
|
http.Error(w, apperr.PasswordResetFailedErrorMessage, http.StatusForbidden)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
if errors.Is(err, user.ErrPasswordTooLong) {
|
||||||
|
http.Error(w, apperr.PasswordTooLongErrorMessage, http.StatusBadRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
http.Error(w, "Internal server error", http.StatusInternalServerError)
|
http.Error(w, "Internal server error", http.StatusInternalServerError)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,38 @@
|
|||||||
|
package builtintype
|
||||||
|
|
||||||
|
import (
|
||||||
|
"RenewCMS/api/pkg/apperr"
|
||||||
|
"RenewCMS/api/pkg/response"
|
||||||
|
domain "RenewCMS/internal/domain/builtintype"
|
||||||
|
"RenewCMS/internal/infrastructure/useCases"
|
||||||
|
"errors"
|
||||||
|
"net/http"
|
||||||
|
|
||||||
|
"github.com/go-chi/chi/v5"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Handler struct {
|
||||||
|
ListUseCase *useCases.ListBuiltinTypesUseCase
|
||||||
|
GetUseCase *useCases.GetBuiltinTypeUseCase
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewHandler(list *useCases.ListBuiltinTypesUseCase, get *useCases.GetBuiltinTypeUseCase) *Handler {
|
||||||
|
return &Handler{ListUseCase: list, GetUseCase: get}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *Handler) List(w http.ResponseWriter, r *http.Request) {
|
||||||
|
response.WriteJSON(w, http.StatusOK, h.ListUseCase.List())
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *Handler) Get(w http.ResponseWriter, r *http.Request) {
|
||||||
|
found, err := h.GetUseCase.Get(chi.URLParam(r, "key"))
|
||||||
|
if errors.Is(err, domain.ErrNotFound) {
|
||||||
|
http.Error(w, apperr.BuiltinTypeNotFoundErrorMessage, http.StatusNotFound)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
http.Error(w, "Internal server error", http.StatusInternalServerError)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
response.WriteJSON(w, http.StatusOK, found)
|
||||||
|
}
|
||||||
@@ -0,0 +1,182 @@
|
|||||||
|
package contenttype
|
||||||
|
|
||||||
|
import (
|
||||||
|
"RenewCMS/api/pkg/apperr"
|
||||||
|
"RenewCMS/api/pkg/response"
|
||||||
|
validator "RenewCMS/api/pkg/validator"
|
||||||
|
domain "RenewCMS/internal/domain/contenttype"
|
||||||
|
"RenewCMS/internal/infrastructure/useCases"
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"net/http"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/go-chi/chi/v5"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Handler struct {
|
||||||
|
CreateUseCase *useCases.CreateContentTypeUseCase
|
||||||
|
ListUseCase *useCases.ListContentTypesUseCase
|
||||||
|
GetUseCase *useCases.GetContentTypeUseCase
|
||||||
|
UpdateUseCase *useCases.UpdateContentTypeUseCase
|
||||||
|
DeleteUseCase *useCases.DeleteContentTypeUseCase
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewHandler(create *useCases.CreateContentTypeUseCase, list *useCases.ListContentTypesUseCase, get *useCases.GetContentTypeUseCase, update *useCases.UpdateContentTypeUseCase, deleteUseCase *useCases.DeleteContentTypeUseCase) *Handler {
|
||||||
|
return &Handler{CreateUseCase: create, ListUseCase: list, GetUseCase: get, UpdateUseCase: update, DeleteUseCase: deleteUseCase}
|
||||||
|
}
|
||||||
|
|
||||||
|
type iconInput struct {
|
||||||
|
value *string
|
||||||
|
invalid bool
|
||||||
|
}
|
||||||
|
|
||||||
|
func (i *iconInput) UnmarshalJSON(data []byte) error {
|
||||||
|
if string(data) == "null" {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
var text string
|
||||||
|
if err := json.Unmarshal(data, &text); err != nil {
|
||||||
|
i.invalid = true
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
i.value = &text
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
type PostContentType struct {
|
||||||
|
Key string `json:"key" validate:"required"`
|
||||||
|
Name string `json:"name" validate:"required,max=100"`
|
||||||
|
Icon iconInput `json:"icon"`
|
||||||
|
Fields []domain.Field `json:"fields"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type PutContentType struct {
|
||||||
|
Key string `json:"key"`
|
||||||
|
Name string `json:"name" validate:"required,max=100"`
|
||||||
|
Icon iconInput `json:"icon"`
|
||||||
|
Fields []domain.Field `json:"fields"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type contentTypeResponse struct {
|
||||||
|
ID uint32 `json:"id"`
|
||||||
|
Key string `json:"key"`
|
||||||
|
Name string `json:"name"`
|
||||||
|
Icon *string `json:"icon"`
|
||||||
|
Fields []domain.Field `json:"fields"`
|
||||||
|
CreatedAt time.Time `json:"created_at"`
|
||||||
|
UpdatedAt time.Time `json:"updated_at"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func toResponse(contentType domain.ContentType) contentTypeResponse {
|
||||||
|
fields := contentType.Fields
|
||||||
|
if fields == nil {
|
||||||
|
fields = []domain.Field{}
|
||||||
|
}
|
||||||
|
return contentTypeResponse{
|
||||||
|
ID: contentType.ID,
|
||||||
|
Key: contentType.Key,
|
||||||
|
Name: contentType.Name,
|
||||||
|
Icon: contentType.Icon,
|
||||||
|
Fields: fields,
|
||||||
|
CreatedAt: contentType.CreatedAt,
|
||||||
|
UpdatedAt: contentType.UpdatedAt,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func writeContentTypeError(w http.ResponseWriter, err error) {
|
||||||
|
switch {
|
||||||
|
case errors.Is(err, domain.ErrContentTypeNotFound):
|
||||||
|
http.Error(w, apperr.ContentTypeNotFoundErrorMessage, http.StatusNotFound)
|
||||||
|
case errors.Is(err, domain.ErrKeyTaken):
|
||||||
|
http.Error(w, apperr.ContentTypeKeyTakenErrorMessage, http.StatusConflict)
|
||||||
|
case errors.Is(err, domain.ErrHasEntries):
|
||||||
|
http.Error(w, apperr.ContentTypeHasEntriesErrorMessage, http.StatusConflict)
|
||||||
|
case errors.Is(err, domain.ErrSchemaIncompatible):
|
||||||
|
http.Error(w, apperr.SchemaIncompatibleErrorMessage, http.StatusConflict)
|
||||||
|
case errors.Is(err, domain.ErrInvalidName):
|
||||||
|
http.Error(w, apperr.BodyErrorMessage, http.StatusBadRequest)
|
||||||
|
case errors.Is(err, domain.ErrInvalidIcon):
|
||||||
|
http.Error(w, apperr.InvalidIconErrorMessage, http.StatusBadRequest)
|
||||||
|
case errors.Is(err, domain.ErrInvalidKey):
|
||||||
|
http.Error(w, apperr.InvalidContentTypeKeyErrorMessage, http.StatusBadRequest)
|
||||||
|
case errors.Is(err, domain.ErrInvalidField):
|
||||||
|
http.Error(w, apperr.InvalidFieldErrorMessage, http.StatusUnprocessableEntity)
|
||||||
|
default:
|
||||||
|
http.Error(w, "Internal server error", http.StatusInternalServerError)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *Handler) List(w http.ResponseWriter, r *http.Request) {
|
||||||
|
found, err := h.ListUseCase.List()
|
||||||
|
if err != nil {
|
||||||
|
writeContentTypeError(w, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
responses := make([]contentTypeResponse, 0, len(found))
|
||||||
|
for _, contentType := range found {
|
||||||
|
responses = append(responses, toResponse(contentType))
|
||||||
|
}
|
||||||
|
response.WriteJSON(w, http.StatusOK, responses)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *Handler) Get(w http.ResponseWriter, r *http.Request) {
|
||||||
|
found, err := h.GetUseCase.Get(chi.URLParam(r, "key"))
|
||||||
|
if err != nil {
|
||||||
|
writeContentTypeError(w, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
response.WriteJSON(w, http.StatusOK, toResponse(found))
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *Handler) Create(w http.ResponseWriter, r *http.Request) {
|
||||||
|
var request PostContentType
|
||||||
|
if err := json.NewDecoder(r.Body).Decode(&request); err != nil {
|
||||||
|
http.Error(w, apperr.BodyErrorMessage, http.StatusBadRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if err := validator.Validate.Struct(request); err != nil {
|
||||||
|
http.Error(w, err.Error(), http.StatusBadRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if request.Icon.invalid {
|
||||||
|
writeContentTypeError(w, domain.ErrInvalidIcon)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
created, err := h.CreateUseCase.Create(useCases.CreateContentTypeCommand{Key: request.Key, Name: request.Name, Icon: request.Icon.value, Fields: request.Fields})
|
||||||
|
if err != nil {
|
||||||
|
writeContentTypeError(w, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
response.WriteJSON(w, http.StatusCreated, toResponse(created))
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *Handler) Update(w http.ResponseWriter, r *http.Request) {
|
||||||
|
var request PutContentType
|
||||||
|
if err := json.NewDecoder(r.Body).Decode(&request); err != nil {
|
||||||
|
http.Error(w, apperr.BodyErrorMessage, http.StatusBadRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if err := validator.Validate.Struct(request); err != nil {
|
||||||
|
http.Error(w, err.Error(), http.StatusBadRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if request.Icon.invalid {
|
||||||
|
writeContentTypeError(w, domain.ErrInvalidIcon)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
updated, err := h.UpdateUseCase.Update(useCases.UpdateContentTypeCommand{Key: chi.URLParam(r, "key"), Name: request.Name, Icon: request.Icon.value, Fields: request.Fields})
|
||||||
|
if err != nil {
|
||||||
|
writeContentTypeError(w, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
response.WriteJSON(w, http.StatusOK, toResponse(updated))
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *Handler) Delete(w http.ResponseWriter, r *http.Request) {
|
||||||
|
if err := h.DeleteUseCase.Delete(chi.URLParam(r, "key")); err != nil {
|
||||||
|
writeContentTypeError(w, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
w.WriteHeader(http.StatusNoContent)
|
||||||
|
}
|
||||||
@@ -0,0 +1,260 @@
|
|||||||
|
package entry
|
||||||
|
|
||||||
|
import (
|
||||||
|
"RenewCMS/api/pkg/apperr"
|
||||||
|
"RenewCMS/api/pkg/claims"
|
||||||
|
"RenewCMS/api/pkg/response"
|
||||||
|
validator "RenewCMS/api/pkg/validator"
|
||||||
|
"RenewCMS/internal/domain/contenttype"
|
||||||
|
domain "RenewCMS/internal/domain/entry"
|
||||||
|
"RenewCMS/internal/infrastructure/useCases"
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"net/http"
|
||||||
|
"net/url"
|
||||||
|
"strconv"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/go-chi/chi/v5"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Handler struct {
|
||||||
|
CreateUseCase *useCases.CreateEntryUseCase
|
||||||
|
GetUseCase *useCases.GetEntryUseCase
|
||||||
|
ListUseCase *useCases.ListEntriesUseCase
|
||||||
|
UpdateUseCase *useCases.UpdateEntryUseCase
|
||||||
|
DeleteUseCase *useCases.DeleteEntryUseCase
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewHandler(create *useCases.CreateEntryUseCase, get *useCases.GetEntryUseCase, list *useCases.ListEntriesUseCase, update *useCases.UpdateEntryUseCase, deleteUseCase *useCases.DeleteEntryUseCase) *Handler {
|
||||||
|
return &Handler{CreateUseCase: create, GetUseCase: get, ListUseCase: list, UpdateUseCase: update, DeleteUseCase: deleteUseCase}
|
||||||
|
}
|
||||||
|
|
||||||
|
type EntryBody struct {
|
||||||
|
Data map[string]any `json:"data" validate:"required"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type entryResponse struct {
|
||||||
|
ID uint32 `json:"id"`
|
||||||
|
ContentType string `json:"content_type"`
|
||||||
|
Data map[string]any `json:"data"`
|
||||||
|
CreatedBy uint32 `json:"created_by"`
|
||||||
|
UpdatedBy uint32 `json:"updated_by"`
|
||||||
|
CreatedAt time.Time `json:"created_at"`
|
||||||
|
UpdatedAt time.Time `json:"updated_at"`
|
||||||
|
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 {
|
||||||
|
return entryResponse{
|
||||||
|
ID: typed.ID,
|
||||||
|
ContentType: typed.ContentTypeKey,
|
||||||
|
Data: typed.Data,
|
||||||
|
CreatedBy: typed.CreatedBy,
|
||||||
|
UpdatedBy: typed.UpdatedBy,
|
||||||
|
CreatedAt: typed.CreatedAt,
|
||||||
|
UpdatedAt: typed.UpdatedAt,
|
||||||
|
Media: toMediaResponse(typed.Media),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type pageResponse struct {
|
||||||
|
Items []entryResponse `json:"items"`
|
||||||
|
Total int `json:"total"`
|
||||||
|
Page int `json:"page"`
|
||||||
|
Size int `json:"size"`
|
||||||
|
}
|
||||||
|
|
||||||
|
const (
|
||||||
|
defaultListPage = 1
|
||||||
|
defaultListSize = 25
|
||||||
|
)
|
||||||
|
|
||||||
|
type listQuery struct {
|
||||||
|
Page int `validate:"gte=1"`
|
||||||
|
Size int `validate:"oneof=5 25 50 100"`
|
||||||
|
Sort domain.Sort
|
||||||
|
}
|
||||||
|
|
||||||
|
func intQueryParam(values url.Values, name string, fallback int) (int, error) {
|
||||||
|
if !values.Has(name) {
|
||||||
|
return fallback, nil
|
||||||
|
}
|
||||||
|
return strconv.Atoi(values.Get(name))
|
||||||
|
}
|
||||||
|
|
||||||
|
func readListQuery(values url.Values) (listQuery, error) {
|
||||||
|
page, err := intQueryParam(values, "page", defaultListPage)
|
||||||
|
if err != nil {
|
||||||
|
return listQuery{}, err
|
||||||
|
}
|
||||||
|
size, err := intQueryParam(values, "size", defaultListSize)
|
||||||
|
if err != nil {
|
||||||
|
return listQuery{}, err
|
||||||
|
}
|
||||||
|
order := domain.DefaultSort()
|
||||||
|
if values.Has("sort") {
|
||||||
|
order, err = domain.ParseSort(values.Get("sort"))
|
||||||
|
if err != nil {
|
||||||
|
return listQuery{}, err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return listQuery{Page: page, Size: size, Sort: order}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func parseEntryId(r *http.Request) (uint32, error) {
|
||||||
|
id, err := strconv.ParseUint(chi.URLParam(r, "id"), 10, 32)
|
||||||
|
return uint32(id), err
|
||||||
|
}
|
||||||
|
|
||||||
|
func writeEntryError(w http.ResponseWriter, err error) {
|
||||||
|
var fieldError domain.FieldError
|
||||||
|
switch {
|
||||||
|
case errors.Is(err, contenttype.ErrContentTypeNotFound):
|
||||||
|
http.Error(w, apperr.ContentTypeNotFoundErrorMessage, http.StatusNotFound)
|
||||||
|
case errors.Is(err, domain.ErrEntryNotFound):
|
||||||
|
http.Error(w, apperr.EntryNotFoundErrorMessage, http.StatusNotFound)
|
||||||
|
case errors.As(err, &fieldError):
|
||||||
|
http.Error(w, apperr.InvalidEntryErrorMessage+": "+fieldError.Error(), fieldErrorStatus(err))
|
||||||
|
case errors.Is(err, domain.ErrInvalidPage), errors.Is(err, domain.ErrInvalidSort):
|
||||||
|
http.Error(w, apperr.BodyErrorMessage, http.StatusBadRequest)
|
||||||
|
case errors.Is(err, domain.ErrInvalidEntry):
|
||||||
|
http.Error(w, apperr.InvalidEntryErrorMessage, http.StatusUnprocessableEntity)
|
||||||
|
default:
|
||||||
|
http.Error(w, "Internal server error", http.StatusInternalServerError)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func fieldErrorStatus(err error) int {
|
||||||
|
if errors.Is(err, domain.ErrUniqueViolation) {
|
||||||
|
return http.StatusConflict
|
||||||
|
}
|
||||||
|
return http.StatusUnprocessableEntity
|
||||||
|
}
|
||||||
|
|
||||||
|
func readBody(w http.ResponseWriter, r *http.Request) (EntryBody, bool) {
|
||||||
|
var body EntryBody
|
||||||
|
if err := json.NewDecoder(r.Body).Decode(&body); err != nil || validator.Validate.Struct(body) != nil {
|
||||||
|
http.Error(w, apperr.BodyErrorMessage, http.StatusBadRequest)
|
||||||
|
return EntryBody{}, false
|
||||||
|
}
|
||||||
|
return body, true
|
||||||
|
}
|
||||||
|
|
||||||
|
func currentUserId(w http.ResponseWriter, r *http.Request) (uint32, bool) {
|
||||||
|
userId, ok := claims.UserId(r)
|
||||||
|
if !ok {
|
||||||
|
http.Error(w, apperr.UnauthorizedErrorMessage, http.StatusUnauthorized)
|
||||||
|
}
|
||||||
|
return userId, ok
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *Handler) List(w http.ResponseWriter, r *http.Request) {
|
||||||
|
query, err := readListQuery(r.URL.Query())
|
||||||
|
if err != nil || validator.Validate.Struct(query) != nil {
|
||||||
|
http.Error(w, apperr.BodyErrorMessage, http.StatusBadRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
page, err := h.ListUseCase.ListPage(useCases.ListEntriesCommand{ContentTypeKey: chi.URLParam(r, "key"), Page: query.Page, Size: query.Size, Sort: query.Sort})
|
||||||
|
if err != nil {
|
||||||
|
writeEntryError(w, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
items := make([]entryResponse, 0, len(page.Items))
|
||||||
|
for _, typed := range page.Items {
|
||||||
|
items = append(items, toResponse(typed))
|
||||||
|
}
|
||||||
|
response.WriteJSON(w, http.StatusOK, pageResponse{Items: items, Total: page.Total, Page: page.Page, Size: page.Size})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *Handler) Get(w http.ResponseWriter, r *http.Request) {
|
||||||
|
id, err := parseEntryId(r)
|
||||||
|
if err != nil {
|
||||||
|
http.Error(w, apperr.IdUint32ErrorMessage, http.StatusBadRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
found, err := h.GetUseCase.Get(chi.URLParam(r, "key"), id)
|
||||||
|
if err != nil {
|
||||||
|
writeEntryError(w, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
response.WriteJSON(w, http.StatusOK, toResponse(found))
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *Handler) Create(w http.ResponseWriter, r *http.Request) {
|
||||||
|
userId, ok := currentUserId(w, r)
|
||||||
|
if !ok {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
body, ok := readBody(w, r)
|
||||||
|
if !ok {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
created, err := h.CreateUseCase.Create(useCases.CreateEntryCommand{ContentTypeKey: chi.URLParam(r, "key"), Data: body.Data, UserID: userId})
|
||||||
|
if err != nil {
|
||||||
|
writeEntryError(w, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
response.WriteJSON(w, http.StatusCreated, toResponse(created))
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *Handler) Update(w http.ResponseWriter, r *http.Request) {
|
||||||
|
id, err := parseEntryId(r)
|
||||||
|
if err != nil {
|
||||||
|
http.Error(w, apperr.IdUint32ErrorMessage, http.StatusBadRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
userId, ok := currentUserId(w, r)
|
||||||
|
if !ok {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
body, ok := readBody(w, r)
|
||||||
|
if !ok {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
updated, err := h.UpdateUseCase.Update(useCases.UpdateEntryCommand{ContentTypeKey: chi.URLParam(r, "key"), ID: id, Data: body.Data, UserID: userId})
|
||||||
|
if err != nil {
|
||||||
|
writeEntryError(w, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
response.WriteJSON(w, http.StatusOK, toResponse(updated))
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *Handler) Delete(w http.ResponseWriter, r *http.Request) {
|
||||||
|
id, err := parseEntryId(r)
|
||||||
|
if err != nil {
|
||||||
|
http.Error(w, apperr.IdUint32ErrorMessage, http.StatusBadRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if err := h.DeleteUseCase.Delete(chi.URLParam(r, "key"), id); err != nil {
|
||||||
|
writeEntryError(w, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
w.WriteHeader(http.StatusNoContent)
|
||||||
|
}
|
||||||
@@ -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)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,66 @@
|
|||||||
|
package user
|
||||||
|
|
||||||
|
import (
|
||||||
|
"RenewCMS/api/pkg/apperr"
|
||||||
|
"RenewCMS/api/pkg/response"
|
||||||
|
domainUser "RenewCMS/internal/domain/user"
|
||||||
|
"RenewCMS/internal/infrastructure/useCases"
|
||||||
|
"errors"
|
||||||
|
"net/http"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
)
|
||||||
|
|
||||||
|
type LookupHandler struct {
|
||||||
|
LookupUseCase *useCases.LookupUserNamesUseCase
|
||||||
|
}
|
||||||
|
|
||||||
|
type userNameResponse struct {
|
||||||
|
ID uint32 `json:"id"`
|
||||||
|
DisplayName string `json:"display_name"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewLookupHandler(lookup *useCases.LookupUserNamesUseCase) *LookupHandler {
|
||||||
|
return &LookupHandler{LookupUseCase: lookup}
|
||||||
|
}
|
||||||
|
|
||||||
|
func parseLookupIDs(raw string) ([]uint32, bool) {
|
||||||
|
if raw == "" {
|
||||||
|
return nil, false
|
||||||
|
}
|
||||||
|
if strings.Count(raw, ",")+1 > domainUser.MaxLookupIDs {
|
||||||
|
return nil, false
|
||||||
|
}
|
||||||
|
parts := strings.Split(raw, ",")
|
||||||
|
ids := make([]uint32, 0, len(parts))
|
||||||
|
for _, part := range parts {
|
||||||
|
id, err := strconv.ParseUint(part, 10, 32)
|
||||||
|
if err != nil {
|
||||||
|
return nil, false
|
||||||
|
}
|
||||||
|
ids = append(ids, uint32(id))
|
||||||
|
}
|
||||||
|
return ids, true
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *LookupHandler) Lookup(w http.ResponseWriter, r *http.Request) {
|
||||||
|
ids, ok := parseLookupIDs(r.URL.Query().Get("ids"))
|
||||||
|
if !ok {
|
||||||
|
http.Error(w, apperr.BodyErrorMessage, http.StatusBadRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
names, err := h.LookupUseCase.Lookup(ids)
|
||||||
|
if errors.Is(err, domainUser.ErrInvalidLookup) {
|
||||||
|
http.Error(w, apperr.BodyErrorMessage, http.StatusBadRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
http.Error(w, "Internal server error", http.StatusInternalServerError)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
items := make([]userNameResponse, 0, len(names))
|
||||||
|
for _, name := range names {
|
||||||
|
items = append(items, userNameResponse{ID: name.ID, DisplayName: name.DisplayName})
|
||||||
|
}
|
||||||
|
response.WriteJSON(w, http.StatusOK, items)
|
||||||
|
}
|
||||||
@@ -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 {
|
||||||
|
|||||||
@@ -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)
|
||||||
|
}
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
package middleware
|
||||||
|
|
||||||
|
import (
|
||||||
|
"RenewCMS/api/pkg/apperr"
|
||||||
|
"net/http"
|
||||||
|
"net/url"
|
||||||
|
)
|
||||||
|
|
||||||
|
func CrossOriginProtection(publicURL string) func(http.Handler) http.Handler {
|
||||||
|
protection := http.NewCrossOriginProtection()
|
||||||
|
if origin, ok := originOf(publicURL); ok {
|
||||||
|
_ = protection.AddTrustedOrigin(origin)
|
||||||
|
}
|
||||||
|
protection.SetDenyHandler(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||||
|
http.Error(w, apperr.CrossOriginErrorMessage, http.StatusForbidden)
|
||||||
|
}))
|
||||||
|
|
||||||
|
return func(next http.Handler) http.Handler {
|
||||||
|
protected := protection.Handler(next)
|
||||||
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
if r.Header.Get("Authorization") != "" {
|
||||||
|
next.ServeHTTP(w, r)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
protected.ServeHTTP(w, r)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func originOf(rawURL string) (string, bool) {
|
||||||
|
parsed, err := url.Parse(rawURL)
|
||||||
|
if err != nil || parsed.Scheme == "" || parsed.Host == "" {
|
||||||
|
return "", false
|
||||||
|
}
|
||||||
|
return parsed.Scheme + "://" + parsed.Host, true
|
||||||
|
}
|
||||||
+34
-12
@@ -14,8 +14,19 @@ type rateLimitWindow struct {
|
|||||||
count int
|
count int
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type rateLimitCounters struct {
|
||||||
|
mu sync.Mutex
|
||||||
|
window time.Duration
|
||||||
|
windows map[string]*rateLimitWindow
|
||||||
|
lastSweep time.Time
|
||||||
|
}
|
||||||
|
|
||||||
func NewRateLimiter(maxAttempts int, window time.Duration) func(http.Handler) http.Handler {
|
func NewRateLimiter(maxAttempts int, window time.Duration) func(http.Handler) http.Handler {
|
||||||
return newKeyedRateLimiter(maxAttempts, window, func(r *http.Request) string { return r.RemoteAddr })
|
return newKeyedRateLimiter(maxAttempts, window, connectionHostKey)
|
||||||
|
}
|
||||||
|
|
||||||
|
func connectionHostKey(r *http.Request) string {
|
||||||
|
return hostOf(r.RemoteAddr)
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewUserRateLimiter(maxAttempts int, window time.Duration) func(http.Handler) http.Handler {
|
func NewUserRateLimiter(maxAttempts int, window time.Duration) func(http.Handler) http.Handler {
|
||||||
@@ -28,12 +39,11 @@ func userRateLimitKey(r *http.Request) string {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func newKeyedRateLimiter(maxAttempts int, window time.Duration, keyOf func(*http.Request) string) func(http.Handler) http.Handler {
|
func newKeyedRateLimiter(maxAttempts int, window time.Duration, keyOf func(*http.Request) string) func(http.Handler) http.Handler {
|
||||||
var mu sync.Mutex
|
counters := &rateLimitCounters{window: window, windows: make(map[string]*rateLimitWindow)}
|
||||||
windows := make(map[string]*rateLimitWindow)
|
|
||||||
|
|
||||||
return func(next http.Handler) http.Handler {
|
return func(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) {
|
||||||
retryAfter, allowed := recordAttempt(&mu, windows, keyOf(r), maxAttempts, window)
|
retryAfter, allowed := counters.recordAttempt(keyOf(r), maxAttempts, time.Now())
|
||||||
if !allowed {
|
if !allowed {
|
||||||
w.Header().Set("Retry-After", strconv.Itoa(retryAfter))
|
w.Header().Set("Retry-After", strconv.Itoa(retryAfter))
|
||||||
http.Error(w, apperr.TooManyRequestsErrorMessage, http.StatusTooManyRequests)
|
http.Error(w, apperr.TooManyRequestsErrorMessage, http.StatusTooManyRequests)
|
||||||
@@ -44,24 +54,36 @@ func newKeyedRateLimiter(maxAttempts int, window time.Duration, keyOf func(*http
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func recordAttempt(mu *sync.Mutex, windows map[string]*rateLimitWindow, key string, maxAttempts int, window time.Duration) (int, bool) {
|
func (c *rateLimitCounters) recordAttempt(key string, maxAttempts int, now time.Time) (int, bool) {
|
||||||
mu.Lock()
|
c.mu.Lock()
|
||||||
defer mu.Unlock()
|
defer c.mu.Unlock()
|
||||||
|
|
||||||
now := time.Now()
|
c.sweepExpired(now)
|
||||||
current, exists := windows[key]
|
current, exists := c.windows[key]
|
||||||
if !exists || now.Sub(current.start) >= window {
|
if !exists || now.Sub(current.start) >= c.window {
|
||||||
current = &rateLimitWindow{start: now}
|
current = &rateLimitWindow{start: now}
|
||||||
windows[key] = current
|
c.windows[key] = current
|
||||||
}
|
}
|
||||||
|
|
||||||
current.count++
|
current.count++
|
||||||
if current.count > maxAttempts {
|
if current.count > maxAttempts {
|
||||||
return retryAfterSeconds(window - now.Sub(current.start)), false
|
return retryAfterSeconds(c.window - now.Sub(current.start)), false
|
||||||
}
|
}
|
||||||
return 0, true
|
return 0, true
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (c *rateLimitCounters) sweepExpired(now time.Time) {
|
||||||
|
if now.Sub(c.lastSweep) < c.window {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.lastSweep = now
|
||||||
|
for key, current := range c.windows {
|
||||||
|
if now.Sub(current.start) >= c.window {
|
||||||
|
delete(c.windows, key)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func retryAfterSeconds(remaining time.Duration) int {
|
func retryAfterSeconds(remaining time.Duration) int {
|
||||||
seconds := int(remaining / time.Second)
|
seconds := int(remaining / time.Second)
|
||||||
if remaining%time.Second > 0 {
|
if remaining%time.Second > 0 {
|
||||||
|
|||||||
@@ -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
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,8 +4,8 @@ import "net/http"
|
|||||||
|
|
||||||
const contentSecurityPolicy = "default-src 'self'; " +
|
const contentSecurityPolicy = "default-src 'self'; " +
|
||||||
"script-src 'self' 'wasm-unsafe-eval'; " +
|
"script-src 'self' 'wasm-unsafe-eval'; " +
|
||||||
"style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; " +
|
"style-src 'self' 'unsafe-inline'; " +
|
||||||
"font-src 'self' https://fonts.gstatic.com; " +
|
"font-src 'self'; " +
|
||||||
"img-src 'self' data: blob: https:; " +
|
"img-src 'self' data: blob: https:; " +
|
||||||
"connect-src 'self'; " +
|
"connect-src 'self'; " +
|
||||||
"object-src 'none'; " +
|
"object-src 'none'; " +
|
||||||
|
|||||||
@@ -16,6 +16,7 @@ const VerificationRequiredErrorMessage = "You must verify your account to access
|
|||||||
const PasswordResetRequestedMessage = "If an account exists for that email, a password reset link has been sent."
|
const PasswordResetRequestedMessage = "If an account exists for that email, a password reset link has been sent."
|
||||||
const PasswordResetFailedErrorMessage = "The password reset code is invalid or has expired."
|
const PasswordResetFailedErrorMessage = "The password reset code is invalid or has expired."
|
||||||
const TooManyRequestsErrorMessage = "Too many requests. Please try again later."
|
const TooManyRequestsErrorMessage = "Too many requests. Please try again later."
|
||||||
|
const CrossOriginErrorMessage = "Cross-origin requests are not allowed."
|
||||||
const EmailHasAccountErrorMessage = "This address already has an account."
|
const EmailHasAccountErrorMessage = "This address already has an account."
|
||||||
const PendingInviteErrorMessage = "There's already a pending invite for this address."
|
const PendingInviteErrorMessage = "There's already a pending invite for this address."
|
||||||
const InviteNotSentErrorMessage = "Couldn't send the invite. Try again in a moment."
|
const InviteNotSentErrorMessage = "Couldn't send the invite. Try again in a moment."
|
||||||
@@ -25,6 +26,7 @@ const InviteInvalidErrorMessage = "This invite link doesn't work."
|
|||||||
const InviteExpiredErrorMessage = "This invite has expired."
|
const InviteExpiredErrorMessage = "This invite has expired."
|
||||||
const OwnerRequiredErrorMessage = "Only the owner can do this."
|
const OwnerRequiredErrorMessage = "Only the owner can do this."
|
||||||
const UsernameTakenErrorMessage = "That username is taken. Try another."
|
const UsernameTakenErrorMessage = "That username is taken. Try another."
|
||||||
|
const PasswordTooLongErrorMessage = "The password must be 72 bytes or fewer."
|
||||||
const MediaQueryErrorMessage = "The media query is invalid."
|
const MediaQueryErrorMessage = "The media query is invalid."
|
||||||
const MediaFilenameErrorMessage = "Enter a filename."
|
const MediaFilenameErrorMessage = "Enter a filename."
|
||||||
const MediaMergeConflictErrorMessage = "Some of the images to merge changed. Refresh and try again."
|
const MediaMergeConflictErrorMessage = "Some of the images to merge changed. Refresh and try again."
|
||||||
@@ -86,3 +88,14 @@ const ArticleSlugTakenErrorMessage = "slug_taken"
|
|||||||
const ArticleImageNotFoundErrorMessage = "image_not_found"
|
const ArticleImageNotFoundErrorMessage = "image_not_found"
|
||||||
const InvalidTitleTemplateErrorMessage = "invalid_title_template"
|
const InvalidTitleTemplateErrorMessage = "invalid_title_template"
|
||||||
const SlugSuggestionHeader = "X-Slug-Suggestion"
|
const SlugSuggestionHeader = "X-Slug-Suggestion"
|
||||||
|
|
||||||
|
const ContentTypeNotFoundErrorMessage = "content_type_not_found"
|
||||||
|
const ContentTypeKeyTakenErrorMessage = "content_type_key_taken"
|
||||||
|
const ContentTypeHasEntriesErrorMessage = "content_type_has_entries"
|
||||||
|
const InvalidContentTypeKeyErrorMessage = "invalid_content_type_key"
|
||||||
|
const InvalidIconErrorMessage = "invalid_icon"
|
||||||
|
const BuiltinTypeNotFoundErrorMessage = "builtin_type_not_found"
|
||||||
|
const InvalidFieldErrorMessage = "invalid_field"
|
||||||
|
const SchemaIncompatibleErrorMessage = "schema_incompatible"
|
||||||
|
const EntryNotFoundErrorMessage = "entry_not_found"
|
||||||
|
const InvalidEntryErrorMessage = "invalid_entry"
|
||||||
@@ -0,0 +1,225 @@
|
|||||||
|
package authtoken
|
||||||
|
|
||||||
|
import (
|
||||||
|
"crypto/hmac"
|
||||||
|
"crypto/rand"
|
||||||
|
"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")
|
||||||
|
ErrRevoked = errors.New("token is revoked")
|
||||||
|
)
|
||||||
|
|
||||||
|
type RevocationStore interface {
|
||||||
|
Revoke(id string, expiresAt time.Time) error
|
||||||
|
IsRevoked(id string) (bool, error)
|
||||||
|
}
|
||||||
|
|
||||||
|
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
|
||||||
|
revocations RevocationStore
|
||||||
|
}
|
||||||
|
|
||||||
|
type Option func(*Auth)
|
||||||
|
|
||||||
|
func WithClock(clock func() time.Time) Option {
|
||||||
|
return func(a *Auth) { a.clock = clock }
|
||||||
|
}
|
||||||
|
|
||||||
|
func WithRevocationStore(store RevocationStore) Option {
|
||||||
|
return func(a *Auth) { a.revocations = store }
|
||||||
|
}
|
||||||
|
|
||||||
|
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()
|
||||||
|
}
|
||||||
|
if _, ok := payload["jti"]; !ok {
|
||||||
|
payload["jti"] = rand.Text()
|
||||||
|
}
|
||||||
|
|
||||||
|
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
|
||||||
|
}
|
||||||
|
if err := a.checkRevocation(claims); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return claims, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *Auth) Revoke(claims Claims) error {
|
||||||
|
id, ok := claims["jti"].(string)
|
||||||
|
if !ok || a.revocations == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
expiry, present, err := numericDate(claims, "exp")
|
||||||
|
if err != nil || !present {
|
||||||
|
return ErrInvalid
|
||||||
|
}
|
||||||
|
return a.revocations.Revoke(id, expiry)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *Auth) checkRevocation(claims Claims) error {
|
||||||
|
raw, present := claims["jti"]
|
||||||
|
if !present {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
id, ok := raw.(string)
|
||||||
|
if !ok {
|
||||||
|
return ErrInvalid
|
||||||
|
}
|
||||||
|
if a.revocations == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
revoked, err := a.revocations.IsRevoked(id)
|
||||||
|
if err != nil {
|
||||||
|
return errors.Join(ErrInvalid, err)
|
||||||
|
}
|
||||||
|
if revoked {
|
||||||
|
return ErrRevoked
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *Auth) validateTimes(claims Claims) error {
|
||||||
|
now := a.clock()
|
||||||
|
|
||||||
|
expiry, present, err := numericDate(claims, "exp")
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if !present {
|
||||||
|
return ErrInvalid
|
||||||
|
}
|
||||||
|
if !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)
|
||||||
|
}
|
||||||
@@ -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
|
||||||
|
}
|
||||||
@@ -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
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,21 @@
|
|||||||
|
package response
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"log"
|
||||||
|
"net/http"
|
||||||
|
)
|
||||||
|
|
||||||
|
func WriteJSON(w http.ResponseWriter, status int, payload any) {
|
||||||
|
body, err := json.Marshal(payload)
|
||||||
|
if err != nil {
|
||||||
|
http.Error(w, "Failed to encode response", http.StatusInternalServerError)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if status != http.StatusOK {
|
||||||
|
w.WriteHeader(status)
|
||||||
|
}
|
||||||
|
if _, err := w.Write(body); err != nil {
|
||||||
|
log.Printf("Failed to write response: %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
+94
-43
@@ -6,6 +6,9 @@ import (
|
|||||||
"RenewCMS/api/handlers/article"
|
"RenewCMS/api/handlers/article"
|
||||||
"RenewCMS/api/handlers/auth"
|
"RenewCMS/api/handlers/auth"
|
||||||
"RenewCMS/api/handlers/author"
|
"RenewCMS/api/handlers/author"
|
||||||
|
"RenewCMS/api/handlers/builtintype"
|
||||||
|
"RenewCMS/api/handlers/contenttype"
|
||||||
|
"RenewCMS/api/handlers/entry"
|
||||||
"RenewCMS/api/handlers/frontend"
|
"RenewCMS/api/handlers/frontend"
|
||||||
"RenewCMS/api/handlers/imagevariant"
|
"RenewCMS/api/handlers/imagevariant"
|
||||||
"RenewCMS/api/handlers/media"
|
"RenewCMS/api/handlers/media"
|
||||||
@@ -15,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),
|
||||||
|
}))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -65,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)
|
||||||
@@ -80,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)
|
||||||
@@ -111,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)
|
||||||
})
|
})
|
||||||
@@ -131,16 +136,18 @@ func NewUserRouter(container *UseCases, rateLimit config.AuthRateLimitSettings,
|
|||||||
r := chi.NewRouter()
|
r := chi.NewRouter()
|
||||||
|
|
||||||
userHandler := user.NewHandler(container.UpdateUserProfileUseCase)
|
userHandler := user.NewHandler(container.UpdateUserProfileUseCase)
|
||||||
|
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)
|
||||||
r.Get("/", inviteHandler.ListUsers)
|
r.Get("/", inviteHandler.ListUsers)
|
||||||
|
r.Get("/lookup", lookupHandler.Lookup)
|
||||||
r.Group(func(r chi.Router) {
|
r.Group(func(r chi.Router) {
|
||||||
r.Use(middleware.RequireOwner(container.GetUserUseCase))
|
r.Use(middleware.RequireOwner(container.GetUserUseCase))
|
||||||
r.Use(middleware.TrustedProxyRealIP(trustedProxies))
|
r.Use(middleware.TrustedProxyRealIP(trustedProxies))
|
||||||
@@ -158,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))
|
||||||
@@ -188,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))
|
||||||
@@ -218,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)
|
||||||
@@ -244,16 +251,64 @@ func NewAuthorRouter(container *UseCases, trustedProxies []string) http.Handler
|
|||||||
return r
|
return r
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func NewContentTypeRouter(container *UseCases, trustedProxies []string) http.Handler {
|
||||||
|
r := chi.NewRouter()
|
||||||
|
|
||||||
|
contentTypeHandler := contenttype.NewHandler(container.CreateContentTypeUseCase, container.ListContentTypesUseCase, container.GetContentTypeUseCase, container.UpdateContentTypeUseCase, container.DeleteContentTypeUseCase)
|
||||||
|
|
||||||
|
entryHandler := entry.NewHandler(container.CreateEntryUseCase, container.GetEntryUseCase, container.ListEntriesUseCase, container.UpdateEntryUseCase, container.DeleteEntryUseCase)
|
||||||
|
|
||||||
|
r.Use(authtoken.Verifier(container.Token))
|
||||||
|
r.Use(container.apiKeyAuth())
|
||||||
|
r.Use(middleware.AuditContext(container.GetUserUseCase, trustedProxies))
|
||||||
|
r.Use(middleware.RequireSignedIn)
|
||||||
|
r.Use(authtoken.Authenticator)
|
||||||
|
r.Use(middleware.RequireCurrentToken(container.GetUserUseCase))
|
||||||
|
r.Use(middleware.RequireVerifiedUser(container.GetUserUseCase))
|
||||||
|
r.Get("/", contentTypeHandler.List)
|
||||||
|
r.Get("/{key}", contentTypeHandler.Get)
|
||||||
|
r.Group(func(r chi.Router) {
|
||||||
|
r.Use(middleware.RequireOwnerOrAdmin(container.GetUserUseCase))
|
||||||
|
r.Post("/", contentTypeHandler.Create)
|
||||||
|
r.Put("/{key}", contentTypeHandler.Update)
|
||||||
|
r.Delete("/{key}", contentTypeHandler.Delete)
|
||||||
|
})
|
||||||
|
r.Get("/{key}/entry", entryHandler.List)
|
||||||
|
r.Post("/{key}/entry", entryHandler.Create)
|
||||||
|
r.Get("/{key}/entry/{id}", entryHandler.Get)
|
||||||
|
r.Put("/{key}/entry/{id}", entryHandler.Update)
|
||||||
|
r.Delete("/{key}/entry/{id}", entryHandler.Delete)
|
||||||
|
return r
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewBuiltinTypeRouter(container *UseCases, trustedProxies []string) http.Handler {
|
||||||
|
r := chi.NewRouter()
|
||||||
|
|
||||||
|
builtinTypeHandler := builtintype.NewHandler(container.ListBuiltinTypesUseCase, container.GetBuiltinTypeUseCase)
|
||||||
|
|
||||||
|
r.Use(authtoken.Verifier(container.Token))
|
||||||
|
r.Use(container.apiKeyAuth())
|
||||||
|
r.Use(middleware.AuditContext(container.GetUserUseCase, trustedProxies))
|
||||||
|
r.Use(middleware.RequireSignedIn)
|
||||||
|
r.Use(authtoken.Authenticator)
|
||||||
|
r.Use(middleware.RequireCurrentToken(container.GetUserUseCase))
|
||||||
|
r.Use(middleware.RequireVerifiedUser(container.GetUserUseCase))
|
||||||
|
r.Use(middleware.RequireOwnerOrAdmin(container.GetUserUseCase))
|
||||||
|
r.Get("/", builtinTypeHandler.List)
|
||||||
|
r.Get("/{key}", builtinTypeHandler.Get)
|
||||||
|
return r
|
||||||
|
}
|
||||||
|
|
||||||
func NewActivityRouter(container *UseCases, trustedProxies []string) http.Handler {
|
func NewActivityRouter(container *UseCases, trustedProxies []string) http.Handler {
|
||||||
r := chi.NewRouter()
|
r := chi.NewRouter()
|
||||||
|
|
||||||
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)
|
||||||
@@ -278,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)
|
||||||
@@ -307,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)
|
||||||
@@ -323,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) {
|
||||||
@@ -360,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))
|
||||||
@@ -387,13 +442,15 @@ 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))
|
||||||
r.Mount("/settings", NewSettingsRouter(container, settings.TrustedProxies))
|
r.Mount("/settings", NewSettingsRouter(container, settings.TrustedProxies))
|
||||||
r.Mount("/site", NewSiteRouter(container, settings.TrustedProxies))
|
r.Mount("/site", NewSiteRouter(container, settings.TrustedProxies))
|
||||||
r.Mount("/author", NewAuthorRouter(container, settings.TrustedProxies))
|
r.Mount("/author", NewAuthorRouter(container, settings.TrustedProxies))
|
||||||
|
r.Mount("/content-type", NewContentTypeRouter(container, settings.TrustedProxies))
|
||||||
|
r.Mount("/builtin-type", NewBuiltinTypeRouter(container, settings.TrustedProxies))
|
||||||
r.Mount("/activity", NewActivityRouter(container, settings.TrustedProxies))
|
r.Mount("/activity", NewActivityRouter(container, settings.TrustedProxies))
|
||||||
r.Mount("/media", NewMediaRouter(container, settings.TrustedProxies))
|
r.Mount("/media", NewMediaRouter(container, settings.TrustedProxies))
|
||||||
r.Mount("/image-variants", NewImageVariantRouter(container, settings.TrustedProxies))
|
r.Mount("/image-variants", NewImageVariantRouter(container, settings.TrustedProxies))
|
||||||
@@ -423,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 {
|
||||||
@@ -440,6 +490,7 @@ func InitRoutes(container *UseCases, settings config.Settings) *chi.Mux {
|
|||||||
apiRouter := chi.NewRouter()
|
apiRouter := chi.NewRouter()
|
||||||
apiRouter.Use(middleware.SecurityHeaders(settings.IsProduction()))
|
apiRouter.Use(middleware.SecurityHeaders(settings.IsProduction()))
|
||||||
enableCorsIfConfigured(apiRouter, settings.CorsAllowedOrigins)
|
enableCorsIfConfigured(apiRouter, settings.CorsAllowedOrigins)
|
||||||
|
apiRouter.Use(middleware.CrossOriginProtection(settings.PublicURL))
|
||||||
apiRouter.Use(chimiddleware.GetHead)
|
apiRouter.Use(chimiddleware.GetHead)
|
||||||
apiRouter.Get("/healthz", GetHealth)
|
apiRouter.Get("/healthz", GetHealth)
|
||||||
apiRouter.Mount("/v1", backend)
|
apiRouter.Mount("/v1", backend)
|
||||||
|
|||||||
+28
-24
@@ -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"
|
||||||
@@ -42,27 +41,28 @@ var requiredEnvVars = []string{
|
|||||||
}
|
}
|
||||||
|
|
||||||
var envDefaults = map[string]string{
|
var envDefaults = map[string]string{
|
||||||
"ENVIRONMENT": "production",
|
"ENVIRONMENT": "production",
|
||||||
"PORT": "8080",
|
"PORT": "8080",
|
||||||
"DB_FILE": "./data/renewcms.db",
|
"DB_FILE": "./data/renewcms.db",
|
||||||
config.EnvDatabaseDriver: config.DefaultDatabaseDriver,
|
config.EnvDatabaseDriver: config.DefaultDatabaseDriver,
|
||||||
"DB_TLS": config.DefaultDatabaseTLS,
|
"DB_TLS": config.DefaultDatabaseTLS,
|
||||||
"DB_SSLMODE": config.DefaultDatabaseSSLMode,
|
"DB_SSLMODE": config.DefaultDatabaseSSLMode,
|
||||||
"DB_MAX_OPEN_CONNS": config.DefaultMaxOpenConns,
|
"DB_MAX_OPEN_CONNS": config.DefaultMaxOpenConns,
|
||||||
"DB_MAX_IDLE_CONNS": config.DefaultMaxIdleConns,
|
"DB_MAX_IDLE_CONNS": config.DefaultMaxIdleConns,
|
||||||
"DB_CONN_MAX_LIFETIME_SECONDS": config.DefaultConnMaxLifetimeSeconds,
|
"DB_CONN_MAX_LIFETIME_SECONDS": config.DefaultConnMaxLifetimeSeconds,
|
||||||
"UPLOAD_DIR": "./data/uploads",
|
"UPLOAD_DIR": "./data/uploads",
|
||||||
config.EnvStorageDriver: config.DefaultStorageDriver,
|
config.EnvStorageDriver: config.DefaultStorageDriver,
|
||||||
"S3_REGION": config.DefaultS3Region,
|
"S3_REGION": config.DefaultS3Region,
|
||||||
"S3_PATH_STYLE": config.DefaultS3PathStyle,
|
"S3_PATH_STYLE": config.DefaultS3PathStyle,
|
||||||
"S3_TLS": config.DefaultS3TLS,
|
"S3_TLS": config.DefaultS3TLS,
|
||||||
"AUTH_RATE_LIMIT_MAX_ATTEMPTS": "5",
|
"AUTH_RATE_LIMIT_MAX_ATTEMPTS": "5",
|
||||||
"AUTH_RATE_LIMIT_WINDOW_SECONDS": "60",
|
"AUTH_RATE_LIMIT_WINDOW_SECONDS": "60",
|
||||||
"TRUSTED_PROXIES": "",
|
"TRUSTED_PROXIES": "",
|
||||||
"UPDATE_FEED_URL": "https://git.floriansylvain.fr",
|
config.EnvSmtpAllowInsecure: config.DefaultSmtpAllowInsecure,
|
||||||
"RENEWCMS_CONTAINER": "false",
|
"UPDATE_FEED_URL": "https://git.floriansylvain.fr",
|
||||||
config.EnvImageVariantMaxSourceBytes: config.DefaultImageVariantMaxSourceBytes,
|
"RENEWCMS_CONTAINER": "false",
|
||||||
config.EnvImageVariantMaxSourcePixels: config.DefaultImageVariantMaxSourcePixels,
|
config.EnvImageVariantMaxSourceBytes: config.DefaultImageVariantMaxSourceBytes,
|
||||||
|
config.EnvImageVariantMaxSourcePixels: config.DefaultImageVariantMaxSourcePixels,
|
||||||
config.EnvImageVariantMaxConcurrentRenders: config.DefaultImageVariantMaxConcurrentRenders,
|
config.EnvImageVariantMaxConcurrentRenders: config.DefaultImageVariantMaxConcurrentRenders,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -106,9 +106,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")
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -21,6 +21,12 @@ for example `https://cms.example/v1/article/`.
|
|||||||
or revoked key answers 401, even on public routes. The site writes (`POST`, `PATCH` and `DELETE`
|
or revoked key answers 401, even on public routes. The site writes (`POST`, `PATCH` and `DELETE`
|
||||||
under `/v1/site`) and the author writes (`POST`, `PATCH` and `DELETE` under `/v1/author`, `POST /v1/author/me` included) are session only too.
|
under `/v1/site`) and the author writes (`POST`, `PATCH` and `DELETE` under `/v1/author`, `POST /v1/author/me` included) are session only too.
|
||||||
- Each key can make 120 requests per minute. Beyond that: 429 with a `Retry-After` header.
|
- Each key can make 120 requests per minute. Beyond that: 429 with a `Retry-After` header.
|
||||||
|
- A session lasts 24 hours. `POST /v1/auth/logout` revokes it on the server, so a copied cookie
|
||||||
|
stops working at once; other sessions of the same user stay valid. A password reset ends every
|
||||||
|
session and revokes every key of that user.
|
||||||
|
- A browser `POST`, `PUT`, `PATCH` or `DELETE` sent from another origin without an
|
||||||
|
`Authorization` header answers 403 "Cross-origin requests are not allowed." This blocks
|
||||||
|
cross-site request forgery with the cookie; scripts on other origins must send their key.
|
||||||
|
|
||||||
## Routes a key can call (30)
|
## Routes a key can call (30)
|
||||||
| Group | Routes |
|
| Group | Routes |
|
||||||
|
|||||||
@@ -55,6 +55,14 @@ The use cases `GetPurgeSettings`, `UpdatePurgeSettings`, `PreviewPurge` and `Run
|
|||||||
| `GET /v1/media/purge-preview` | Groups, copies, distinct articles, the first 5 groups, `more` and the fingerprint. |
|
| `GET /v1/media/purge-preview` | Groups, copies, distinct articles, the first 5 groups, `more` and the fingerprint. |
|
||||||
| `POST /v1/media/purge` | Runs the purge. Optional `fingerprint`; 409 when stale or when a run is in progress. |
|
| `POST /v1/media/purge` | Runs the purge. Optional `fingerprint`; 409 when stale or when a run is in progress. |
|
||||||
|
|
||||||
|
### Sessions and personal data retention
|
||||||
|
|
||||||
|
A session is an HS256 token from `api/pkg/authtoken`. `Encode` adds a random `jti` and an `exp` 24 hours ahead; `Decode` refuses a token without `exp`. `authtoken.WithRevocationStore` plugs in `useCases.SessionRevocationUseCase`, which stores a `session.Revocation` (`jti`, `exp`) through the `internal/domain/session` `Repository` (`persistence.RevokedSessionRepository`, table `revoked_sessions`). `LoginHandler.Logout` revokes the presented token; from then on `Decode` answers `ErrRevoked` for it, and a store that cannot be read makes every token invalid rather than valid. Revoking every session of a user stays the job of `token_version`, bumped by a password reset.
|
||||||
|
|
||||||
|
`useCases.EnforceRetentionUseCase.Tick(now)` deletes revocations past their expiry, unverified accounts 7 days after their code expired (`user.UnverifiedRetention`) and invites 30 days after they expired or were accepted (`invite.Retention`), and returns a `retention.Result`. `scheduler.NewSystemRetentionRunner` calls it one minute after startup and then hourly, logs one line only when something was removed, and stops with the other runners on shutdown.
|
||||||
|
|
||||||
|
Uploads go through the `image.MetadataStripper` port before they are measured for size, hashed and stored. `imaging.MetadataStripper` walks the JPEG segments, PNG chunks and WebP RIFF chunks without re-encoding pixels, drops metadata, keeps colour profiles and re-adds an orientation-only EXIF block when the photo was rotated. A container it cannot walk fails the upload with `image.ErrImageUnreadable`.
|
||||||
|
|
||||||
### Activity log
|
### Activity log
|
||||||
|
|
||||||
`internal/domain/audit` holds the append-only `Event` (actor, target and failure-reason snapshots, outcome, security flag, source, ip, user agent, `params` and `changes`), the closed vocabularies (actor type, category, outcome, source, change kind), the `Filter`, `Summary` and `Settings` types, the `Repository` interface (`Append`, `List`, `Summary`, `DeleteOlderThan`: no way to edit or delete one event), the `SettingsRepository` (`Get`, `SaveRetention`, `SaveLastCleanup`; no row means 90 days) and the sentinels `ErrInvalidFilter`, `ErrInvalidRetention`, `ErrInvalidEvent` and `ErrActorNotAllowed`. The `Recorder` port is `Record(ctx, event)`; it returns nothing, so a caller can never fail on it.
|
`internal/domain/audit` holds the append-only `Event` (actor, target and failure-reason snapshots, outcome, security flag, source, ip, user agent, `params` and `changes`), the closed vocabularies (actor type, category, outcome, source, change kind), the `Filter`, `Summary` and `Settings` types, the `Repository` interface (`Append`, `List`, `Summary`, `DeleteOlderThan`: no way to edit or delete one event), the `SettingsRepository` (`Get`, `SaveRetention`, `SaveLastCleanup`; no row means 90 days) and the sentinels `ErrInvalidFilter`, `ErrInvalidRetention`, `ErrInvalidEvent` and `ErrActorNotAllowed`. The `Recorder` port is `Record(ctx, event)`; it returns nothing, so a caller can never fail on it.
|
||||||
@@ -95,7 +103,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).
|
||||||
|
|
||||||
|
|||||||
@@ -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.
|
||||||
|
|
||||||
@@ -11,7 +11,7 @@ Copy [`.env.example`](../.env.example) to `.env` to get started. When a required
|
|||||||
| Name | Description | Example |
|
| Name | Description | Example |
|
||||||
|-----------------|---------------------------------------------------------------------------------------------------------------------|----------------------------|
|
|-----------------|---------------------------------------------------------------------------------------------------------------------|----------------------------|
|
||||||
| `PUBLIC_URL` | Public base URL of the site, including scheme and no trailing slash. Used for links in emails and in the startup log. It is also the CMS's own address: at the first migration, when the sites table is empty, it seeds the default site (name "Default", key "default") with its scheme and host (path dropped, non-loopback `http` upgraded to `https`); an unparseable value stops the migration. It is never read for sites afterwards. | `https://cms.example.com` |
|
| `PUBLIC_URL` | Public base URL of the site, including scheme and no trailing slash. Used for links in emails and in the startup log. It is also the CMS's own address: at the first migration, when the sites table is empty, it seeds the default site (name "Default", key "default") with its scheme and host (path dropped, non-loopback `http` upgraded to `https`); an unparseable value stops the migration. It is never read for sites afterwards. | `https://cms.example.com` |
|
||||||
| `JWT_SECRET` | Secret used to sign the auth JWT. Use a long random value; changing it logs everyone out. | `openssl rand -hex 32` |
|
| `JWT_SECRET` | Secret used to sign the auth JWT. It must be at least 32 bytes, and the example values from `.env.example` and `docker.env.example` are refused: the server stops at startup with `JWT_SECRET is too weak` and how to generate one. Changing it logs everyone out. | `openssl rand -hex 32` |
|
||||||
| `SMTP_LOGIN` | SMTP username used to authenticate with the server. Some providers (e.g. Brevo) issue a login distinct from the sender address. | `noreply@example.com` |
|
| `SMTP_LOGIN` | SMTP username used to authenticate with the server. Some providers (e.g. Brevo) issue a login distinct from the sender address. | `noreply@example.com` |
|
||||||
| `SMTP_SENDER` | Sender address used in the `From` header. Must be an address/domain the SMTP provider allows that login to send as. | `noreply@example.com` |
|
| `SMTP_SENDER` | Sender address used in the `From` header. Must be an address/domain the SMTP provider allows that login to send as. | `noreply@example.com` |
|
||||||
| `SMTP_PASSWORD` | SMTP password. | |
|
| `SMTP_PASSWORD` | SMTP password. | |
|
||||||
@@ -29,9 +29,10 @@ 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. |
|
||||||
|
| `SMTP_ALLOW_INSECURE` | `false` | `true` lets RenewCMS deliver mail without encryption to a server on another host that does not offer STARTTLS (a relay on a private network, a local Mailpit container). By default such delivery fails with an error naming this variable; port `465` always uses implicit TLS and `localhost`, `127.0.0.1` and `::1` are always allowed in clear text. Credentials (`SMTP_LOGIN`/`SMTP_PASSWORD`) are never sent unencrypted to another host, whatever this says. Any value other than `true` or `false` (case-insensitive) stops the server at boot. |
|
||||||
| `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). |
|
||||||
| `RENEWCMS_CONTAINER` | `false` | Set to `true` (case-insensitive; any other value means `false`) when the app runs in a container. Settings then tells the owner to update by pulling a new image instead of offering browser updates, and `can_apply` is always `false`. The Dockerfile and `docker-compose.yml` set it to `true`. Update checks still work. |
|
| `RENEWCMS_CONTAINER` | `false` | Set to `true` (case-insensitive; any other value means `false`) when the app runs in a container. Settings then tells the owner to update by pulling a new image instead of offering browser updates, and `can_apply` is always `false`. The Dockerfile and `docker-compose.yml` set it to `true`. Update checks still work. |
|
||||||
| `IMAGE_VARIANT_MAX_SOURCE_BYTES` | `10485760` | Largest stored image, in bytes, that an [image variant](image-variants.md) may be generated from. A request for a bigger source answers 413 with a plain-text body. The original is never affected, and SVG and animated GIF are always served as they are. A value that is not a whole number greater than zero stops the server at boot with an error naming the variable. |
|
| `IMAGE_VARIANT_MAX_SOURCE_BYTES` | `10485760` | Largest stored image, in bytes, that an [image variant](image-variants.md) may be generated from. A request for a bigger source answers 413 with a plain-text body. The original is never affected, and SVG and animated GIF are always served as they are. A value that is not a whole number greater than zero stops the server at boot with an error naming the variable. |
|
||||||
|
|||||||
@@ -0,0 +1,20 @@
|
|||||||
|
# Custom content types
|
||||||
|
|
||||||
|
A content type is a named schema (a key, a name and 1 to 50 fields) stored as one row with the fields as a JSON text column. Entries of every type share one generic table whose `data` column holds a JSON object. No DDL runs at runtime, so creating or changing a type never alters the database schema.
|
||||||
|
|
||||||
|
## Icon, built-in types and user lookup
|
||||||
|
|
||||||
|
- A content type has an optional `icon`: `null` or a string matching `^[a-z][a-z0-9-]{0,39}$`, validated in the domain (`ErrInvalidIcon`, `400 invalid_icon`) and never checked against a list of known icons. `""` is stored as `null`. `PUT` replaces the icon like the name and the fields, so an absent icon clears it. The column is nullable, so rows stored before it existed read as `null`.
|
||||||
|
- `GET /v1/builtin-type` and `GET /v1/builtin-type/{key}` expose a static, read-only catalogue (`internal/domain/builtintype`) of the built-in types `article`, `author`, `site`, `media` and `user` as `key`, `name` and `fields` shaped like content type fields. Owners and admins only. It uses no repository; an unknown key is `404 builtin_type_not_found`. A test checks that every catalogue field key exists in the JSON of the matching entity.
|
||||||
|
- `GET /v1/user/lookup?ids=1,2,3` returns `[{id, display_name}]` for any verified user, ordered by id, with the username when the display name is empty. 1 to 100 distinct uint32 ids; anything else is `400`. Unknown ids are omitted.
|
||||||
|
|
||||||
|
## Layering
|
||||||
|
|
||||||
|
The domain packages `internal/domain/contenttype` and `internal/domain/entry` own the rules: key, name and field validation, entry validation against a schema, the sort whitelist, the page limits and the value equality used by uniqueness. The use cases orchestrate them through the two repositories. The repositories only store and load rows. Entry counting for the "type still has entries" rule lives on the entry repository.
|
||||||
|
|
||||||
|
## Known limitations of phase 1
|
||||||
|
|
||||||
|
- Uniqueness and schema re-validation are O(n). Checking a unique field loads every entry of the type and compares values in Go, and updating a type with stored entries loads all of them to re-validate. This keeps the SQL portable across SQLite, MySQL/MariaDB and PostgreSQL. The path to fix it is the filterable-fields phase: project the values of unique and filterable fields into an indexed table, so uniqueness becomes an indexed lookup and re-validation can be restricted to the changed fields.
|
||||||
|
- Unique values are checked without a transaction, so two concurrent writes of the same unique value can both succeed. A content type key is protected by a unique index, and a violation is reported as `content_type_key_taken` (409).
|
||||||
|
- `entry.Repository.DeleteByContentType` is intentionally unused for now. A content type that still has entries cannot be deleted; the method is kept as part of the repository contract for a later cascade.
|
||||||
|
- Listing is limited to page 1,000,000 and to page sizes of 100 so that the SQL offset cannot overflow.
|
||||||
+1
-1
@@ -274,7 +274,7 @@ Either way, set `TRUSTED_PROXIES` (see [configuration.md](configuration.md)) to
|
|||||||
|
|
||||||
RenewCMS sends `Content-Security-Policy` (including `frame-ancestors 'none'`), `X-Content-Type-Options`, `X-Frame-Options`, `Referrer-Policy` and `Cross-Origin-Opener-Policy` itself, so the proxy doesn't need to add them. With `ENVIRONMENT=production` it also sends `Strict-Transport-Security: max-age=31536000` (browsers ignore it over plain HTTP, so serve the site over HTTPS only). Don't add the same headers in the proxy, or they will be duplicated.
|
RenewCMS sends `Content-Security-Policy` (including `frame-ancestors 'none'`), `X-Content-Type-Options`, `X-Frame-Options`, `Referrer-Policy` and `Cross-Origin-Opener-Policy` itself, so the proxy doesn't need to add them. With `ENVIRONMENT=production` it also sends `Strict-Transport-Security: max-age=31536000` (browsers ignore it over plain HTTP, so serve the site over HTTPS only). Don't add the same headers in the proxy, or they will be duplicated.
|
||||||
|
|
||||||
The CSP allows Google Fonts (`fonts.googleapis.com`, `fonts.gstatic.com`) and `https:` images, because the SPA loads its fonts from Google and articles may embed remote images. `style-src` keeps `'unsafe-inline'` for the article editor; `script-src` is `'self'` only.
|
The CSP serves fonts from `'self'` only (the SPA bundles its fonts, so no visitor IP address is sent to a font CDN) and allows `https:` images, because articles may embed remote images. `style-src` keeps `'unsafe-inline'` for the article editor; `script-src` is `'self'` only.
|
||||||
|
|
||||||
## Using MySQL or MariaDB
|
## Using MySQL or MariaDB
|
||||||
|
|
||||||
|
|||||||
@@ -20,6 +20,12 @@ Back-office board groups: Sites, Sites: form, Sites: delete, Authors, Authors: f
|
|||||||
- Only individual states that render a relative time or a countdown carry the "Clock-sensitive" tag (13 states, listed in states.md). No Home or Articles frame is tagged as a whole.
|
- Only individual states that render a relative time or a countdown carry the "Clock-sensitive" tag (13 states, listed in states.md). No Home or Articles frame is tagged as a whole.
|
||||||
- Role-restricted variants drawn: read-only Authors list and detail, hidden Sites entry, Sites 403, own-author edit.
|
- Role-restricted variants drawn: read-only Authors list and detail, hidden Sites entry, Sites 403, own-author edit.
|
||||||
|
|
||||||
|
## Pass 4: custom content types
|
||||||
|
Board `RenewCMS Screens Schema.dc.html` (frames: `SchemaFrame`, mounted in `AppFrame`): 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.
|
||||||
|
- Backend gaps still open: built-in types and fields, display names for created_by and updated_by, a type icon, per-change entry counts.
|
||||||
|
- Not done: Back-office and Prototype boards were not compared visually after the sidebar change (see Checks below).
|
||||||
|
|
||||||
## Specs
|
## Specs
|
||||||
routes.md · components.md · states.md · foundations.md · change-list.md · activity-spec.js · screens/*.md (24 files)
|
routes.md · components.md · states.md · foundations.md · change-list.md · activity-spec.js · screens/*.md (24 files)
|
||||||
|
|
||||||
|
|||||||
@@ -89,3 +89,45 @@ Frames: `DirectoryFrame.dc.html` (Sites, Authors, editor section content; the li
|
|||||||
| SeoStatusChip | New | UBadge | Lightbulb + count (warning soft) or eye-off "Hidden" (outline). Articles rows and cards |
|
| SeoStatusChip | New | UBadge | Lightbulb + count (warning soft) or eye-off "Hidden" (outline). Articles rows and cards |
|
||||||
| NeedsAttentionToggle | New | UButton (pressed state) | Articles toolbar, sand when on |
|
| NeedsAttentionToggle | New | UButton (pressed state) | Articles toolbar, sand when on |
|
||||||
| TitleTemplateField | New | UInput + live example | Sites form |
|
| TitleTemplateField | New | UInput + live example | Sites form |
|
||||||
|
|
||||||
|
|
||||||
|
## Custom content types (pass 4)
|
||||||
|
|
||||||
|
Frames: `SchemaFrame.dc.html` (all schema, content and entry bodies; relation, permissions and import frames are Later), mounted in `AppFrame.dc.html`. Existing pieces are reused unchanged: dialogs and sheets, toasts, alerts, paginator, skeletons, empty states, SlugField, CodeSnippet, the single switch.
|
||||||
|
|
||||||
|
**AppFrame changes.** Sidebar: a "Schema" item (icon shapes) after Users, owner and admin only. A "Content" group under the main items, one row per custom type (default icon files, name truncated with the full name in the tooltip, selected row sand). Over 5 types it shows the first 5 and the selected one, then "Show all N". Mobile drawer: the group is one collapsed row "All content types" with the count; expanded it lists the types at 44 px. New props on the shell state: `content` (types), `contentOn`, `contentOpen`. The group is hidden when there are no custom types. No existing item changed.
|
||||||
|
|
||||||
|
| Component | Status | Nuxt UI | Notes |
|
||||||
|
|---|---|---|---|
|
||||||
|
| SchemaTable | New | UTable; below 640 px a list of UCard | Same pattern as SitesTable. Built-in rows add the lock and a Built-in badge |
|
||||||
|
| BuiltInBadge | New | UBadge outline + lock icon | Existing badges have no lock; same size as the Linked badge |
|
||||||
|
| FieldList | New | List of UButton rows, useSortable, UBadge | No Nuxt UI sortable list. Keyboard: the grip is a button; Space picks up, arrows move, Space drops, Esc cancels. Move up and Move down buttons on the selected row. Same approach as AuthorList |
|
||||||
|
| FieldInspector | New | UForm, UFormField, UInput, UInputNumber, UInputDate, USelect, UTextarea, USwitch | Composition only. Controls follow the field type |
|
||||||
|
| FieldTypePicker | New | URadioGroup variant="card" in a grid, icon in the label | Existing radio cards fit; only the icon and the lock state are added |
|
||||||
|
| KeyField | Existing | SlugField (UInput + UButton + UBadge) | Reused for the type key and field keys. Locked variant already exists |
|
||||||
|
| ChoicesEditor | New | UInput + UButton rows, useSortable | UInputTags can't reorder or flag a blank or duplicate per row |
|
||||||
|
| ApiPreview | New | UCollapsible + CodeSnippet + UButton | CodeSnippet is reused. Sheet on mobile |
|
||||||
|
| ChangeReview | New | UModal (sheet on mobile), UBadge, list rows | Dialog pattern unchanged. Rows reuse the UAlert-style row of SuggestionList |
|
||||||
|
| SchemaRefusal, DeleteTypeDialog | New | UModal + UAlert | Dialog pattern unchanged. Delete uses color="error" |
|
||||||
|
| ContentNavGroup | New | UNavigationMenu group "Content" (NavGroup) | Adds the 5 + selected cap, "Show all N" and the collapsed mobile row |
|
||||||
|
| EntryTable | New | UTable with column visibility | Cells per field type (FieldCell). Cards on mobile |
|
||||||
|
| ColumnPicker | New | UPopover + UCheckbox list; bottom sheet on mobile | UDropdownMenu closes on each pick and has no cap message |
|
||||||
|
| SortSelect | New | USelect + UButton icon | ID, Created and Updated only |
|
||||||
|
| FieldControl | New | UInput, UInputNumber, UInputDate, USelect, USwitch (the single toggle), MarkdownField | One switch per field type, generated from the schema |
|
||||||
|
| MarkdownField | New | UTextarea + UTabs (Write, Preview) + toolbar of UButton | The article editor is a full document editor. This is a compact one |
|
||||||
|
| FieldCell | New | text, UBadge outline (choice), icon + text (yes or no) | Renders one value per type, with the empty dash |
|
||||||
|
| EntryForm | New | UForm generated from the schema | Provenance footer, schema-changed alert |
|
||||||
|
| RelationPicker (later) | New | URadioGroup card + USelect | Sentence preview is text |
|
||||||
|
| RelationField (later) | New | UInputMenu multiple | Chips and search |
|
||||||
|
| PermissionsGrid (later) | New | UTable + UCheckbox; UCard list on mobile | |
|
||||||
|
| SchemaImportDialog (later) | New | UModal + UFileUpload | |
|
||||||
|
|
||||||
|
## 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 |
|
||||||
@@ -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.
|
||||||
@@ -16,6 +16,13 @@
|
|||||||
| /article/:id/edit | Editor gains the "Site and authors" section (Site select and authors, any role that can edit the article) | none | PATCH /v1/article/{id} {site_id, author_ids[]} |
|
| /article/:id/edit | Editor gains the "Site and authors" section (Site select and authors, any role that can edit the article) | none | PATCH /v1/article/{id} {site_id, author_ids[]} |
|
||||||
| /profile | Profile gains the "Author profile" card, all roles | none | POST /v1/author/me |
|
| /profile | Profile gains the "Author profile" card, all roles | none | POST /v1/author/me |
|
||||||
| /integration/api-keys | API keys | none | GET/POST /v1/api-key, DELETE /v1/api-key/{id} |
|
| /integration/api-keys | API keys | none | GET/POST /v1/api-key, DELETE /v1/api-key/{id} |
|
||||||
|
| /schema | Schema list, custom and built-in types (owner or admin; others get a 403 page and no sidebar entry). Available now | none | GET /v1/content-type |
|
||||||
|
| /schema/new | Schema builder, new type (owner or admin). Available now | none | POST /v1/content-type |
|
||||||
|
| /schema/:key | Schema builder for a custom type, read-only view for a built-in (owner or admin). Review step on save when the type has entries. Available now | none | GET/PUT/DELETE /v1/content-type/{key} |
|
||||||
|
| /content/:key | Entry list (any verified user). Available now | page, size, sort | GET /v1/content-type/{key}, GET /v1/content-type/{key}/entry?page=&size=&sort= |
|
||||||
|
| /content/:key/new | New entry (any verified user). Available now | none | POST /v1/content-type/{key}/entry |
|
||||||
|
| /content/:key/:id | Entry editor (any verified user). Available now | none | GET/PUT/DELETE /v1/content-type/{key}/entry/{id} |
|
||||||
|
| /settings/permissions | Permissions grid (owner or admin). Later | none | not built |
|
||||||
|
|
||||||
## Pagination in the URL (Articles, Media)
|
## Pagination in the URL (Articles, Media)
|
||||||
`/articles?page=2&size=50` and `/media?page=7&size=50`. Parameter names follow the repo (activity already uses `page` and `size`). Allowed sizes 5, 25, 50, 100. Defaults `page=1`, `size=25`, omitted from the URL when default. Changing search, tab, filter or size resets `page` to 1. `page` above the last page redirects (replace) to the last page and shows "That page doesn't exist. Showing the last page." An invalid `size` falls back to 25.
|
`/articles?page=2&size=50` and `/media?page=7&size=50`. Parameter names follow the repo (activity already uses `page` and `size`). Allowed sizes 5, 25, 50, 100. Defaults `page=1`, `size=25`, omitted from the URL when default. Changing search, tab, filter or size resets `page` to 1. `page` above the last page redirects (replace) to the last page and shows "That page doesn't exist. Showing the last page." An invalid `size` falls back to 25.
|
||||||
@@ -43,3 +50,6 @@ Sites pagination: `/settings/sites?q=&page=&size=` with the same rules as Articl
|
|||||||
|
|
||||||
## SEO
|
## SEO
|
||||||
No new page routes. The panel and dialog are overlays on `/article/:id/edit`: `?panel=seo` (optionally `&field=seo_title|seo_description|slug|cover|authors|body` for the suggestion jump) and `?dialog=seo-api`. `/articles?seo=suggestions` is the Needs attention filter. API: GET /v1/article/{id}/seo, GET /v1/site/{key}/sitemap?page=&size=, PATCH /v1/article/{id} (new fields), PATCH /v1/site/{id} {site_name, title_template, default_description, social_image_id, default_robots}, GET /v1/article/?seo=ready|suggestions|hidden. 401 without a session; 403 owner_only on site SEO fields; 409 slug_taken {suggestion} on PATCH slug; 400 on invalid canonical_url or title_template.
|
No new page routes. The panel and dialog are overlays on `/article/:id/edit`: `?panel=seo` (optionally `&field=seo_title|seo_description|slug|cover|authors|body` for the suggestion jump) and `?dialog=seo-api`. `/articles?seo=suggestions` is the Needs attention filter. API: GET /v1/article/{id}/seo, GET /v1/site/{key}/sitemap?page=&size=, PATCH /v1/article/{id} (new fields), PATCH /v1/site/{id} {site_name, title_template, default_description, social_image_id, default_robots}, GET /v1/article/?seo=ready|suggestions|hidden. 401 without a session; 403 owner_only on site SEO fields; 409 slug_taken {suggestion} on PATCH slug; 400 on invalid canonical_url or title_template.
|
||||||
|
|
||||||
|
## Custom content types in the URL
|
||||||
|
`/content/events?page=2&size=50&sort=created_at:desc`. `page` and `size` follow Articles (sizes 5, 25, 50, 100; default 25). `sort` is one parameter, `<id|created_at|updated_at>:<asc|desc>`, default `updated_at:desc`. Defaults are omitted from the URL; a size or sort change resets `page` to 1; invalid values are replaced silently by the default; a `page` past the end falls back to the last page. The response carries `total`, `page`, `size` and `sort`: use them for the summary ("Showing 1–5 of 37"), the pager and the "37 entries use this content type" line of the review step. No filter or search on custom fields yet. Auth: `/schema*` owner or admin (403 page otherwise), `/content*` any verified user (unverified accounts are redirected to /register/pending). Unknown type: 404 content_type_not_found page. Unknown entry: 404 entry_not_found page.
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
# Content
|
||||||
|
|
||||||
|
Route: `/content/:key`. API: GET /v1/content-type/{key} · GET /v1/content-type/{key}/entry?page=&size=&sort=. Auth: any verified user.
|
||||||
|
|
||||||
|
Visual reference: `RenewCMS Screens Schema.dc.html`, groups "Content and entry list". Frames: `SchemaFrame.dc.html` mounted in `AppFrame.dc.html` (shell, sidebar, topbar, drawer). Every state is drawn in light and dark (theme switch) at 1440×900 (shown at 50%) and 390×844 (shown at 75%). Copy is exact. Strings in a Copy cell are separated by " · " and listed in reading order. Nothing is clock-sensitive.
|
||||||
|
|
||||||
|
### 5 Content navigation and entry list (group "5 Content and entry list", 9 states)
|
||||||
|
|
||||||
|
Route: `/content/:key`. API: GET /v1/content-type/{key}, GET /v1/content-type/{key}/entry. Auth: Any verified user.
|
||||||
|
|
||||||
|
The sidebar gets a "Content" group, one item per custom type (a default icon: types have no icon in the API). With more than 5 types it shows the first 5 and the selected one, then "Show all N"; long names truncate with the full name in a tooltip. On mobile the group is one collapsed row in the drawer. List: ID, up to 6 chosen field columns (default: first 4), Created, Updated, Updated by. Sort: ID, Created, Updated, either direction (default Updated, newest first). Page size 5, 25, 50, 100 (default 25). No filter or search. URL: /content/events?page=2&size=50&sort=created_at:desc (defaults omitted). The response carries total, page, size and sort; the summary, the pager and the review dialog use them.
|
||||||
|
|
||||||
|
| # | State | Trigger | Copy | Scope |
|
||||||
|
|---|---|---|---|---|
|
||||||
|
| 1 | Populated | /content/events. 7 entries, one page: no pager, only the count. | Content · Events · events · 7 fields · New entry · Sort by · Last updated · Columns · Edit content type · ID · Title · Starts on · Ends on · Online · Created · Updated · Updated by · 7 entries | Available now |
|
||||||
|
| 2 | Paginated, 5 per page | /content/events?size=5. 37 entries. | Showing 1–5 of 37 · 5 per page · Page 1 of 8 (mobile) | Available now |
|
||||||
|
| 3 | Columns menu | The Columns button. Popover on desktop, sheet on mobile. Created and updated always show. | Columns · 4 of 6 · Choose up to 6 fields to show. 4 selected. · Created and updated dates always show · Reset · Done | Available now |
|
||||||
|
| 4 | Many types in the sidebar | 14 custom types. Long names truncate. Mobile shows the drawer with the group expanded. | Content · Frequently asked questions and answers (truncated) · Show all 14 · All content types 14 (mobile, collapsed) | Available now |
|
||||||
|
| 5 | Loading | First load or retry. | (skeleton) | Available now |
|
||||||
|
| 6 | Empty for this type | Total is 0. The hint points to New entry. | No entries yet · Use New entry to add the first event. Each entry follows the fields of this content type. · New entry | Available now |
|
||||||
|
| 7 | Error | 500 or network failure. | Couldn't load entries · GET /v1/content-type/events/entry failed. Check your connection and try again. · Try again | Available now |
|
||||||
|
| 8 | Forbidden (403) | The API answers 403. Unverified accounts are redirected to /register/pending before this. | You don't have access to Events · Your account can't open this content right now. If you think this is a mistake, ask an owner or an admin. · Go to Home | Available now |
|
||||||
|
| 9 | Type not found | 404 content_type_not_found on /content/unknown. | Content type not found · It may have been deleted, or the address may be mistyped. · Go to Home | Available now |
|
||||||
|
|
||||||
|
## 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.
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
# Entry editor
|
||||||
|
|
||||||
|
Route: `/content/:key/new`, `/content/:key/:id`. API: POST /v1/content-type/{key}/entry · GET/PUT/DELETE /v1/content-type/{key}/entry/{id}. Auth: any verified user.
|
||||||
|
|
||||||
|
Visual reference: `RenewCMS Screens Schema.dc.html`, groups "Entry editor". Frames: `SchemaFrame.dc.html` mounted in `AppFrame.dc.html` (shell, sidebar, topbar, drawer). Every state is drawn in light and dark (theme switch) at 1440×900 (shown at 50%) and 390×844 (shown at 75%). Copy is exact. Strings in a Copy cell are separated by " · " and listed in reading order. Nothing is clock-sensitive.
|
||||||
|
|
||||||
|
### 6 Entry editor (group "6 Entry editor", 13 states)
|
||||||
|
|
||||||
|
Route: `/content/:key/new, /content/:key/:id`. API: POST /v1/content-type/{key}/entry, GET/PUT/DELETE /v1/content-type/{key}/entry/{id}. Auth: Any verified user.
|
||||||
|
|
||||||
|
The form is generated from the schema, one control per field in schema order. Required fields carry * and the line "Fields marked * are required." Defaults are pre-filled on create and tagged Default. Saving replaces the whole entry.
|
||||||
|
|
||||||
|
| # | State | Trigger | Copy | Scope |
|
||||||
|
|---|---|---|---|---|
|
||||||
|
| 1 | New entry | /content/events/new. Online is pre-filled from its default. | New entry · Events · Fields marked * are required. · Default · Each entry needs a different title. · Between 1 and 5000. · Choose an option · Pick a date · Save · Cancel · New entry · Not saved yet | Available now |
|
||||||
|
| 2 | Editing | /content/events/42. Save is disabled until something changes. | Lime plaster workshop · Events · Entry 42 · Saved · Delete · Cancel · Save · Created by · Updated by · Inès Duarte · 12 Oct 2026, 09:14 · Marta Alves · 15 Oct 2026, 11:02 | Available now |
|
||||||
|
| 3 | Unsaved changes | Any edit. | Unsaved changes · 32 / 80 | Available now |
|
||||||
|
| 4 | Markdown preview | The Preview tab of a rich text field. | Write · Preview | Available now |
|
||||||
|
| 5 | Saving | PUT or POST in flight. Form dims. | Saving… | Available now |
|
||||||
|
| 6 | Saved | 200. | Saved at 11:02 · Entry saved · "Lime plaster workshop" is up to date. | Available now |
|
||||||
|
| 7 | Save failed | 500 or network failure. Values stay. | Save failed · Couldn't save the entry · Something went wrong on our side. Your changes are still here. Try again in a moment. · Try again | Available now |
|
||||||
|
| 8 | Required fields empty | 422 invalid_entry: title: required, starts_on: required. The first field with an error takes focus. | Fill in Title. · Pick a date for Starts on. · Not saved | Available now |
|
||||||
|
| 9 | Rule errors | 422 invalid_entry for max, type, max and options. One rule per field is shown at a time. | Title can be up to 80 characters. · 91 / 80 · Ends on must be a date, like 2026-11-21. · Capacity must be at most 5000. · Choose one of: Talk, Workshop or Meetup. · Not saved | Available now |
|
||||||
|
| 10 | Duplicate unique value (409) | 409 invalid_entry: title: unique. | Not saved · Another entry already uses this title. Change it and save again. · Another entry already uses this Title. Enter a different one. | Available now |
|
||||||
|
| 11 | Entry not found | 404 entry_not_found, for example after a delete elsewhere. | Entry not found · It may have been deleted by someone else. · Back to Events | Available now |
|
||||||
|
| 12 | Schema changed since load | 422 invalid_entry: room: required, or unknown_field. The form is read-only until reloaded. | The fields of Events changed · A field was removed and a new required field, Room, was added after you opened this form. Reload the form to continue. What you typed here can't be saved against the old fields. · Reload form | Available now |
|
||||||
|
| 13 | Delete entry: confirm | Delete. | Delete this entry? · "Lime plaster workshop" will be deleted from Events. This can't be undone. · Cancel · Delete entry | Available now |
|
||||||
|
|
||||||
|
## 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.
|
||||||
@@ -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.
|
||||||
@@ -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.
|
||||||
@@ -0,0 +1,40 @@
|
|||||||
|
# Schema: later
|
||||||
|
|
||||||
|
All states on this page are **Later**: relations, permissions and schema export and import are not built. Drawn now so the model and the layout are settled.
|
||||||
|
|
||||||
|
Visual reference: `RenewCMS Screens Schema.dc.html`, groups "Relations", "Permissions", "Export and import". Frames: `SchemaFrame.dc.html` mounted in `AppFrame.dc.html` (shell, sidebar, topbar, drawer). Every state is drawn in light and dark (theme switch) at 1440×900 (shown at 50%) and 390×844 (shown at 75%). Copy is exact. Strings in a Copy cell are separated by " · " and listed in reading order. Nothing is clock-sensitive.
|
||||||
|
|
||||||
|
### 7 Relation field and picker (group "7 Relations", 3 states)
|
||||||
|
|
||||||
|
Route: `/schema/:key, /content/:key/:id`. API: not built. Auth: Owner or admin (picker), any verified user (form).
|
||||||
|
|
||||||
|
All later. The model reads as two sentences, with a live preview of both sides. Three shapes: one to one, one to many, many to many.
|
||||||
|
|
||||||
|
| # | State | Trigger | Copy | Scope |
|
||||||
|
|---|---|---|---|---|
|
||||||
|
| 1 | Relation in the builder | A seventh type, Relation, in the type gallery. | Relation · Related content type · How are they connected? · One to one · Each Event has one Venue, and each Venue has one Event. · One to many · Each Event has one Venue. A Venue has many Events. · Many to many · Each Event has many Venues, and each Venue has many Events. · Each Event has one Venue · Each Venue has many Events · shown on Venue as the field "Events" | Later |
|
||||||
|
| 2 | Relation in the entry form | Search and pick; chips for many. | Venue · Speakers · Search to add · An event can have many speakers. | Later |
|
||||||
|
| 3 | Relation in the list | One chip, two chips and +N, or a dash. | One chip for a single relation. Up to two chips and a "+N" for many. Empty shows a dash. | Later |
|
||||||
|
|
||||||
|
### 8 Permissions grid (group "8 Permissions", 2 states)
|
||||||
|
|
||||||
|
Route: `/settings/permissions`. API: not built. Auth: Owner or admin.
|
||||||
|
|
||||||
|
All later. Rows are types, columns are actions, one role at a time. Built-in rows are locked. Mobile collapses to one card per type with four checkboxes.
|
||||||
|
|
||||||
|
| # | State | Trigger | Copy | Scope |
|
||||||
|
|---|---|---|---|---|
|
||||||
|
| 1 | Default: today's rules | Role User selected. Everything on, as today. | Permissions · What each role can do with each content type. · Today's rules are the starting point · Owners and admins edit the schema. Any verified user can read, add, edit and delete entries. · Owner · Admin · User · Read · Create · Update · Delete · Built-in types. RenewCMS sets these rules. · Schema (create, edit and delete content types): owners and admins only. Set by RenewCMS. · No changes · Discard · Save permissions | Later |
|
||||||
|
| 2 | Changed, not saved | Two types restricted for the User role. | 4 changes not saved · Changed | Later |
|
||||||
|
|
||||||
|
### 9 Schema export and import (group "9 Export and import", 3 states)
|
||||||
|
|
||||||
|
Route: `/schema (dialogs)`. API: not built. Auth: Owner or admin.
|
||||||
|
|
||||||
|
All later. Dev-to-production flow: export a file, import it elsewhere, preview, same compatibility review as group 3, explicit confirm.
|
||||||
|
|
||||||
|
| # | State | Trigger | Copy | Scope |
|
||||||
|
|---|---|---|---|---|
|
||||||
|
| 1 | Export | Export on /schema. | Export schema · Download the fields of your content types as a file. Entries aren't included. · All content types · 3 content types · One content type · Choose which one · File name · renewcms-schema.json · Import this file on another RenewCMS site to create the same content types. · Cancel · Download file | Later |
|
||||||
|
| 2 | Import preview | A file was chosen. | Import schema · renewcms-schema.json · 3 content types · Create 1, change 1, no change 1 · Recipes · New content type with 4 fields. · Events · Add 2 fields, remove Description. Events has 37 entries on this site. · Removes data · Press mentions · Same as on this site. · Existing entries are checked against the changes when you import. If any entry doesn't fit, nothing is imported. · Cancel · Import schema | Later |
|
||||||
|
| 3 | Import refused | The server answers schema_incompatible. | Nothing was imported · Some entries on this site don't fit the imported fields. RenewCMS can't tell which entries. The flagged change can cause this. · Try again | Later |
|
||||||
@@ -0,0 +1,81 @@
|
|||||||
|
# Schema
|
||||||
|
|
||||||
|
Route: `/schema`, `/schema/new`, `/schema/:key`. API: GET/POST /v1/content-type · GET/PUT/DELETE /v1/content-type/{key}. Auth: owner or admin.
|
||||||
|
|
||||||
|
Custom content types: an owner or admin defines a type (for example Events) made of 1 to 50 ordered fields; any verified user then writes entries. Everything about a type happens on one screen. Primary words: content type, field, choice list, entry. "Key" is kept for the API identifier. The key of a type is chosen at creation and never changes; the key and type of a saved field never change. Built-in types (Articles, Authors, Sites, Media, Users) are listed with a lock and a "Built-in" badge and open a read-only view. Non-owner, non-admin users see no Schema entry; a direct link shows a 403 page.
|
||||||
|
|
||||||
|
Visual reference: `RenewCMS Screens Schema.dc.html`, groups "Schema list", "Schema builder", "Review and delete", "Field types". Frames: `SchemaFrame.dc.html` mounted in `AppFrame.dc.html` (shell, sidebar, topbar, drawer). Every state is drawn in light and dark (theme switch) at 1440×900 (shown at 50%) and 390×844 (shown at 75%). Copy is exact. Strings in a Copy cell are separated by " · " and listed in reading order. Nothing is clock-sensitive.
|
||||||
|
|
||||||
|
### 1 Schema: list of types (group "1 Schema list", 6 states)
|
||||||
|
|
||||||
|
Route: `/schema, /schema/:key (built-in)`. API: GET /v1/content-type. Auth: Owner or admin.
|
||||||
|
|
||||||
|
Sidebar entry "Schema" for owners and admins only. Built-in types are listed with a lock and a Built-in badge, always after the custom ones. They open a read-only view. Sample data: the field counts of built-ins are illustrative.
|
||||||
|
|
||||||
|
| # | State | Trigger | Copy | Scope |
|
||||||
|
|---|---|---|---|---|
|
||||||
|
| 1 | Populated | An owner or admin opens /schema. | Schema · Content types and the fields they are made of. · New content type · Name · Key · Fields · Last updated · Built-in types are managed by RenewCMS. You can read their fields, but not change them. · Built-in · 3 content types · 5 built-in | Available now |
|
||||||
|
| 2 | Loading | First load or retry. Skeleton rows appear after 150 ms. New content type is disabled. | (skeleton) · New content type (disabled) | Available now |
|
||||||
|
| 3 | Empty: no custom type yet | GET /v1/content-type returns []. Built-ins are still listed below. | No content types yet · Create a content type to manage your own kind of content, like events or recipes. The built-in types stay as they are. · New content type | Available now |
|
||||||
|
| 4 | Error | 500 or network failure on the list request. | Couldn't load content types · GET /v1/content-type failed. Check your connection and try again. · Try again | Available now |
|
||||||
|
| 5 | Forbidden (403) | A user who is not owner or admin types /schema. There is no sidebar entry, so the page explains instead of redirecting. | You don't have access to Schema · Only owners and admins can change content types. You can still add and edit entries from the Content menu. · Go to Home | Available now |
|
||||||
|
| 6 | Built-in type: read-only view | Click Articles in the list. No edit, no delete, no add field. | Articles · Built-in · Managed by RenewCMS · Articles is a built-in type. You can read its fields here, but you can't edit it, delete it or add fields. · Label · Key · Type · Rules · Entries of built-in types are managed from their own screens, like Articles and Authors. | Available now |
|
||||||
|
|
||||||
|
### 2 Schema builder (group "2 Schema builder", 16 states)
|
||||||
|
|
||||||
|
Route: `/schema/new, /schema/:key`. API: POST /v1/content-type, GET/PUT /v1/content-type/{key}. Auth: Owner or admin.
|
||||||
|
|
||||||
|
One screen, three regions: type name and key on top, ordered field list on the left, field inspector on the right, collapsible API preview at the bottom. Mobile: the list is the page, the inspector is a 92% sheet, the API preview is a sheet. Field keys and types of saved fields are locked; fields added since the last save can still choose both.
|
||||||
|
|
||||||
|
| # | State | Trigger | Copy | Scope |
|
||||||
|
|---|---|---|---|---|
|
||||||
|
| 1 | New type | /schema/new. One starter field is added because a type needs at least one. | New content type · Name · For example, Events · Key · events · Used in URLs and the API. Lowercase letters, digits and hyphens. It can't change after you save. · Fields · 1 of 50 · Add field · Field: Title · Label · Key · The name used in the API. Starts with a letter. Lowercase letters, digits and underscores. · Type · Required · An entry can't be saved with this field empty. · Unique values · Default value · Used when an entry is created and this field is left out. · Shortest · Longest · Counted in characters. Entries show a counter. · Save · Discard | Available now |
|
||||||
|
| 2 | Editing an existing type | /schema/events with 37 entries. Key is locked, saved field keys and types are locked. | 37 entries use this content type. Changes are checked against them when you save. · Key (lock) · Used in the API, so it can't change. · Can't change after saving · Saved | Available now |
|
||||||
|
| 3 | Locked key: tooltip | Hover or focus the locked key. | The key is used in URLs and the API, so it can't change after the type is created. | Available now |
|
||||||
|
| 4 | Unsaved changes | Two fields added, Capacity changed, Description removed. Rows carry New and Changed badges; removal shows an undo row. | Unsaved changes · New · Changed · Description will be removed · Undo · Save · Discard | Available now |
|
||||||
|
| 5 | Field errors | Checked as the user types, and again on Save. The row is outlined and shows an alert icon. Save is disabled until all are fixed. | 3 problems to fix · Give the field a label. · Lowest value can't be above the highest value. · Choices can't be blank. · Two choices are the same. | Available now |
|
||||||
|
| 6 | Type-level errors | New type with no name, a one-letter key and no fields. | Give the content type a name. · Use 2 to 40 lowercase letters, digits or hyphens. · No fields yet · A content type needs at least one field. · 3 problems to fix | Available now |
|
||||||
|
| 7 | Field key error | A field added since the last save has an invalid key (hyphen). Checked as the user types. Field keys use underscores; type keys use hyphens. | Key · Start with a letter. Use lowercase letters, digits and underscores. · 1 problem to fix | Available now |
|
||||||
|
| 8 | Choice list editor | A Choice field is selected. Add, remove and reorder; blanks and duplicates are flagged per row. | Choices · 5 of 50 · Add a choice · Add · Add 1 to 50 choices. Each one needs a different name. Removing a choice that entries use will be refused when you save. · Choices can't be blank. · Two choices are the same. | Available now |
|
||||||
|
| 9 | Keyboard reorder | Focus the grip, press Space. Up and Down move, Space drops, Esc cancels. Move up, Move down and Remove buttons are on the selected row. | Moving Ends on. Position 2 of 7. Press Up or Down to move, Space to drop, Esc to cancel. (live region, polite) | Available now |
|
||||||
|
| 10 | API preview open | The panel at the bottom. Updates as fields change. Copy JSON copies the sample entry. | API preview · Where entries of this type live · A sample entry. Values come from each field's type and default. · Updates as you edit. Fields you add or remove here appear after you save. · Copy JSON · Copied | Available now |
|
||||||
|
| 11 | Saving | PUT in flight. Inputs dim, Save shows the loader, nothing can be dragged. | Saving… | Available now |
|
||||||
|
| 12 | Saved | 200. A toast confirms, the badges clear. | Saved at 11:02 · Content type saved · Events now has 8 fields. | Available now |
|
||||||
|
| 13 | Save failed | 500 or network failure. Nothing was sent as saved; the edits stay. | Save failed · Couldn't save the content type · Something went wrong on our side. Your changes are still here. Try again in a moment. · Try again | Available now |
|
||||||
|
| 14 | Key already taken | 409 content_type_key_taken on POST. | The key "events" is already used by another content type. Choose a different key. | Available now |
|
||||||
|
| 15 | Schema incompatible | 409 schema_incompatible on PUT. The review dialog (group 3) closes into this state. Changes of the kinds that can cause it are marked. | Nothing was changed · Some entries don't fit the new fields, so the whole change was refused. RenewCMS can't tell which entries. The changes that can cause this are marked. · Review changes · Possible cause | Available now |
|
||||||
|
| 16 | Offline | navigator.onLine is false. Edits are kept; Save is disabled. | You're offline. Changes will be saved when you reconnect. · Waiting for connection | Available now |
|
||||||
|
|
||||||
|
### 3 Schema change review and delete type (group "3 Review and delete", 7 states)
|
||||||
|
|
||||||
|
Route: `/schema/:key (dialogs)`. API: PUT /v1/content-type/{key}, DELETE /v1/content-type/{key}. Auth: Owner or admin.
|
||||||
|
|
||||||
|
The review opens on Save when the type already has entries (37 here). It is informational: the server decides compatibility. Destructive changes (removing a field or a choice, tightening a limit, making a field unique or required) carry a warning flag. Per-change entry counts and a full diff are later.
|
||||||
|
|
||||||
|
| # | State | Trigger | Copy | Scope |
|
||||||
|
|---|---|---|---|---|
|
||||||
|
| 1 | Review before saving | Save on a type that has entries. | Review changes to Events · Apply them to save the content type. · Add 2 fields, change 1, remove 1 · Events has 37 entries. Each one is checked against the new fields when you apply. · Add Speaker · Text, optional. · Add Room · Choice, required, default "Main hall". Existing entries get the default, so they still fit. · Change Capacity · Highest value goes from 5000 to 2000. · Entries may not fit · Remove Description · Entries stop returning its values. · Removes data · Flagged changes can be refused if existing entries don't fit. If that happens, nothing is changed. · Back to editing · Apply changes | Available now |
|
||||||
|
| 2 | Applying | PUT in flight. Dialog cannot be dismissed. | Applying… | Available now |
|
||||||
|
| 3 | Refused (schema_incompatible) | 409 schema_incompatible. States that nothing changed and names the kind of change that likely caused it, never an entry. | Nothing was changed · RenewCMS refused the changes because some entries don't fit the new fields. It doesn't say which entries. · Your content type is as it was · No field was added, changed or removed. · The change that can cause this in your edit · Possible cause · This kind of change is refused when an entry is over the new limit, a new required field has no default, a field becomes unique while entries share a value, or a removed choice is still in use. · Discard changes · Back to editing | Available now |
|
||||||
|
| 4 | Review with counts and diff | Per-change entry counts and a full diff need an API that does not exist yet. | Affects 0 entries · Affects 37 entries · Affects 3 entries · Affects 31 entries · View full diff · Per-change counts and diff come later | Later |
|
||||||
|
| 5 | Delete type: blocked | Delete content type on a type with entries. No confirm button. | You can't delete Events yet · A content type can only be deleted when it has no entries. · Events has 37 entries · Delete all of its entries first, then delete the content type. · Close · View entries | Available now |
|
||||||
|
| 6 | Delete type: confirm | Delete content type on an empty type. | Delete Recipes? · Recipes has no entries. Its fields and its API routes will be deleted. This can't be undone. · Key: recipes · Cancel · Delete content type | Available now |
|
||||||
|
| 7 | Delete type: server fallback (409) | 409 content_type_has_entries. An entry was added after the page loaded. | Recipes now has entries · Someone added an entry after this page loaded, so nothing was deleted. Delete the entries first, then try again. · Close · View entries | Available now |
|
||||||
|
|
||||||
|
### 4 Field-type gallery (group "4 Field types", 6 states)
|
||||||
|
|
||||||
|
Route: `reference board`. API: none. Auth: n/a.
|
||||||
|
|
||||||
|
One frame per type: inspector options, the entry form control (default and open states), the list cell with its empty state, the error message for each rule, and the filter widget. Filters are later: filtering on custom fields is not in the API. Mobile drops the inspector column (the builder frames show it as a sheet).
|
||||||
|
|
||||||
|
| # | State | Trigger | Copy | Scope |
|
||||||
|
|---|---|---|---|---|
|
||||||
|
| 1 | Text | type: "text" | Text · Short text, like a title or a name · Shortest · Longest · characters · 74 / 80 · Fill in Title. · Title must be text. · Title needs at least 3 characters. · Title can be up to 80 characters. · Another entry already uses this Title. Enter a different one. | Available now |
|
||||||
|
| 2 | Rich text | type: "richtext" | Rich text · Long text with formatting, written in Markdown · Write · Preview · Markdown. Switch to Preview to check the result. · 86 / 5000 · Not available for rich text. (Unique) | Available now |
|
||||||
|
| 3 | Number | type: "number" | Number · Whole or decimal numbers · Lowest value · Highest value · Enter a number · Between 1 and 5000. · Description must be a number. · Capacity must be at least 1. · Capacity must be at most 5000. | Available now |
|
||||||
|
| 4 | Yes or no | type: "boolean" | Yes or no · An on or off switch · On by default · Yes or no fields have no limits. · Not available for yes or no fields. (Unique) · Choose yes or no for Online. · Online must be yes or no. | Available now |
|
||||||
|
| 5 | Date | type: "date" | Date · A calendar day, without a time · Earliest date · Latest date · Pick a date · Pick a date for Starts on. · Starts on must be a date, like 2026-11-21. · Starts on can't be before 1 Jan 2026. · Starts on can't be after 31 Dec 2027. | Available now |
|
||||||
|
| 6 | Choice | type: "select" | Choice · One option from a list you define · Choices · Choose an option · Choose one of: Talk, Workshop or Meetup. · Another entry already uses this choice for Category. | Available now |
|
||||||
|
|
||||||
|
## 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.
|
||||||
@@ -14,6 +14,7 @@
|
|||||||
<sc-for list="{{ nav }}" as="n" hint-placeholder-count="3">
|
<sc-for list="{{ nav }}" as="n" hint-placeholder-count="3">
|
||||||
<div data-act="nav-{{ n.key }}" style="display:flex;align-items:center;gap:10px;height:32px;padding:0 10px;background:{{ n.bg }};color:{{ n.fg }};font-weight:{{ n.fw }}"><span aria-hidden="true" style="display:inline-block;width:16px;height:16px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/{{ n.icon }}.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/{{ n.icon }}.svg') center / contain no-repeat"></span>{{ n.t }}<sc-if value="{{ n.badge }}"><span style="margin-left:auto;height:18px;padding:0 6px;display:inline-flex;align-items:center;background:var(--ui-info);color:var(--ui-bg);font:500 11px 'IBM Plex Sans',sans-serif">Update</span></sc-if><sc-if value="{{ n.chev }}"><span aria-hidden="true" style="margin-left:{{ n.chevML }};display:inline-block;flex-shrink:0;width:14px;height:14px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/{{ n.chev }}.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/{{ n.chev }}.svg') center / contain no-repeat"></span></sc-if></div><sc-if value="{{ n.sub }}"><div style="display:flex;flex-direction:column;gap:2px;margin-left:19px;border-left:1px solid var(--ui-border)"><span style="padding:6px 10px 2px 12px;font-size:11px;line-height:16px;font-weight:600;letter-spacing:.04em;text-transform:uppercase;color:var(--ui-text-muted)">Media</span><sc-for list="{{ n.subs }}" as="x" hint-placeholder-count="2"><div data-act="nav-{{ x.t }}" style="display:flex;align-items:center;gap:10px;height:32px;padding:0 10px 0 12px;background:{{ x.bg }};color:{{ x.fg }};font-weight:{{ x.fw }}"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:14px;height:14px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/{{ x.ic }}.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/{{ x.ic }}.svg') center / contain no-repeat"></span>{{ x.t }}</div></sc-for><sc-if value="{{ n.hasSites }}"><span style="padding:6px 10px 2px 12px;font-size:11px;line-height:16px;font-weight:600;letter-spacing:.04em;text-transform:uppercase;color:var(--ui-text-muted)">Publishing</span></sc-if><sc-for list="{{ n.subs2 }}" as="x2" hint-placeholder-count="1"><div data-act="nav-{{ x2.t }}" style="display:flex;align-items:center;gap:10px;height:32px;padding:0 10px 0 12px;background:{{ x2.bg }};color:{{ x2.fg }};font-weight:{{ x2.fw }}"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:14px;height:14px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/{{ x2.ic }}.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/{{ x2.ic }}.svg') center / contain no-repeat"></span>{{ x2.t }}</div></sc-for></div></sc-if>
|
<div data-act="nav-{{ n.key }}" style="display:flex;align-items:center;gap:10px;height:32px;padding:0 10px;background:{{ n.bg }};color:{{ n.fg }};font-weight:{{ n.fw }}"><span aria-hidden="true" style="display:inline-block;width:16px;height:16px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/{{ n.icon }}.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/{{ n.icon }}.svg') center / contain no-repeat"></span>{{ n.t }}<sc-if value="{{ n.badge }}"><span style="margin-left:auto;height:18px;padding:0 6px;display:inline-flex;align-items:center;background:var(--ui-info);color:var(--ui-bg);font:500 11px 'IBM Plex Sans',sans-serif">Update</span></sc-if><sc-if value="{{ n.chev }}"><span aria-hidden="true" style="margin-left:{{ n.chevML }};display:inline-block;flex-shrink:0;width:14px;height:14px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/{{ n.chev }}.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/{{ n.chev }}.svg') center / contain no-repeat"></span></sc-if></div><sc-if value="{{ n.sub }}"><div style="display:flex;flex-direction:column;gap:2px;margin-left:19px;border-left:1px solid var(--ui-border)"><span style="padding:6px 10px 2px 12px;font-size:11px;line-height:16px;font-weight:600;letter-spacing:.04em;text-transform:uppercase;color:var(--ui-text-muted)">Media</span><sc-for list="{{ n.subs }}" as="x" hint-placeholder-count="2"><div data-act="nav-{{ x.t }}" style="display:flex;align-items:center;gap:10px;height:32px;padding:0 10px 0 12px;background:{{ x.bg }};color:{{ x.fg }};font-weight:{{ x.fw }}"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:14px;height:14px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/{{ x.ic }}.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/{{ x.ic }}.svg') center / contain no-repeat"></span>{{ x.t }}</div></sc-for><sc-if value="{{ n.hasSites }}"><span style="padding:6px 10px 2px 12px;font-size:11px;line-height:16px;font-weight:600;letter-spacing:.04em;text-transform:uppercase;color:var(--ui-text-muted)">Publishing</span></sc-if><sc-for list="{{ n.subs2 }}" as="x2" hint-placeholder-count="1"><div data-act="nav-{{ x2.t }}" style="display:flex;align-items:center;gap:10px;height:32px;padding:0 10px 0 12px;background:{{ x2.bg }};color:{{ x2.fg }};font-weight:{{ x2.fw }}"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:14px;height:14px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/{{ x2.ic }}.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/{{ x2.ic }}.svg') center / contain no-repeat"></span>{{ x2.t }}</div></sc-for></div></sc-if>
|
||||||
</sc-for>
|
</sc-for>
|
||||||
|
<sc-if value="{{ contentShow }}"><div style="display:flex;flex-direction:column;gap:2px;margin-top:8px"><span style="padding:6px 10px 2px;font-size:11px;line-height:16px;font-weight:600;letter-spacing:.04em;text-transform:uppercase;color:var(--ui-text-muted)">Content</span><sc-if value="{{ contentColl }}"><div style="display:flex;align-items:center;gap:10px;height:32px;padding:0 10px;color:var(--ui-text-toned)"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:16px;height:16px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/layers.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/layers.svg') center / contain no-repeat"></span><span style="flex:1">All content types</span><span style="font-size:12px;color:var(--ui-text-muted)">{{ contentCount }}</span><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:14px;height:14px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/chevron-right.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/chevron-right.svg') center / contain no-repeat"></span></div></sc-if><sc-for list="{{ contentRows }}" as="c" hint-placeholder-count="3"><div data-act="nav-content-{{ c.key }}" title="{{ c.name }}" style="display:flex;align-items:center;gap:10px;height:32px;padding:0 10px;background:{{ c.bg }};color:{{ c.fg }};font-weight:{{ c.fw }}"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:16px;height:16px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/{{ c.icon }}.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/{{ c.icon }}.svg') center / contain no-repeat"></span><span style="flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap">{{ c.name }}</span></div></sc-for><sc-if value="{{ contentMore }}"><div style="display:flex;align-items:center;gap:10px;height:32px;padding:0 10px;color:var(--ui-text-muted)"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:16px;height:16px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/ellipsis.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/ellipsis.svg') center / contain no-repeat"></span><span>{{ contentMore }}</span></div></sc-if></div></sc-if>
|
||||||
<div style="flex:1"></div>
|
<div style="flex:1"></div>
|
||||||
<sc-if value="{{ s.boot }}"><div style="display:flex;align-items:center;gap:10px;height:40px;padding:0 6px"><span style="width:26px;height:26px;background:var(--ui-bg-accented)"></span><span style="width:80px;height:12px;background:var(--ui-bg-accented)"></span></div></sc-if>
|
<sc-if value="{{ s.boot }}"><div style="display:flex;align-items:center;gap:10px;height:40px;padding:0 6px"><span style="width:26px;height:26px;background:var(--ui-bg-accented)"></span><span style="width:80px;height:12px;background:var(--ui-bg-accented)"></span></div></sc-if>
|
||||||
<sc-if value="{{ notBoot }}"><div data-act="usermenu" role="button" aria-haspopup="menu" aria-expanded="{{ menuOpen }}" title="Account" style="display:flex;align-items:center;gap:10px;height:40px;padding:0 6px;background:{{ chipBg }};color:{{ chipFg }}"><span style="width:26px;height:26px;flex-shrink:0;background:var(--rc-sand);color:var(--rc-on-sand);display:flex;align-items:center;justify-content:center;font:600 11px 'IBM Plex Sans',sans-serif">{{ ini }}</span><span style="flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-weight:500">{{ who }}</span><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:14px;height:14px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/chevrons-up-down.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/chevrons-up-down.svg') center / contain no-repeat"></span></div></sc-if>
|
<sc-if value="{{ notBoot }}"><div data-act="usermenu" role="button" aria-haspopup="menu" aria-expanded="{{ menuOpen }}" title="Account" style="display:flex;align-items:center;gap:10px;height:40px;padding:0 6px;background:{{ chipBg }};color:{{ chipFg }}"><span style="width:26px;height:26px;flex-shrink:0;background:var(--rc-sand);color:var(--rc-on-sand);display:flex;align-items:center;justify-content:center;font:600 11px 'IBM Plex Sans',sans-serif">{{ ini }}</span><span style="flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-weight:500">{{ who }}</span><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:14px;height:14px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/chevrons-up-down.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/chevrons-up-down.svg') center / contain no-repeat"></span></div></sc-if>
|
||||||
@@ -368,7 +369,7 @@
|
|||||||
</sc-if>
|
</sc-if>
|
||||||
|
|
||||||
{{ purgeDlg }}
|
{{ purgeDlg }}
|
||||||
<sc-if value="{{ navDrawer }}"><div data-act="mnav-close" style="position:absolute;inset:0;z-index:60;display:flex;background:var(--rc-overlay)"><div role="navigation" aria-label="Main" style="width:300px;max-width:85%;height:100%;background:var(--ui-bg);box-shadow:var(--rc-shadow-modal);display:flex;flex-direction:column;padding:12px;gap:2px"><div style="display:flex;align-items:center;gap:10px;height:40px;padding:0 6px;margin-bottom:10px"><svg width="26" height="26" viewBox="0 0 16 16" shape-rendering="crispEdges"><rect width="16" height="16" fill="#111"></rect><path fill="#fff" fill-rule="evenodd" d="M4 3h6v1h1v1h1v3h-1v1h-1v1h1v1h1v2h-2v-2h-1v-1H6v3H4zm2 2v3h4V5z"></path></svg><span style="flex:1;font-weight:600;font-size:14px;color:var(--ui-text-highlighted)">RenewCMS</span></div><sc-for list="{{ nav }}" as="n" hint-placeholder-count="3"><div data-act="nav-{{ n.key }}" style="display:flex;align-items:center;gap:10px;height:44px;padding:0 10px;background:{{ n.bg }};color:{{ n.fg }};font-weight:{{ n.fw }}"><span aria-hidden="true" style="display:inline-block;width:16px;height:16px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/{{ n.icon }}.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/{{ n.icon }}.svg') center / contain no-repeat"></span><span style="flex:1">{{ n.t }}</span><sc-if value="{{ n.chev }}"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:14px;height:14px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/{{ n.chev }}.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/{{ n.chev }}.svg') center / contain no-repeat"></span></sc-if></div><sc-if value="{{ n.sub }}"><div style="display:flex;flex-direction:column;gap:2px;margin-left:19px;border-left:1px solid var(--ui-border)"><span style="padding:6px 10px 2px 12px;font-size:11px;line-height:16px;font-weight:600;letter-spacing:.04em;text-transform:uppercase;color:var(--ui-text-muted)">Media</span><sc-for list="{{ n.subs }}" as="x" hint-placeholder-count="2"><div data-act="nav-{{ x.t }}" style="display:flex;align-items:center;gap:10px;height:44px;padding:0 10px 0 12px;background:{{ x.bg }};color:{{ x.fg }};font-weight:{{ x.fw }}"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:14px;height:14px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/{{ x.ic }}.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/{{ x.ic }}.svg') center / contain no-repeat"></span>{{ x.t }}</div></sc-for><sc-if value="{{ n.hasSites }}"><span style="padding:6px 10px 2px 12px;font-size:11px;line-height:16px;font-weight:600;letter-spacing:.04em;text-transform:uppercase;color:var(--ui-text-muted)">Publishing</span></sc-if><sc-for list="{{ n.subs2 }}" as="x2" hint-placeholder-count="1"><div data-act="nav-{{ x2.t }}" style="display:flex;align-items:center;gap:10px;height:44px;padding:0 10px 0 12px;background:{{ x2.bg }};color:{{ x2.fg }};font-weight:{{ x2.fw }}"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:14px;height:14px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/{{ x2.ic }}.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/{{ x2.ic }}.svg') center / contain no-repeat"></span>{{ x2.t }}</div></sc-for></div></sc-if></sc-for><div style="flex:1"></div><div style="display:flex;align-items:center;gap:10px;height:44px;padding:0 6px;color:var(--ui-text-highlighted)"><span style="width:26px;height:26px;flex-shrink:0;background:var(--rc-sand);color:var(--rc-on-sand);display:flex;align-items:center;justify-content:center;font:600 11px 'IBM Plex Sans',sans-serif">{{ ini }}</span><span style="flex:1;font-weight:500">{{ who }}</span></div></div></div></sc-if>
|
<sc-if value="{{ navDrawer }}"><div data-act="mnav-close" style="position:absolute;inset:0;z-index:60;display:flex;background:var(--rc-overlay)"><div role="navigation" aria-label="Main" style="width:300px;max-width:85%;height:100%;background:var(--ui-bg);box-shadow:var(--rc-shadow-modal);display:flex;flex-direction:column;padding:12px;gap:2px"><div style="display:flex;align-items:center;gap:10px;height:40px;padding:0 6px;margin-bottom:10px"><svg width="26" height="26" viewBox="0 0 16 16" shape-rendering="crispEdges"><rect width="16" height="16" fill="#111"></rect><path fill="#fff" fill-rule="evenodd" d="M4 3h6v1h1v1h1v3h-1v1h-1v1h1v1h1v2h-2v-2h-1v-1H6v3H4zm2 2v3h4V5z"></path></svg><span style="flex:1;font-weight:600;font-size:14px;color:var(--ui-text-highlighted)">RenewCMS</span></div><sc-for list="{{ nav }}" as="n" hint-placeholder-count="3"><div data-act="nav-{{ n.key }}" style="display:flex;align-items:center;gap:10px;height:44px;padding:0 10px;background:{{ n.bg }};color:{{ n.fg }};font-weight:{{ n.fw }}"><span aria-hidden="true" style="display:inline-block;width:16px;height:16px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/{{ n.icon }}.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/{{ n.icon }}.svg') center / contain no-repeat"></span><span style="flex:1">{{ n.t }}</span><sc-if value="{{ n.chev }}"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:14px;height:14px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/{{ n.chev }}.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/{{ n.chev }}.svg') center / contain no-repeat"></span></sc-if></div><sc-if value="{{ n.sub }}"><div style="display:flex;flex-direction:column;gap:2px;margin-left:19px;border-left:1px solid var(--ui-border)"><span style="padding:6px 10px 2px 12px;font-size:11px;line-height:16px;font-weight:600;letter-spacing:.04em;text-transform:uppercase;color:var(--ui-text-muted)">Media</span><sc-for list="{{ n.subs }}" as="x" hint-placeholder-count="2"><div data-act="nav-{{ x.t }}" style="display:flex;align-items:center;gap:10px;height:44px;padding:0 10px 0 12px;background:{{ x.bg }};color:{{ x.fg }};font-weight:{{ x.fw }}"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:14px;height:14px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/{{ x.ic }}.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/{{ x.ic }}.svg') center / contain no-repeat"></span>{{ x.t }}</div></sc-for><sc-if value="{{ n.hasSites }}"><span style="padding:6px 10px 2px 12px;font-size:11px;line-height:16px;font-weight:600;letter-spacing:.04em;text-transform:uppercase;color:var(--ui-text-muted)">Publishing</span></sc-if><sc-for list="{{ n.subs2 }}" as="x2" hint-placeholder-count="1"><div data-act="nav-{{ x2.t }}" style="display:flex;align-items:center;gap:10px;height:44px;padding:0 10px 0 12px;background:{{ x2.bg }};color:{{ x2.fg }};font-weight:{{ x2.fw }}"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:14px;height:14px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/{{ x2.ic }}.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/{{ x2.ic }}.svg') center / contain no-repeat"></span>{{ x2.t }}</div></sc-for></div></sc-if></sc-for><sc-if value="{{ contentShow }}"><div style="display:flex;flex-direction:column;gap:2px;margin-top:8px"><span style="padding:6px 10px 2px;font-size:11px;line-height:16px;font-weight:600;letter-spacing:.04em;text-transform:uppercase;color:var(--ui-text-muted)">Content</span><sc-if value="{{ contentColl }}"><div style="display:flex;align-items:center;gap:10px;height:44px;padding:0 10px;color:var(--ui-text-toned)"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:16px;height:16px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/layers.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/layers.svg') center / contain no-repeat"></span><span style="flex:1">All content types</span><span style="font-size:12px;color:var(--ui-text-muted)">{{ contentCount }}</span><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:14px;height:14px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/chevron-right.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/chevron-right.svg') center / contain no-repeat"></span></div></sc-if><sc-for list="{{ contentRows }}" as="c" hint-placeholder-count="3"><div data-act="nav-content-{{ c.key }}" title="{{ c.name }}" style="display:flex;align-items:center;gap:10px;height:44px;padding:0 10px;background:{{ c.bg }};color:{{ c.fg }};font-weight:{{ c.fw }}"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:16px;height:16px;background-color:currentColor;-webkiLine truncated
|
||||||
<sc-if value="{{ lk.sheet }}"><div style="position:absolute;inset:0;z-index:55;background:var(--rc-overlay);display:flex;align-items:flex-end"><div role="dialog" aria-label="Link" style="width:100%;background:var(--ui-bg);box-shadow:var(--rc-shadow-modal);display:flex;flex-direction:column"><div style="display:flex;justify-content:center;padding-top:8px"><span style="display:block;width:36px;height:4px;background:var(--ui-border-accented)"></span></div><div style="display:flex;flex-direction:column;gap:2px;padding:12px 16px 12px;border-bottom:1px solid var(--ui-border)"><span style="font-weight:600;font-size:16px;line-height:24px;color:var(--ui-text-highlighted)">timber windows</span><span style="font:400 12px/18px 'IBM Plex Mono',monospace;color:var(--ui-text-toned);overflow:hidden;text-overflow:ellipsis;white-space:nowrap">/articles/winter-checklist</span></div><div style="display:flex;flex-direction:column;padding:8px 0 16px"><span style="height:48px;padding:0 16px;display:flex;align-items:center;gap:12px;color:var(--ui-text-highlighted)"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:18px;height:18px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/pencil.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/pencil.svg') center / contain no-repeat"></span>Edit link</span><span style="height:48px;padding:0 16px;display:flex;align-items:center;gap:12px;color:var(--ui-text-highlighted)"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:18px;height:18px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/external-link.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/external-link.svg') center / contain no-repeat"></span>Open link</span><span style="height:48px;padding:0 16px;display:flex;align-items:center;gap:12px;color:var(--ui-error)"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:18px;height:18px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/unlink.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/unlink.svg') center / contain no-repeat"></span>Remove link</span></div></div></div></sc-if>
|
<sc-if value="{{ lk.sheet }}"><div style="position:absolute;inset:0;z-index:55;background:var(--rc-overlay);display:flex;align-items:flex-end"><div role="dialog" aria-label="Link" style="width:100%;background:var(--ui-bg);box-shadow:var(--rc-shadow-modal);display:flex;flex-direction:column"><div style="display:flex;justify-content:center;padding-top:8px"><span style="display:block;width:36px;height:4px;background:var(--ui-border-accented)"></span></div><div style="display:flex;flex-direction:column;gap:2px;padding:12px 16px 12px;border-bottom:1px solid var(--ui-border)"><span style="font-weight:600;font-size:16px;line-height:24px;color:var(--ui-text-highlighted)">timber windows</span><span style="font:400 12px/18px 'IBM Plex Mono',monospace;color:var(--ui-text-toned);overflow:hidden;text-overflow:ellipsis;white-space:nowrap">/articles/winter-checklist</span></div><div style="display:flex;flex-direction:column;padding:8px 0 16px"><span style="height:48px;padding:0 16px;display:flex;align-items:center;gap:12px;color:var(--ui-text-highlighted)"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:18px;height:18px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/pencil.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/pencil.svg') center / contain no-repeat"></span>Edit link</span><span style="height:48px;padding:0 16px;display:flex;align-items:center;gap:12px;color:var(--ui-text-highlighted)"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:18px;height:18px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/external-link.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/external-link.svg') center / contain no-repeat"></span>Open link</span><span style="height:48px;padding:0 16px;display:flex;align-items:center;gap:12px;color:var(--ui-error)"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:18px;height:18px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/unlink.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/unlink.svg') center / contain no-repeat"></span>Remove link</span></div></div></div></sc-if>
|
||||||
<sc-if value="{{ edSheet }}"><div style="position:absolute;inset:0;z-index:55;background:var(--rc-overlay);display:flex;align-items:flex-end"><div role="dialog" aria-modal="true" aria-label="Details" style="width:100%;height:92%;background:var(--ui-bg);box-shadow:var(--rc-shadow-modal);display:flex;flex-direction:column"><div style="display:flex;justify-content:center;padding-top:8px;flex-shrink:0"><span style="display:block;width:36px;height:4px;background:var(--ui-border-accented)"></span></div><div style="padding:8px 16px 0 16px;display:flex;align-items:center;gap:12px;flex-shrink:0"><span style="flex:1;font:600 16px/24px 'IBM Plex Sans',sans-serif;color:var(--ui-text-highlighted)">Details</span><span data-act="modal-close" style="width:44px;height:44px;display:flex;align-items:center;justify-content:center;color:var(--ui-text-muted)"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:16px;height:16px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/x.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/x.svg') center / contain no-repeat"></span></span></div><div style="flex:1;min-height:0;overflow:hidden;padding:12px 16px 16px;display:flex;flex-direction:column;gap:16px"><div style="display:flex;flex-direction:column;gap:12px;padding-bottom:16px;border-bottom:1px solid var(--ui-border)"><div data-act="meta-toggle" role="button" tabindex="0" aria-expanded="{{ metaOpen }}" aria-controls="meta-body" style="display:flex;align-items:center;gap:8px;min-height:24px;color:var(--ui-text-highlighted)"><span style="display:flex;transform:rotate({{ metaRot }})"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:14px;height:14px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/chevron-down.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/chevron-down.svg') center / contain no-repeat"></span></span><span style="font-weight:600;font-size:14px">Site and authors</span></div><sc-if value="{{ metaOpen }}"><div id="meta-body" style="display:flex;flex-direction:column;gap:16px">{{ edMeta }}</div></sc-if><sc-if value="{{ metaClosed }}"><span style="padding-left:22px;color:var(--ui-text-muted);overflow:hidden;text-overflow:ellipsis;white-space:nowrap">{{ metaSummary }}</span></sc-if></div><div style="display:flex;flex-direction:column;gap:12px;padding-bottom:16px;border-bottom:1px solid var(--ui-border)"><div data-act="seo-toggle" role="button" tabindex="0" aria-expanded="{{ seoOpen }}" aria-controls="seo-body" style="display:flex;align-items:center;gap:8px;min-height:24px;color:var(--ui-text-highlighted)"><span style="display:flex;transform:rotate({{ seoRot }})"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:14px;height:14px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/chevron-down.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/chevron-down.svg') center / contain no-repeat"></span></span><span style="font-weight:600;font-size:14px">Search and sharing</span></div><sc-if value="{{ seoOpen }}"><div id="seo-body" style="display:flex;flex-direction:column;gap:12px">{{ edSeo }}</div></sc-if><sc-if value="{{ seoClosed }}"><span style="padding-left:22px;color:{{ seoFg }};overflow:hidden;text-overflow:ellipsis;white-space:nowrap">{{ seoSummary }}</span></sc-if></div><div style="display:grid;grid-template-columns:auto 1fr;gap:8px 12px"><span style="color:var(--ui-text-muted)">Created</span><span>12 Mar 2026, 09:14</span><span style="color:var(--ui-text-muted)">Updated</span><span>Today, 11:02</span><span style="color:var(--ui-text-muted)">ID</span><span style="font-family:'IBM Plex Mono',monospace">12</span></div><div style="display:flex;flex-direction:column;gap:6px"><span style="color:var(--ui-text-muted)">Public API URL</span><span style="padding:6px 8px;background:var(--ui-bg-elevated);font:400 12px 'IBM Plex Mono',monospace">/v1/article/12</span></div></div></div></div></sc-if>
|
<sc-if value="{{ edSheet }}"><div style="position:absolute;inset:0;z-index:55;background:var(--rc-overlay);display:flex;align-items:flex-end"><div role="dialog" aria-modal="true" aria-label="Details" style="width:100%;height:92%;background:var(--ui-bg);box-shadow:var(--rc-shadow-modal);display:flex;flex-direction:column"><div style="display:flex;justify-content:center;padding-top:8px;flex-shrink:0"><span style="display:block;width:36px;height:4px;background:var(--ui-border-accented)"></span></div><div style="padding:8px 16px 0 16px;display:flex;align-items:center;gap:12px;flex-shrink:0"><span style="flex:1;font:600 16px/24px 'IBM Plex Sans',sans-serif;color:var(--ui-text-highlighted)">Details</span><span data-act="modal-close" style="width:44px;height:44px;display:flex;align-items:center;justify-content:center;color:var(--ui-text-muted)"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:16px;height:16px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/x.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/x.svg') center / contain no-repeat"></span></span></div><div style="flex:1;min-height:0;overflow:hidden;padding:12px 16px 16px;display:flex;flex-direction:column;gap:16px"><div style="display:flex;flex-direction:column;gap:12px;padding-bottom:16px;border-bottom:1px solid var(--ui-border)"><div data-act="meta-toggle" role="button" tabindex="0" aria-expanded="{{ metaOpen }}" aria-controls="meta-body" style="display:flex;align-items:center;gap:8px;min-height:24px;color:var(--ui-text-highlighted)"><span style="display:flex;transform:rotate({{ metaRot }})"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:14px;height:14px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/chevron-down.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/chevron-down.svg') center / contain no-repeat"></span></span><span style="font-weight:600;font-size:14px">Site and authors</span></div><sc-if value="{{ metaOpen }}"><div id="meta-body" style="display:flex;flex-direction:column;gap:16px">{{ edMeta }}</div></sc-if><sc-if value="{{ metaClosed }}"><span style="padding-left:22px;color:var(--ui-text-muted);overflow:hidden;text-overflow:ellipsis;white-space:nowrap">{{ metaSummary }}</span></sc-if></div><div style="display:flex;flex-direction:column;gap:12px;padding-bottom:16px;border-bottom:1px solid var(--ui-border)"><div data-act="seo-toggle" role="button" tabindex="0" aria-expanded="{{ seoOpen }}" aria-controls="seo-body" style="display:flex;align-items:center;gap:8px;min-height:24px;color:var(--ui-text-highlighted)"><span style="display:flex;transform:rotate({{ seoRot }})"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:14px;height:14px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/chevron-down.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/chevron-down.svg') center / contain no-repeat"></span></span><span style="font-weight:600;font-size:14px">Search and sharing</span></div><sc-if value="{{ seoOpen }}"><div id="seo-body" style="display:flex;flex-direction:column;gap:12px">{{ edSeo }}</div></sc-if><sc-if value="{{ seoClosed }}"><span style="padding-left:22px;color:{{ seoFg }};overflow:hidden;text-overflow:ellipsis;white-space:nowrap">{{ seoSummary }}</span></sc-if></div><div style="display:grid;grid-template-columns:auto 1fr;gap:8px 12px"><span style="color:var(--ui-text-muted)">Created</span><span>12 Mar 2026, 09:14</span><span style="color:var(--ui-text-muted)">Updated</span><span>Today, 11:02</span><span style="color:var(--ui-text-muted)">ID</span><span style="font-family:'IBM Plex Mono',monospace">12</span></div><div style="display:flex;flex-direction:column;gap:6px"><span style="color:var(--ui-text-muted)">Public API URL</span><span style="padding:6px 8px;background:var(--ui-bg-elevated);font:400 12px 'IBM Plex Mono',monospace">/v1/article/12</span></div></div></div></div></sc-if>
|
||||||
{{ slotOverlays }}
|
{{ slotOverlays }}
|
||||||
@@ -387,9 +388,10 @@ class Component extends DCLogic {
|
|||||||
const s = this.props.s || {}
|
const s = this.props.s || {}
|
||||||
const m = !!this.props.mobile
|
const m = !!this.props.mobile
|
||||||
const k = s.kind || 'home'
|
const k = s.kind || 'home'
|
||||||
const navItems = s.role === 'user' ? [['home', 'house', 'Home'], ['articles', 'file-text', 'Articles'], ['media', 'images', 'Media'], ['authors', 'feather', 'Authors'], ['activity', 'history', 'Activity']] : [['home', 'house', 'Home'], ['articles', 'file-text', 'Articles'], ['media', 'images', 'Media'], ['authors', 'feather', 'Authors'], ['users', 'users', 'Users'], ['activity', 'history', 'Activity'], ['integration', 'plug', 'Integration'], ['settings', 'settings', 'Settings']]
|
const navItems = s.role === 'user' ? [['home', 'house', 'Home'], ['articles', 'file-text', 'Articles'], ['media', 'images', 'Media'], ['authors', 'feather', 'Authors'], ['activity', 'history', 'Activity']] : [['home', 'house', 'Home'], ['articles', 'file-text', 'Articles'], ['media', 'images', 'Media'], ['authors', 'feather', 'Authors'], ['users', 'users', 'Users'], ['schema', 'shapes', 'Schema'], ['activity', 'history', 'Activity'], ['integration', 'plug', 'Integration'], ['settings', 'settings', 'Settings']]
|
||||||
const cr0 = s.crumbs || [], setOpen = s.nav === 'settings' || !!s.sideOpen, parentOn = (key) => s.nav === key && (key !== 'settings' || cr0.length <= 1)
|
const cr0 = s.crumbs || [], setOpen = s.nav === 'settings' || !!s.sideOpen, parentOn = (key) => s.nav === key && (key !== 'settings' || cr0.length <= 1)
|
||||||
const nav = navItems.map(([key, icon, t]) => { const on = parentOn(key), open = key === 'settings' && setOpen; return { key, icon, t, bg: on ? 'var(--rc-sand)' : 'transparent', badge: key === 'settings' && !!s.navBadge, fg: on ? 'var(--rc-on-sand)' : open ? 'var(--ui-text-highlighted)' : 'var(--ui-text-toned)', fw: on || open ? 500 : 400, chev: key === 'settings' ? (open ? 'chevron-down' : 'chevron-right') : '', chevML: key === 'settings' && s.navBadge ? '8px' : 'auto', sub: open, hasSites: !s.role || s.role === 'owner', subs2: (!s.role || s.role === 'owner') ? (() => { const o = cr0[cr0.length - 1] === 'Sites'; return [{ t: 'Sites', ic: 'globe', bg: o ? 'var(--rc-sand)' : 'transparent', fg: o ? 'var(--rc-on-sand)' : 'var(--ui-text-toned)', fw: o ? 500 : 400 }] })() : [], subs: ['Variants', 'Cache'].map(x => { const o = cr0[cr0.length - 1] === x; return { t: x, ic: x === 'Variants' ? 'layers' : 'database', bg: o ? 'var(--rc-sand)' : 'transparent', fg: o ? 'var(--rc-on-sand)' : 'var(--ui-text-toned)', fw: o ? 500 : 400 } }) } })
|
const nav = navItems.map(([key, icon, t]) => { const on = parentOn(key), open = key === 'settings' && setOpen; return { key, icon, t, bg: on ? 'var(--rc-sand)' : 'transparent', badge: key === 'settings' && !!s.navBadge, fg: on ? 'var(--rc-on-sand)' : open ? 'var(--ui-text-highlighted)' : 'var(--ui-text-toned)', fw: on || open ? 500 : 400, chev: key === 'settings' ? (open ? 'chevron-down' : 'chevron-right') : '', chevML: key === 'settings' && s.navBadge ? '8px' : 'auto', sub: open, hasSites: !s.role || s.role === 'owner', subs2: (!s.role || s.role === 'owner') ? (() => { const o = cr0[cr0.length - 1] === 'Sites'; return [{ t: 'Sites', ic: 'globe', bg: o ? 'var(--rc-sand)' : 'transparent', fg: o ? 'var(--rc-on-sand)' : 'var(--ui-text-toned)', fw: o ? 500 : 400 }] })() : [], subs: ['Variants', 'Cache'].map(x => { const o = cr0[cr0.length - 1] === x; return { t: x, ic: x === 'Variants' ? 'layers' : 'database', bg: o ? 'var(--rc-sand)' : 'transparent', fg: o ? 'var(--rc-on-sand)' : 'var(--ui-text-toned)', fw: o ? 500 : 400 } }) } })
|
||||||
|
const CT = s.content || [], ctOn = s.contentOn, ctMax = 5, ctVis = CT.slice(0, Math.max(ctMax, CT.findIndex(x => x.key === ctOn) + 1)), contentRows = (m ? (s.contentOpen ? ctVis : []) : ctVis).map(x => { const on = x.key === ctOn; return { key: x.key, name: x.name, icon: x.icon || 'file-text', bg: on ? 'var(--rc-sand)' : 'transparent', fg: on ? 'var(--rc-on-sand)' : 'var(--ui-text-toned)', fw: on ? 500 : 400 } })
|
||||||
const crumbs = (s.crumbs || []).map((t, i, a) => ({ t, sep: i > 0, fg: i === a.length - 1 ? 'var(--ui-text-highlighted)' : 'var(--ui-text-muted)', fw: i === a.length - 1 ? 500 : 400 }))
|
const crumbs = (s.crumbs || []).map((t, i, a) => ({ t, sep: i > 0, fg: i === a.length - 1 ? 'var(--ui-text-highlighted)' : 'var(--ui-text-muted)', fw: i === a.length - 1 ? 500 : 400 }))
|
||||||
const L = s.list || {}
|
const L = s.list || {}
|
||||||
const counts = L.counts || [6, 4, 2]
|
const counts = L.counts || [6, 4, 2]
|
||||||
@@ -541,7 +543,7 @@ class Component extends DCLogic {
|
|||||||
chipBg: s.userMenu || s.nav === 'profile' ? 'var(--rc-sand)' : 'transparent', chipFg: s.userMenu || s.nav === 'profile' ? 'var(--rc-on-sand)' : 'var(--ui-text-highlighted)',
|
chipBg: s.userMenu || s.nav === 'profile' ? 'var(--rc-sand)' : 'transparent', chipFg: s.userMenu || s.nav === 'profile' ? 'var(--rc-on-sand)' : 'var(--ui-text-highlighted)',
|
||||||
isSettings: k === 'settings', isProfile: k === 'profile', pfLoading: k === 'profile' && !!pf.loading, pfReady: k === 'profile' && !pf.loading,
|
isSettings: k === 'settings', isProfile: k === 'profile', pfLoading: k === 'profile' && !!pf.loading, pfReady: k === 'profile' && !pf.loading,
|
||||||
upBtnDir: m ? 'column' : 'row', upBtnAlign: m ? 'stretch' : 'flex-start', cardPad: '16px', cardPadX: m ? '16px' : '20px', inH: m ? '44px' : '40px', pfCols: m ? 'minmax(0,1fr)' : 'minmax(0,1fr) minmax(0,1.4fr)', pwDir: m ? 'column' : 'row', pwAlign: m ? 'stretch' : 'flex-end', edTitle, edBody: e.body || '', sampleBody: !e.body, tabs, rows, save, counter, pub, mFields, up, toasts, endpoints, toolbar,
|
upBtnDir: m ? 'column' : 'row', upBtnAlign: m ? 'stretch' : 'flex-start', cardPad: '16px', cardPadX: m ? '16px' : '20px', inH: m ? '44px' : '40px', pfCols: m ? 'minmax(0,1fr)' : 'minmax(0,1fr) minmax(0,1.4fr)', pwDir: m ? 'column' : 'row', pwAlign: m ? 'stretch' : 'flex-end', edTitle, edBody: e.body || '', sampleBody: !e.body, tabs, rows, save, counter, pub, mFields, up, toasts, endpoints, toolbar,
|
||||||
desk: !m, mob: m, notBoot: !s.boot,
|
contentShow: CT.length > 0, contentRows, contentColl: m && !s.contentOpen, contentCount: String(CT.length), contentMore: (!m || s.contentOpen) && CT.length > ctVis.length ? 'Show all ' + CT.length : '', desk: !m, mob: m, notBoot: !s.boot,
|
||||||
fw: m ? '390px' : '1440px', fh: m ? '844px' : '900px', dir: m ? 'column' : 'row',
|
fw: m ? '390px' : '1440px', fh: m ? '844px' : '900px', dir: m ? 'column' : 'row',
|
||||||
mLead: s.mLead || 'menu',
|
mLead: s.mLead || 'menu',
|
||||||
navDrawer: m && !!s.drawer, isSlot: !!this.props.slotBody, slotBody: this.props.slotBody || null, slotOverlays: this.props.slotOverlays || null, isBoot: !!s.boot, isHome: k === 'home' && !s.boot, isList: k === 'articles', isEditor: k === 'editor', isInteg: k === 'integration', isKeys: k === 'apikeys', isError: k === 'error', isUsers: k === 'users',
|
navDrawer: m && !!s.drawer, isSlot: !!this.props.slotBody, slotBody: this.props.slotBody || null, slotOverlays: this.props.slotOverlays || null, isBoot: !!s.boot, isHome: k === 'home' && !s.boot, isList: k === 'articles', isEditor: k === 'editor', isInteg: k === 'integration', isKeys: k === 'apikeys', isError: k === 'error', isUsers: k === 'users',
|
||||||
|
|||||||
@@ -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 }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,79 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html>
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||||
|
<script src="./support.js"></script>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<x-dc>
|
||||||
|
<helmet>
|
||||||
|
<meta name="design_doc_mode" content="canvas">
|
||||||
|
<link rel="icon" href="brand/favicon.svg">
|
||||||
|
<link href="https://fonts.googleapis.com/css2?family=IBM+Plex+Sans:wght@400;500;600&family=IBM+Plex+Mono:wght@400;500&display=swap" rel="stylesheet">
|
||||||
|
<style>body{margin:0;font-family:'IBM Plex Sans',sans-serif;font-size:13px;line-height:20px}*{box-sizing:border-box}a{color:inherit;text-underline-offset:3px}a:hover{opacity:.8}code{font-family:'IBM Plex Mono',monospace;font-size:12px}</style>
|
||||||
|
</helmet>
|
||||||
|
<div ref="{{ rootRef }}" data-screen-label="Schema screens" style="background:var(--rc-canvas);color:var(--ui-text);padding:64px;display:flex;flex-direction:column;gap:72px;width:max-content;min-width:100%">
|
||||||
|
<div style="display:flex;align-items:flex-end;gap:32px;max-width:1400px">
|
||||||
|
<div style="flex:1;display:flex;flex-direction:column;gap:10px">
|
||||||
|
<h1 style="margin:0;font:600 36px/44px 'IBM Plex Sans',sans-serif;letter-spacing:-0.02em;color:var(--ui-text-highlighted)">Screens: custom content types</h1>
|
||||||
|
<p style="margin:0;max-width:900px;font-size:16px;line-height:26px;color:var(--ui-text-toned);text-wrap:pretty">Schema list, builder, change review, field-type gallery, content navigation, entry list and entry editor, plus the later screens: relations, permissions, export and import. Every state at 1440 px (shown at 50%) and 390 px (shown at 75%); the switch shows dark. Each state is tagged <b>Available now</b> or <b>Later</b>. Spec tables at the end: scope, routes, components with their Nuxt UI mapping, errors, needs backend, decisions, accessibility. Same shell, tokens and copy tone as <a href="RenewCMS Screens Back-office.dc.html">the back-office board</a>. 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 role="radiogroup" aria-label="Theme" style="display:flex;border:1px solid var(--ui-border-accented);background:var(--ui-bg)">
|
||||||
|
<sc-for list="{{ modes }}" as="m" hint-placeholder-count="3">
|
||||||
|
<button role="radio" aria-checked="{{ m.on }}" onClick="{{ m.pick }}" style="all:unset;cursor:pointer;height:36px;padding:0 14px;display:flex;align-items:center;font-weight:500;font-size:14px;background:{{ m.bg }};color:{{ m.fg }}" style-focus-visible="outline:2px solid var(--ui-primary);outline-offset:2px">{{ m.label }}</button>
|
||||||
|
</sc-for>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<sc-for list="{{ groups }}" as="g" hint-placeholder-count="9">
|
||||||
|
<section data-screen-label="{{ g.label }}" style="display:flex;flex-direction:column;gap:28px">
|
||||||
|
<div style="display:flex;flex-direction:column;gap:6px;max-width:1100px">
|
||||||
|
<h2 style="margin:0;font:600 28px/36px 'IBM Plex Sans',sans-serif;color:var(--ui-text-highlighted)">{{ g.title }}</h2>
|
||||||
|
<div style="display:flex;gap:16px;flex-wrap:wrap;font:400 14px/22px 'IBM Plex Mono',monospace;color:var(--ui-text-toned)"><span>{{ g.route }}</span><span style="color:var(--ui-text-muted)">{{ g.api }}</span><span style="color:var(--ui-text-muted)">Auth: {{ g.auth }}</span></div>
|
||||||
|
<p style="margin:4px 0 0;font-size:15px;line-height:24px;color:var(--ui-text-toned);text-wrap:pretty">{{ g.note }}</p>
|
||||||
|
</div>
|
||||||
|
<div style="display:flex;flex-wrap:wrap;gap:48px 40px;align-items:flex-start">
|
||||||
|
<sc-for list="{{ g.states }}" as="st" hint-placeholder-count="4">
|
||||||
|
<div style="display:flex;flex-direction:column;gap:12px;width:1037px">
|
||||||
|
<div style="display:flex;flex-direction:column;gap:2px"><span style="font:600 16px/24px 'IBM Plex Sans',sans-serif;color:var(--ui-text-highlighted)">{{ st.name }}<span style="margin-left:10px;padding:1px 6px;border:{{ st.chipBd }};color:var(--ui-text-toned);font:500 11px/16px 'IBM Plex Mono',monospace;vertical-align:middle">{{ st.scopeLabel }}</span></span><span style="font-size:13px;color:var(--ui-text-muted)">{{ st.trigger }}</span></div>
|
||||||
|
<div style="display:flex;gap:24px;align-items:flex-start">
|
||||||
|
<div style="width:720px;height:450px;overflow:hidden;border:1px solid var(--ui-border);flex-shrink:0"><div style="width:1440px;height:900px;zoom:0.5"><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"><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>
|
||||||
|
<p style="margin:0;font-size:12px;line-height:18px;color:var(--ui-text-muted);text-wrap:pretty"><b style="color:var(--ui-text-toned)">Copy:</b> {{ st.copy }}</p>
|
||||||
|
</div>
|
||||||
|
</sc-for>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
</sc-for>
|
||||||
|
<sc-for list="{{ tables }}" as="t" hint-placeholder-count="3">
|
||||||
|
<section style="display:flex;flex-direction:column;gap:10px;max-width:1240px">
|
||||||
|
<h2 style="margin:0;font:600 22px/30px 'IBM Plex Sans',sans-serif;color:var(--ui-text-highlighted)">{{ t.title }}</h2>
|
||||||
|
<div style="background:var(--ui-bg);border:1px solid var(--ui-border)">
|
||||||
|
<div style="display:grid;grid-template-columns:{{ t.tpl }};gap:16px;padding:8px 12px;background:var(--ui-bg-elevated);color:var(--ui-text-muted);font-weight:500"><sc-for list="{{ t.cols }}" as="c" hint-placeholder-count="3"><span>{{ c }}</span></sc-for></div>
|
||||||
|
<sc-for list="{{ t.rows }}" as="r" hint-placeholder-count="4"><div style="display:grid;grid-template-columns:{{ t.tpl }};gap:16px;padding:10px 12px;border-top:1px solid var(--ui-border);line-height:20px"><sc-for list="{{ r.cells }}" as="c" hint-placeholder-count="3"><span style="color:var(--ui-text-highlighted);text-wrap:pretty;overflow-wrap:anywhere">{{ c }}</span></sc-for></div></sc-for>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
</sc-for>
|
||||||
|
</div>
|
||||||
|
</x-dc>
|
||||||
|
<script type="text/x-dc" data-dc-script data-props="{"theme":{"editor":"enum","default":"light","options":["system","light","dark"],"tsType":"string"}}">
|
||||||
|
class Component extends DCLogic {
|
||||||
|
state = { mode: this.props.theme ?? 'light', spec: { groups: [], tables: [] } }
|
||||||
|
rootRef = React.createRef()
|
||||||
|
light = { '--ui-bg': '#ffffff', '--ui-bg-muted': '#fafafa', '--ui-bg-elevated': '#f3f2f0', '--ui-bg-accented': '#e6e4e0', '--ui-bg-inverted': '#111111', '--ui-text-dimmed': '#999999', '--ui-text-muted': '#666666', '--ui-text-toned': '#444444', '--ui-text': '#222222', '--ui-text-highlighted': '#111111', '--ui-text-inverted': '#ffffff', '--ui-border': '#e6e4e0', '--ui-border-muted': '#f3f2f0', '--ui-border-accented': '#8a8783', '--ui-primary': '#111111', '--ui-secondary': '#635643', '--ui-success': '#315b33', '--ui-info': '#34536d', '--ui-warning': '#6c4700', '--ui-error': '#882c21', '--rc-sand': '#e8dfd1', '--rc-sel': '#e8dfd1', '--rc-on-sel': '#111111', '--rc-on-sand': '#111111', '--rc-success-soft': '#eaefea', '--rc-info-soft': '#ebeef0', '--rc-warning-soft': '#f0ede6', '--rc-error-soft': '#f3eae9', '--rc-overlay': 'rgb(10 10 10 / 0.4)', '--rc-shadow-pop': '0 4px 16px rgb(17 17 17 / 0.08), 0 1px 2px rgb(17 17 17 / 0.06)', '--rc-shadow-modal': '0 16px 48px rgb(17 17 17 / 0.18)', '--rc-canvas': '#ecebe8' }
|
||||||
|
dark = { '--ui-bg': '#111111', '--ui-bg-muted': '#0a0a0a', '--ui-bg-elevated': '#1a1a1a', '--ui-bg-accented': '#222222', '--ui-bg-inverted': '#fafafa', '--ui-text-dimmed': '#666666', '--ui-text-muted': '#999999', '--ui-text-toned': '#cfccc7', '--ui-text': '#e6e4e0', '--ui-text-highlighted': '#fafafa', '--ui-text-inverted': '#111111', '--ui-border': '#333333', '--ui-border-muted': '#222222', '--ui-border-accented': '#666666', '--ui-primary': '#fafafa', '--ui-secondary': '#d4c5b0', '--ui-success': '#a3caa3', '--ui-info': '#a5c2db', '--ui-warning': '#dfb67d', '--ui-error': '#fba394', '--rc-sand': '#d4c5b0', '--rc-sel': '#222222', '--rc-on-sel': '#fafafa', '--rc-on-sand': '#111111', '--rc-success-soft': '#1f241f', '--rc-info-soft': '#202428', '--rc-warning-soft': '#2a251e', '--rc-error-soft': '#2c201f', '--rc-overlay': 'rgb(0 0 0 / 0.6)', '--rc-shadow-pop': '0 4px 16px rgb(0 0 0 / 0.5)', '--rc-shadow-modal': '0 16px 48px rgb(0 0 0 / 0.6)', '--rc-canvas': '#1c1c1c' }
|
||||||
|
resolved() { if (this.state.mode === 'system') return window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light'; return this.state.mode }
|
||||||
|
apply() { const el = this.rootRef.current; if (!el) return; const vars = this.resolved() === 'dark' ? this.dark : this.light; for (const k in vars) el.style.setProperty(k, vars[k]); document.body.style.background = vars['--rc-canvas'] }
|
||||||
|
componentDidMount() { this.apply(); import('./schema-spec.js').then(x => this.setState({ spec: { groups: x.groups, tables: x.tables } })).catch(() => {}) }
|
||||||
|
componentDidUpdate(p) { if (p.theme !== this.props.theme && this.props.theme) this.setState({ mode: this.props.theme }); this.apply() }
|
||||||
|
renderVals() {
|
||||||
|
const modes = [['system', 'System'], ['light', 'Light'], ['dark', 'Dark']].map(([k, label]) => { const on = this.state.mode === k; return { label, on, bg: on ? 'var(--ui-primary)' : 'transparent', fg: on ? 'var(--ui-bg)' : 'var(--ui-text-toned)', pick: () => this.setState({ mode: k }) } })
|
||||||
|
const groups = this.state.spec.groups.map(g => ({ ...g, states: g.states.map(s => ({ ...s, 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 })) }))
|
||||||
|
return { rootRef: this.rootRef, modes, groups, tables }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
@@ -0,0 +1,457 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html>
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||||
|
<script src="./support.js"></script>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<x-dc>
|
||||||
|
<sc-if value="{{ framed }}" hint-placeholder-val="{{ true }}"><dc-import name="AppFrame" s="{{ shell }}" mobile="{{ mob }}" slot-body="{{ main }}" slot-overlays="{{ ov }}" hint-size="100%,100%"></dc-import></sc-if>
|
||||||
|
<sc-if value="{{ bare }}"><div style="width:{{ bw }};height:{{ bh }};overflow:hidden;position:relative;background:var(--ui-bg-muted);color:var(--ui-text);font-family:'IBM Plex Sans',sans-serif;font-size:13px;line-height:20px">{{ main }}</div></sc-if>
|
||||||
|
</x-dc>
|
||||||
|
<script type="text/x-dc" data-dc-script data-props="{"$preview":{"width":1440,"height":900},"s":{"editor":null,"tsType":"object"},"mobile":{"editor":null,"tsType":"boolean"}}">
|
||||||
|
class Component extends DCLogic {
|
||||||
|
renderVals() {
|
||||||
|
const s = this.props.s || {}, m = !!this.props.mobile
|
||||||
|
const P = t => Object.fromEntries(t.split(';').filter(x => x.trim()).map(x => { const i = x.indexOf(':'); const k = x.slice(0, i).trim(); return [k.startsWith('--') ? k : k.replace(/-([a-z])/g, (_, c) => c.toUpperCase()), x.slice(i + 1).trim()] }))
|
||||||
|
const h = React.createElement
|
||||||
|
const D = (t, ...c) => h('div', { style: P(t) }, ...c)
|
||||||
|
const S = (t, ...c) => h('span', { style: P(t) }, ...c)
|
||||||
|
const I = (n, z = 16, t = '') => h('span', { 'aria-hidden': 'true', style: { display: 'inline-block', flexShrink: 0, width: z, height: z, backgroundColor: 'currentColor', WebkitMask: 'url("https://api.iconify.design/lucide/' + n + '.svg") center / contain no-repeat', mask: 'url("https://api.iconify.design/lucide/' + n + '.svg") center / contain no-repeat', ...(t ? P(t) : {}) } })
|
||||||
|
const mono = 'font-family:\'IBM Plex Mono\',monospace;'
|
||||||
|
const bh = m ? 44 : 32, ih = m ? 44 : 32, fs = m ? 16 : 13
|
||||||
|
const B = (label, o = {}) => {
|
||||||
|
const k = o.k || 'outline'
|
||||||
|
const bg = k === 'primary' ? 'var(--ui-primary)' : k === 'danger' ? 'var(--ui-error)' : k === 'ghost' ? 'transparent' : 'var(--ui-bg)'
|
||||||
|
const fg = k === 'primary' || k === 'danger' ? 'var(--ui-bg)' : k === 'del' ? 'var(--ui-error)' : 'var(--ui-text-highlighted)'
|
||||||
|
const bd = k === 'primary' || k === 'danger' ? bg : k === 'ghost' ? 'transparent' : 'var(--ui-border-accented)'
|
||||||
|
return S('height:' + (o.h || bh) + 'px;' + (o.w ? 'width:' + o.w + 'px;' : '') + 'padding:0 ' + (o.px ?? 12) + 'px;display:flex;align-items:center;justify-content:center;gap:6px;background:' + bg + ';color:' + fg + ';border:1px solid ' + bd + ';font-weight:500;font-size:' + (o.fs || 13) + 'px;white-space:nowrap;flex-shrink:0;opacity:' + (o.dis ? 0.4 : 1) + ';' + (o.full ? 'flex:1;' : '') + (o.ring ? 'outline:2px solid var(--ui-primary);outline-offset:2px;' : ''), o.icon && I(o.icon, o.z || 16), label)
|
||||||
|
}
|
||||||
|
const IB = (ic, o = {}) => B(null, { k: 'ghost', icon: ic, w: o.w || (m ? 44 : 28), h: o.h || (m ? 44 : 28), px: 0, dis: o.dis, ring: o.ring, z: o.z || 16 })
|
||||||
|
const Alert = (tone, icon, title, text, ...actions) => D('display:flex;gap:10px;padding:12px 14px;background:var(--rc-' + tone + '-soft);color:var(--ui-' + tone + ')', S('display:flex;padding-top:2px', I(icon)), D('flex:1;display:flex;flex-direction:column;gap:8px', D('display:flex;flex-direction:column;gap:2px', S('font-weight:600', title), text && S('color:var(--ui-text-toned);text-wrap:pretty', text)), actions.length > 0 && D('display:flex;gap:8px;flex-wrap:wrap', ...actions.map((a, i) => B(a, { icon: i === 0 && /again|Retry|Reload/.test(a) ? 'rotate-cw' : null, z: 14, h: m ? 44 : 28, fs: 12, px: 10, k: 'outline' })))))
|
||||||
|
const Later = (t = 'Later') => S('align-self:flex-start;height:20px;padding:0 6px;display:inline-flex;align-items:center;border:1px dashed var(--ui-border-accented);color:var(--ui-text-toned);white-space:nowrap;flex-shrink:0;font:500 11px/16px \'IBM Plex Mono\',monospace', t)
|
||||||
|
const BDG = { req: 'border:1px solid var(--ui-border-accented);color:var(--ui-text-toned)', uniq: 'border:1px solid var(--ui-border-accented);color:var(--ui-text-toned)', neu: 'background:var(--rc-sand);color:var(--rc-on-sand)', chg: 'background:var(--rc-info-soft);color:var(--ui-info)', err: 'background:var(--rc-error-soft);color:var(--ui-error)', warn: 'background:var(--rc-warning-soft);color:var(--ui-warning)', built: 'border:1px solid var(--ui-border-accented);color:var(--ui-text-toned)', ok: 'background:var(--rc-success-soft);color:var(--ui-success)' }
|
||||||
|
const Bd = (t, k, ic) => S('height:20px;padding:0 6px;display:inline-flex;align-items:center;gap:4px;font-size:12px;font-weight:500;white-space:nowrap;flex-shrink:0;' + BDG[k], ic && I(ic, 12), t)
|
||||||
|
const Seg = (opts, on, w) => D('display:flex;border:1px solid var(--ui-border-accented);width:' + (w || '100%'), ...opts.map(([k, t]) => S('flex:1;height:' + bh + 'px;padding:0 10px;display:flex;align-items:center;justify-content:center;font-weight:' + (on === k ? 500 : 400) + ';background:' + (on === k ? 'var(--rc-sand)' : 'var(--ui-bg)') + ';color:' + (on === k ? 'var(--rc-on-sand)' : 'var(--ui-text-toned)') + ';font-size:' + fs + 'px', t)))
|
||||||
|
const SwR = (on, lab, help, dis) => D('display:flex;gap:16px;align-items:center;justify-content:space-between;padding:12px 0;border-bottom:1px solid var(--ui-border);opacity:' + (dis ? 0.6 : 1), D('display:flex;flex-direction:column;gap:2px;min-width:0', S('font-weight:500;color:var(--ui-text-highlighted)', lab), help && S('color:var(--ui-text-muted);font-size:12px;line-height:18px;text-wrap:pretty', help)), S('width:32px;height:18px;padding:2px;display:flex;flex-shrink:0;justify-content:' + (on ? 'flex-end' : 'flex-start') + ';background:' + (on ? 'var(--ui-primary)' : 'var(--ui-bg-accented)') + ';' + (on ? '' : 'outline:1px solid var(--ui-border-accented);outline-offset:-1px'), S('width:14px;height:14px;background:var(--ui-bg)')))
|
||||||
|
const Sw = (on, lab, help, dis) => D('display:flex;gap:12px;align-items:flex-start;opacity:' + (dis ? 0.6 : 1), S('width:32px;height:18px;margin-top:2px;padding:2px;display:flex;flex-shrink:0;justify-content:' + (on ? 'flex-end' : 'flex-start') + ';background:' + (on ? 'var(--ui-primary)' : 'var(--ui-bg-accented)') + ';' + (on ? '' : 'outline:1px solid var(--ui-border-accented);outline-offset:-1px'), S('width:14px;height:14px;background:var(--ui-bg)')), D('display:flex;flex-direction:column;gap:2px', lab && S('font-weight:500;color:var(--ui-text-highlighted)', lab), help && S('color:var(--ui-text-muted);font-size:12px;line-height:18px;text-wrap:pretty', help)))
|
||||||
|
const Chk = on => S('width:16px;height:16px;flex-shrink:0;display:inline-flex;align-items:center;justify-content:center;box-sizing:border-box;border:1px solid ' + (on ? 'var(--ui-primary)' : 'var(--ui-border-accented)') + ';background:' + (on ? 'var(--ui-primary)' : 'var(--ui-bg)') + ';color:var(--ui-bg)', on && I('check', 12))
|
||||||
|
const Skel = (w, hh = 14) => S('display:block;height:' + hh + 'px;width:' + w + ';background:var(--ui-bg-accented)')
|
||||||
|
const F = (lab, val, o = {}) => D('display:flex;flex-direction:column;gap:6px;min-width:0', (lab || o.count) && D('display:flex;justify-content:space-between;gap:8px', S('font-weight:500;color:var(--ui-text-highlighted)', lab, o.req && ' *', o.opt && S('font-weight:400;color:var(--ui-text-muted)', ' (optional)')), o.count && S(mono + 'font-size:12px;color:' + (o.countErr ? 'var(--ui-error)' : 'var(--ui-text-muted)'), o.count)),
|
||||||
|
D('display:flex;align-items:' + (o.area ? 'flex-start' : 'center') + ';min-height:' + (o.area ? (m ? 120 : 88) : ih) + 'px;border:1px solid ' + (o.err ? 'var(--ui-error)' : o.focus ? 'var(--ui-primary)' : 'var(--ui-border-accented)') + ';' + (o.err ? 'box-shadow:inset 0 0 0 1px var(--ui-error);' : o.focus ? 'box-shadow:inset 0 0 0 1px var(--ui-primary);' : '') + 'background:' + (o.dis || o.lock ? 'var(--ui-bg-elevated)' : 'var(--ui-bg)') + ';font-size:' + fs + 'px;opacity:' + (o.dis ? 0.6 : 1), o.pre, S('flex:1;min-width:0;padding:' + (o.area ? '8px 10px' : '0 10px') + ';color:' + (o.ph || val === '' ? 'var(--ui-text-muted)' : 'var(--ui-text-highlighted)') + ';' + (o.area ? '' : 'overflow:hidden;text-overflow:ellipsis;white-space:nowrap;') + (o.mono ? mono + 'font-size:' + (m ? 14 : 12) + 'px;' : ''), val === '' && o.phText ? o.phText : val), o.auto && Bd('Auto', 'neu'), o.auto && I('pencil', 14, 'margin:0 10px 0 8px;color:var(--ui-text-muted)'), o.lock && I('lock', 14, 'margin-right:10px;color:var(--ui-text-muted)'), o.sel && I('chevron-down', 14, 'margin-right:10px;color:var(--ui-text-muted)'), o.suffix && S('padding-right:10px;color:var(--ui-text-muted);font-size:12px', o.suffix), o.ico && I(o.ico, 14, 'margin-right:10px;color:var(--ui-text-muted)')),
|
||||||
|
o.err && S('display:flex;gap:6px;align-items:flex-start;color:var(--ui-error);font-size:12px;line-height:18px', I('circle-alert', 14, 'margin-top:2px'), o.err), o.help && S('color:var(--ui-text-muted);font-size:12px;line-height:18px;text-wrap:pretty', o.help))
|
||||||
|
const Shell = (o, body) => D('position:absolute;inset:0;z-index:' + (o.z || 50) + ';background:var(--rc-overlay);display:flex;align-items:' + (m ? 'flex-end' : 'flex-start') + ';justify-content:center;padding:' + (m ? '0' : (o.top || 140) + 'px 16px 16px'),
|
||||||
|
D('width:' + (m ? '100%' : (o.w || 460) + 'px') + ';max-height:100%;background:var(--ui-bg);box-shadow:var(--rc-shadow-modal);display:flex;flex-direction:column', m && D('display:flex;justify-content:center;padding-top:8px;flex-shrink:0', S('display:block;width:36px;height:4px;background:var(--ui-border-accented)')),
|
||||||
|
D('padding:20px 24px 0;display:flex;align-items:flex-start;gap:12px', D('flex:1;display:flex;flex-direction:column;gap:4px', S('font:600 16px/24px \'IBM Plex Sans\',sans-serif;color:var(--ui-text-highlighted)', o.title), o.desc && S('color:var(--ui-text-muted);text-wrap:pretty', o.desc)), o.later && Later(), o.close && S('width:' + (m ? 44 : 28) + 'px;height:' + (m ? 44 : 28) + 'px;display:flex;align-items:center;justify-content:center;color:var(--ui-text-muted)', I('x'))),
|
||||||
|
D('padding:20px 24px 0;display:flex;flex-direction:column;gap:16px;min-height:0;overflow:hidden', body),
|
||||||
|
D('padding:20px 24px;display:flex;flex-direction:' + (m ? 'column-reverse' : 'row') + ';justify-content:flex-end;gap:8px;flex-shrink:0', o.cancel && B(o.cancel, { dis: o.loading }), o.confirm && S('height:' + bh + 'px;padding:0 12px;display:flex;align-items:center;justify-content:center;gap:6px;background:' + (o.tone === 'danger' ? 'var(--ui-error)' : 'var(--ui-primary)') + ';color:var(--ui-bg);font-weight:500;white-space:nowrap;opacity:' + (o.cdis ? 0.4 : 1), o.loading && I('loader-circle'), o.confirm))))
|
||||||
|
const Sheet = (o, body, foot) => D('position:absolute;inset:0;z-index:' + (o.z || 40) + ';display:flex;align-items:flex-end;background:var(--rc-overlay)',
|
||||||
|
D('width:100%;height:92%;background:var(--ui-bg);box-shadow:var(--rc-shadow-modal);display:flex;flex-direction:column', D('display:flex;justify-content:center;padding-top:8px;flex-shrink:0', S('display:block;width:36px;height:4px;background:var(--ui-border-accented)')),
|
||||||
|
D('flex-shrink:0;display:flex;align-items:center;gap:12px;padding:4px 6px 4px 16px;height:56px;border-bottom:1px solid var(--ui-border)', S('flex:1;min-width:0;font:600 16px/24px \'IBM Plex Sans\',sans-serif;color:var(--ui-text-highlighted);overflow:hidden;text-overflow:ellipsis;white-space:nowrap', o.title), o.later && Later(), S('width:44px;height:44px;display:flex;align-items:center;justify-content:center;color:var(--ui-text-muted)', I('x'))),
|
||||||
|
D('flex:1;min-height:0;overflow:hidden;padding:16px;display:flex;flex-direction:column;gap:16px', body), foot && D('flex-shrink:0;padding:12px 16px;border-top:1px solid var(--ui-border);display:flex;gap:8px', foot)))
|
||||||
|
const Toast = (tone, icon, title, text, action) => D('position:absolute;z-index:60;display:flex;gap:10px;padding:12px 14px;background:var(--ui-bg);border:1px solid var(--ui-border);box-shadow:var(--rc-shadow-pop);' + (m ? 'left:16px;right:16px;bottom:' + (s.toastB || 16) + 'px' : 'right:24px;bottom:24px;width:356px'), S('margin-top:2px;display:flex;color:var(--ui-' + tone + ')', I(icon)), D('flex:1;display:flex;flex-direction:column;gap:6px', D('display:flex;flex-direction:column;gap:2px', S('font-weight:600;color:var(--ui-text-highlighted)', title), S('color:var(--ui-text-muted)', text)), action && B(action, { icon: 'rotate-cw', z: 14, h: m ? 44 : 28, fs: 12, px: 10 })), I('x'))
|
||||||
|
const Offline = () => D('flex-shrink:0;display:flex;align-items:center;gap:10px;padding:10px 16px;background:var(--ui-bg-inverted);color:var(--ui-text-inverted)', I('wifi-off'), S('flex:1', 'You\'re offline. Changes will be saved when you reconnect.'))
|
||||||
|
const Tip = t => D('position:absolute;z-index:30;width:260px;padding:8px 10px;background:var(--ui-bg-inverted);color:var(--ui-text-inverted);font-size:12px;line-height:18px;box-shadow:var(--rc-shadow-pop)', t)
|
||||||
|
const Page = (pad, ...c) => D('flex:1;min-width:0;min-height:0;display:flex;flex-direction:column;position:relative;overflow:hidden;padding:' + pad + ';gap:16px', ...c)
|
||||||
|
const Title = (t, sub, ...acts) => D('display:flex;align-items:flex-end;gap:16px;flex-wrap:wrap;flex-shrink:0', D('flex:1;min-width:200px;display:flex;flex-direction:column;gap:2px', !m && S('font:600 20px/28px \'IBM Plex Sans\',sans-serif;color:var(--ui-text-highlighted)', t), sub && S('color:var(--ui-text-muted)', sub)), ...acts)
|
||||||
|
const pad = m ? '16px' : '24px'
|
||||||
|
const Fab = l => m && D('position:absolute;left:16px;right:16px;bottom:16px;height:48px;z-index:5;display:flex;align-items:center;justify-content:center;gap:8px;background:var(--ui-primary);color:var(--ui-bg);font-weight:500;font-size:15px;box-shadow:var(--rc-shadow-pop)', I('plus', 18), l)
|
||||||
|
const Center = (icon, title, text, ...acts) => D('flex:1;display:flex;align-items:center;justify-content:center;padding:24px', D('max-width:420px;display:flex;flex-direction:column;align-items:center;gap:12px;text-align:center', S('width:44px;height:44px;display:flex;align-items:center;justify-content:center;background:var(--ui-bg-elevated);color:var(--ui-text-toned)', I(icon, 20)), S('font:600 24px/32px \'IBM Plex Sans\',sans-serif;color:var(--ui-text-highlighted)', title), S('color:var(--ui-text-muted);text-wrap:pretty', text), D('display:flex;gap:8px', ...acts)))
|
||||||
|
const Empty = (icon, title, text, action) => D('background:var(--ui-bg);border:1px solid var(--ui-border);padding:40px 24px;display:flex;flex-direction:column;align-items:center;gap:12px;text-align:center', S('width:44px;height:44px;display:flex;align-items:center;justify-content:center;background:var(--ui-bg-elevated);color:var(--ui-text-toned)', I(icon, 20)), S('font-weight:600;font-size:15px;color:var(--ui-text-highlighted)', title), S('color:var(--ui-text-muted);max-width:360px;text-wrap:pretty', text), action && B(action, { k: 'primary', icon: 'plus', px: 16 }))
|
||||||
|
|
||||||
|
// ---------- data
|
||||||
|
const FT = { text: ['type', 'Text', 'Short text, like a title or a name'], richtext: ['pilcrow', 'Rich text', 'Long text with formatting, written in Markdown'], number: ['hash', 'Number', 'Whole or decimal numbers'], boolean: ['toggle-left', 'Yes or no', 'An on or off switch'], date: ['calendar', 'Date', 'A calendar day, without a time'], select: ['list', 'Choice', 'One option from a list you define'], media: ['image', 'Media', 'One image from your media library'] }
|
||||||
|
const EV = [
|
||||||
|
{ key: 'title', label: 'Title', type: 'text', req: true, uniq: true, max: 80 }, { key: 'starts_on', label: 'Starts on', type: 'date', req: true }, { key: 'ends_on', label: 'Ends on', type: 'date' },
|
||||||
|
{ key: 'online', label: 'Online', type: 'boolean', def: false }, { key: 'capacity', label: 'Capacity', type: 'number', min: 1, max: 5000 }, { key: 'category', label: 'Category', type: 'select', opts: ['Talk', 'Workshop', 'Meetup'] }, { key: 'description', label: 'Description', type: 'richtext' }].map(f => ({ ...f, saved: true }))
|
||||||
|
const RC = [{ key: 'title', label: 'Title', type: 'text', req: true }, { key: 'servings', label: 'Servings', type: 'number', min: 1 }, { key: 'vegetarian', label: 'Vegetarian', type: 'boolean' }, { key: 'method', label: 'Method', type: 'richtext' }].map(f => ({ ...f, saved: true }))
|
||||||
|
const SPK = { key: 'speaker', label: 'Speaker', type: 'text', isNew: true }, ROOM = { key: 'room', label: 'Room', type: 'select', req: true, def: 'Main hall', opts: ['Main hall', 'Studio'], isNew: true }
|
||||||
|
const CAPC = { ...EV[4], max: 2000, changed: true }
|
||||||
|
const DIRTY = [EV[0], EV[1], EV[2], EV[3], CAPC, EV[5], SPK, ROOM]
|
||||||
|
const CT = n => ['Events', 'Recipes', 'Press mentions', 'Frequently asked questions and answers', 'Job openings', 'Testimonials', 'Suppliers', 'Certifications', 'Case studies', 'Glossary terms', 'Partners', 'Downloads', 'Locations', 'Awards'].slice(0, n).map(x => ({ key: x === 'Events' ? 'events' : x.toLowerCase().replace(/[^a-z0-9]+/g, '-'), name: x, icon: 'files' }))
|
||||||
|
const shell = { kind: 'slot', display: 'Marta Alves', role: s.role || 'owner', content: CT(s.many ? 14 : 3), contentOn: 'events', navBadge: false }
|
||||||
|
const BUILTIN = [['Articles', 'articles', 5], ['Authors', 'authors', 5], ['Sites', 'sites', 8], ['Media', 'media', 6], ['Users', 'users', 6]]
|
||||||
|
const CUSTOM = [['Events', 'events', 7, '15 Oct 2026'], ['Recipes', 'recipes', 4, '2 Oct 2026'], ['Press mentions', 'press-mentions', 5, '18 Sep 2026']]
|
||||||
|
const ROWS = [
|
||||||
|
{ id: 42, title: 'Lime plaster workshop', starts_on: '21 Nov 2026', ends_on: '22 Nov 2026', online: false, capacity: 18, category: 'Workshop', description: 'Two days of hands-on work with lime putty and old stone.', c: '12 Oct 2026', u: '15 Oct 2026, 11:02', by: 'Marta Alves' },
|
||||||
|
{ id: 41, title: 'Heat pumps: what the numbers say', starts_on: '3 Nov 2026', ends_on: '', online: true, capacity: 500, category: 'Talk', description: 'A look at running costs after two winters.', c: '8 Oct 2026', u: '14 Oct 2026, 16:40', by: 'Jonas Pereira' },
|
||||||
|
{ id: 40, title: 'Open day at the Rue Verte site', starts_on: '12 Nov 2026', ends_on: '12 Nov 2026', online: false, capacity: 120, category: 'Meetup', description: '', c: '2 Oct 2026', u: '12 Oct 2026, 09:15', by: 'Inès Duarte' },
|
||||||
|
{ id: 39, title: 'Winter windows clinic', starts_on: '5 Dec 2026', ends_on: '', online: false, capacity: null, category: 'Workshop', description: 'Bring a window, leave with a plan.', c: '30 Sep 2026', u: '9 Oct 2026, 14:22', by: 'Marta Alves' },
|
||||||
|
{ id: 38, title: 'Timber joinery for beginners', starts_on: '14 Jan 2027', ends_on: '15 Jan 2027', online: false, capacity: 12, category: 'Workshop', description: 'Mortise, tenon and a lot of patience.', c: '28 Sep 2026', u: '7 Oct 2026, 10:05', by: 'Inès Duarte' },
|
||||||
|
{ id: 37, title: 'Q&A with the site managers', starts_on: '28 Oct 2026', ends_on: '', online: true, capacity: null, category: 'Meetup', description: '', c: '21 Sep 2026', u: '2 Oct 2026, 17:48', by: 'Jonas Pereira' },
|
||||||
|
{ id: 36, title: 'Reclaimed floorboards talk', starts_on: '17 Oct 2026', ends_on: '', online: false, capacity: 60, category: 'Talk', description: 'Where to find them and how to lay them.', c: '14 Sep 2026', u: '29 Sep 2026, 08:30', by: 'Marta Alves' }]
|
||||||
|
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 sampleVal = f => f.type === 'text' ? (f.def ?? 'Example text') : f.type === 'richtext' ? (f.def ?? 'Markdown text') : f.type === 'number' ? (f.def ?? f.min ?? 0) : f.type === 'boolean' ? (f.def ?? false) : f.type === 'date' ? (f.def ?? '2026-11-21') : (f.def ?? (f.opts && f.opts[0]) ?? null)
|
||||||
|
const apiJson = (fs_, key) => JSON.stringify({ id: 42, content_type: key, data: Object.fromEntries(fs_.map(f => [f.key, sampleVal(f)])), created_by: 3, updated_by: 3, created_at: '2026-10-15T11:02:00Z', updated_at: '2026-10-15T11:02:00Z' }, null, 2)
|
||||||
|
const MM = t => t === 'number' ? ['Lowest value', 'Highest value', ''] : t === 'date' ? ['Earliest date', 'Latest date', ''] : ['Shortest', 'Longest', 'characters']
|
||||||
|
const dot = (t, ic) => S('display:inline-flex;align-items:center;gap:6px', I(ic, 14), t)
|
||||||
|
|
||||||
|
// ---------- inspector
|
||||||
|
const 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 t = f.type, e = f.err || {}, one = m || o.one, locked = !!f.saved
|
||||||
|
const [mnL, mxL, suf] = MM(t), canU = ['text', 'number', 'date', 'select'].includes(t), hasMM = ['text', 'richtext', 'number', 'date'].includes(t)
|
||||||
|
const g2 = one ? '1fr' : '1fr 1fr'
|
||||||
|
const tile = k => { const on = k === t, dim = locked && !on; return D('display:flex;gap:10px;align-items:flex-start;padding:10px;min-height:56px;border:1px solid ' + (on ? 'var(--ui-primary)' : 'var(--ui-border-accented)') + ';background:' + (on ? 'var(--rc-sand)' : 'var(--ui-bg)') + ';color:' + (on ? 'var(--rc-on-sand)' : 'var(--ui-text-highlighted)') + ';opacity:' + (dim ? 0.4 : 1), I(FT[k][0], 16, 'margin-top:2px'), D('display:flex;flex-direction:column;min-width:0', S('font-weight:500', FT[k][1]), S('font-size:12px;line-height:16px;color:' + (on ? 'var(--rc-on-sand)' : 'var(--ui-text-muted)') + ';text-wrap:pretty', FT[k][2]))) }
|
||||||
|
const mmErr = e.min || ''
|
||||||
|
const minV = f.min != null ? String(f.min) : '', maxV = f.max != null ? String(f.max) : ''
|
||||||
|
const defCtl = t === 'boolean' ? null : F('Default value', f.def != null ? String(f.def) : '', { opt: true, ph: f.def == null, phText: t === 'select' ? 'None' : t === 'date' ? 'No default' : 'No default', sel: t === 'select', ico: t === 'date' ? 'calendar' : null, area: t === 'richtext', err: e.def, dis: !!f.uniq, help: f.uniq ? 'A field with unique values can\'t have a default.' : e.def ? '' : 'Used when an entry is created and this field is left out.' })
|
||||||
|
const left = D('display:flex;flex-direction:column;min-width:0;border-top:1px solid var(--ui-border)', SwR(!!f.req, 'Required', 'An entry can\'t be saved with this field empty.'), 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 = 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) : 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',
|
||||||
|
D('display:grid;grid-template-columns:' + g2 + ';gap:14px', F('Label', f.label, { req: true, err: e.label, focus: o.focus === 'label', ph: !f.label, phText: 'For example, Title' }),
|
||||||
|
D('display:flex;flex-direction:column;gap:6px;min-width:0', F('Key', f.key || '', { mono: true, auto: !locked && !e.key && !!f.key, lock: locked, err: e.key, ph: !f.key, phText: 'title', dis: false, help: locked ? 'Used in the API, so it can\'t change.' : e.key ? '' : 'The name used in the API. Starts with a letter. Lowercase letters, digits and underscores.' }))),
|
||||||
|
D('display:flex;flex-direction:column;gap:6px', D('display:flex;justify-content:space-between;gap:8px', S('font-weight:500;color:var(--ui-text-highlighted)', 'Type'), locked && S('color:var(--ui-text-muted);font-size:12px;display:flex;gap:4px;align-items:center', I('lock', 12), 'Can\'t change after saving')), D('display:grid;grid-template-columns:repeat(' + (one ? 2 : 3) + ',minmax(0,1fr));gap:8px', ...Object.keys(FT).map(tile))),
|
||||||
|
left,
|
||||||
|
right.length > 0 && D('display:grid;grid-template-columns:' + g2 + ';gap:14px;align-items:start', ...right.filter(Boolean)),
|
||||||
|
ch)
|
||||||
|
}
|
||||||
|
const Choices = f => {
|
||||||
|
const e = f.err || {}, ops = f.opts || [], bad = e.choices || {}
|
||||||
|
return D('display:flex;flex-direction:column;gap:8px', D('display:flex;justify-content:space-between', S('font-weight:500;color:var(--ui-text-highlighted)', 'Choices', ' *'), S(mono + 'font-size:12px;color:var(--ui-text-muted)', ops.length + ' of 50')),
|
||||||
|
...ops.map((o_, i) => D('display:flex;flex-direction:column;gap:4px', D('display:flex;align-items:center;gap:4px', S('width:' + (m ? 44 : 28) + 'px;height:' + (m ? 44 : 28) + 'px;display:flex;align-items:center;justify-content:center;color:var(--ui-text-muted)', I('grip-vertical', 16)), D('flex:1;height:' + ih + 'px;display:flex;align-items:center;padding:0 10px;font-size:' + fs + 'px;border:1px solid ' + (bad[i] ? 'var(--ui-error)' : 'var(--ui-border-accented)') + ';background:var(--ui-bg);color:' + (o_ ? 'var(--ui-text-highlighted)' : 'var(--ui-text-muted)'), o_ || 'Choice'), IB('x')), bad[i] && S('margin-left:' + (m ? 48 : 32) + 'px;display:flex;gap:6px;color:var(--ui-error);font-size:12px;line-height:18px', I('circle-alert', 14, 'margin-top:2px'), bad[i]))),
|
||||||
|
D('display:flex;gap:8px;padding-left:' + (m ? 48 : 32) + 'px', D('flex:1;height:' + ih + 'px;display:flex;align-items:center;padding:0 10px;border:1px dashed var(--ui-border-accented);color:var(--ui-text-muted);font-size:' + fs + 'px', 'Add a choice'), B('Add', { icon: 'plus' })),
|
||||||
|
S('color:var(--ui-text-muted);font-size:12px;line-height:18px', 'Add 1 to 50 choices. Each one needs a different name. Removing a choice that entries use will be refused when you save.'))
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------- field list
|
||||||
|
const FRow = (f, i, o = {}) => {
|
||||||
|
const on = o.sel === i, err = !!f.err, kb = o.kb === i
|
||||||
|
const rm = on && D('display:flex;gap:2px;margin-left:auto', IB('chevron-up', { dis: i === 0 }), IB('chevron-down'), IB('trash-2'))
|
||||||
|
return D('display:flex;align-items:center;gap:' + (m ? 4 : 2) + 'px;min-height:' + (m ? 64 : 56) + 'px;padding:6px 8px 6px 4px;border:1px solid ' + (err ? 'var(--ui-error)' : kb ? 'var(--ui-primary)' : 'var(--ui-border)') + ';' + (kb ? 'outline:2px solid var(--ui-primary);outline-offset:-1px;box-shadow:var(--rc-shadow-pop);' : '') + 'background:' + (on ? 'var(--rc-sel)' : 'var(--ui-bg)') + ';color:' + (on ? 'var(--rc-on-sel)' : 'var(--ui-text-highlighted)') + ';opacity:' + (o.dim ? 0.6 : 1),
|
||||||
|
S('width:' + (m ? 36 : 24) + 'px;height:32px;display:flex;align-items:center;justify-content:center;flex-shrink:0;color:' + (on ? 'var(--rc-on-sel)' : 'var(--ui-text-muted)'), I('grip-vertical', 16)),
|
||||||
|
S('width:28px;height:28px;flex-shrink:0;display:flex;align-items:center;justify-content:center;background:' + (on ? 'var(--ui-bg)' : 'var(--ui-bg-elevated)') + ';color:var(--ui-text-highlighted)', I(FT[f.type][0], 16)),
|
||||||
|
D('flex:1;min-width:0;display:flex;flex-direction:column;margin-left:8px', S('font-weight:500;overflow:hidden;text-overflow:ellipsis;white-space:nowrap', f.label || 'Untitled field'), D('display:flex;align-items:center;gap:6px;min-width:0', S(mono + 'font-size:12px;line-height:16px;color:' + (on ? 'var(--rc-on-sel)' : 'var(--ui-text-muted)') + ';overflow:hidden;text-overflow:ellipsis;white-space:nowrap;min-width:0;flex:0 1 auto', f.key || '–'), f.isNew && Bd('New', 'neu'), f.changed && Bd('Changed', 'chg'), !on && o.cause && f.changed && Bd('Possible cause', 'warn', 'triangle-alert'), f.req && h('span', { title: 'Required', 'aria-label': 'Required', style: { display: 'flex', flexShrink: 0 } }, Bd('R', 'req')), f.uniq && h('span', { title: 'Unique', 'aria-label': 'Unique', style: { display: 'flex', flexShrink: 0 } }, Bd('U', 'uniq')))),
|
||||||
|
err && !on && I('circle-alert', 16, 'color:var(--ui-error);flex-shrink:0;margin:0 4px'), on && !m && rm)
|
||||||
|
}
|
||||||
|
const ApiPanel = (fl, key, open) => {
|
||||||
|
const routes = [['GET', '/v1/content-type/' + key + '/entry'], ['POST', '/v1/content-type/' + key + '/entry'], ['GET', '/v1/content-type/' + key + '/entry/{id}'], ['PUT', '/v1/content-type/' + key + '/entry/{id}'], ['DELETE', '/v1/content-type/' + key + '/entry/{id}']]
|
||||||
|
const head = D('height:44px;flex-shrink:0;display:flex;align-items:center;gap:10px;padding:0 ' + (m ? 12 : 24) + 'px;border-top:1px solid var(--ui-border);background:var(--ui-bg);color:var(--ui-text-highlighted)', I(open ? 'chevron-down' : 'chevron-right', 14), S('font-weight:600', 'API preview'), !m && S(mono + 'font-size:12px;color:var(--ui-text-muted);flex:1;overflow:hidden;text-overflow:ellipsis;white-space:nowrap', 'GET /v1/content-type/' + key + '/entry'), m && S('flex:1'), B('Copy JSON', { icon: 'copy', h: m ? 44 : 28, fs: 12, px: 10 }))
|
||||||
|
if (!open) return head
|
||||||
|
return D('flex-shrink:0;display:flex;flex-direction:column', head, D('display:grid;grid-template-columns:1fr 1.4fr;gap:16px;height:248px;padding:0 24px 16px;background:var(--ui-bg)', D('display:flex;flex-direction:column;gap:6px;min-width:0', S('color:var(--ui-text-muted);font-size:12px', 'Where entries of this type live'), D('display:flex;flex-direction:column;gap:2px;padding:10px 12px;background:var(--ui-bg-elevated);border:1px solid var(--ui-border)', ...routes.map(r => S(mono + 'font-size:12px;line-height:19px;color:var(--ui-text-highlighted);white-space:nowrap;overflow:hidden;text-overflow:ellipsis', S('display:inline-block;width:56px;color:var(--ui-text-muted)', r[0]), r[1]))), S('color:var(--ui-text-muted);font-size:12px;line-height:18px;text-wrap:pretty', 'Updates as you edit. Fields you add or remove here appear after you save.')), D('display:flex;flex-direction:column;gap:6px;min-width:0', S('color:var(--ui-text-muted);font-size:12px', 'A sample entry. Values come from each field\'s type and default.'), S('display:block;flex:1;overflow:hidden;padding:10px 12px;background:var(--ui-bg-elevated);border:1px solid var(--ui-border);white-space:pre;' + mono + 'font-size:12px;line-height:19px;color:var(--ui-text-highlighted)', apiJson(fl, key)))))
|
||||||
|
}
|
||||||
|
const stChip = (kind, n) => { const M = { clean: ['check', 'Saved', 'var(--ui-text-muted)'], dirty: ['circle-dot', 'Unsaved changes', 'var(--ui-warning)'], saving: ['loader-circle', 'Saving…', 'var(--ui-text-muted)'], saved: ['check', 'Saved at 11:02', 'var(--ui-text-muted)'], fail: ['circle-alert', 'Save failed', 'var(--ui-error)'], offline: ['wifi-off', 'Waiting for connection', 'var(--ui-text-muted)'], errs: ['circle-alert', n + (n === 1 ? ' problem' : ' problems') + ' to fix', 'var(--ui-error)'] }[kind]; return S('display:flex;align-items:center;gap:6px;white-space:nowrap;font-size:12px;color:' + M[2], I(M[0], 14), M[1]) }
|
||||||
|
|
||||||
|
// ---------- entry controls
|
||||||
|
const hint = f => { const t = f.type; if (t === 'text' || t === 'richtext') return [f.min && 'At least ' + f.min + ' characters', f.max && 'Up to ' + f.max + ' characters', f.uniq && 'Each entry needs a different one'].filter(Boolean).join('. ') + (f.min || f.max || f.uniq ? '.' : ''); if (t === 'number') return f.min != null && f.max != null ? 'Between ' + f.min + ' and ' + f.max + '.' : f.min != null ? 'At least ' + f.min + '.' : f.max != null ? 'At most ' + f.max + '.' : ''; if (t === 'date') return [f.min && 'From ' + f.min, f.max && 'until ' + f.max].filter(Boolean).join(' ') ; return t === 'select' ? '' : '' }
|
||||||
|
const MdBox = (o, val) => D('display:flex;flex-direction:column;border:1px solid ' + (o.err ? 'var(--ui-error)' : o.focus ? 'var(--ui-primary)' : 'var(--ui-border-accented)') + ';background:' + (o.dis ? 'var(--ui-bg-elevated)' : 'var(--ui-bg)') + (o.err ? ';box-shadow:inset 0 0 0 1px var(--ui-error)' : ''),
|
||||||
|
D('display:flex;align-items:center;border-bottom:1px solid var(--ui-border);padding:0 6px;gap:2px;overflow:hidden', D('display:flex;gap:14px;padding:0 6px;margin-right:8px', ...[['write', 'Write'], ['preview', 'Preview']].map(([k, t]) => S('height:' + (m ? 44 : 32) + 'px;display:flex;align-items:center;font-weight:' + (o.tab === k || (!o.tab && k === 'write') ? 500 : 400) + ';color:' + (o.tab === k || (!o.tab && k === 'write') ? 'var(--ui-text-highlighted)' : 'var(--ui-text-toned)') + ';border-bottom:2px solid ' + (o.tab === k || (!o.tab && k === 'write') ? 'var(--ui-primary)' : 'transparent'), t))), ...(o.tab === 'preview' ? [] : ['bold', 'italic', 'heading', 'link', 'list'].map(ic => S('width:' + (m ? 40 : 28) + 'px;height:' + (m ? 40 : 28) + 'px;display:flex;align-items:center;justify-content:center;color:var(--ui-text-toned)', I(ic, 16))))),
|
||||||
|
o.tab === 'preview' ? D('padding:10px 12px;min-height:' + (m ? 120 : 96) + 'px;display:flex;flex-direction:column;gap:8px;font-size:' + fs + 'px', S('', 'Two days of hands-on work with ', S('font-weight:600', 'lime putty'), ' and old stone.'), D('display:flex;flex-direction:column;gap:2px;padding-left:18px', S('display:list-item;list-style:square', 'Bring work clothes'), S('display:list-item;list-style:square', 'Lunch is included'))) : S('display:block;white-space:pre-wrap;padding:8px 10px;min-height:' + (m ? 120 : 96) + 'px;font-size:' + (m ? 14 : 12) + 'px;line-height:' + (m ? 22 : 19) + 'px;' + mono + 'color:' + (val ? 'var(--ui-text-highlighted)' : 'var(--ui-text-muted)'), val || 'Write in Markdown'))
|
||||||
|
const Cal = () => { const cells = [...Array(6).fill(''), ...Array.from({ length: 30 }, (_, i) => i + 1)]; return D('width:' + (m ? 280 : 252) + 'px;padding:8px;background:var(--ui-bg);border:1px solid var(--ui-border);box-shadow:var(--rc-shadow-pop)', D('display:flex;align-items:center;justify-content:space-between;height:32px', IB('chevron-left'), S('font-weight:600', 'November 2026'), IB('chevron-right')), D('display:grid;grid-template-columns:repeat(7,1fr)', ...['Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa', 'Su'].map(d => S('height:28px;display:flex;align-items:center;justify-content:center;font-size:12px;color:var(--ui-text-muted)', d)), ...cells.map(c => S('height:' + (m ? 34 : 30) + 'px;display:flex;align-items:center;justify-content:center;background:' + (c === 21 ? 'var(--ui-primary)' : 'transparent') + ';color:' + (c === 21 ? 'var(--ui-bg)' : 'var(--ui-text-highlighted)'), c))) ) }
|
||||||
|
const Ctl = (f, o = {}) => {
|
||||||
|
const t = f.type, v = o.v == null ? '' : String(o.v)
|
||||||
|
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 bd = o.err ? 'var(--ui-error)' : o.focus ? 'var(--ui-primary)' : 'var(--ui-border-accented)'
|
||||||
|
const box = (...inner) => D('display:flex;align-items:center;min-height:' + ih + 'px;border:1px solid ' + bd + ';background:' + (o.dis ? 'var(--ui-bg-elevated)' : 'var(--ui-bg)') + ';font-size:' + fs + 'px;' + (o.err ? 'box-shadow:inset 0 0 0 1px var(--ui-error);' : o.focus ? 'box-shadow:inset 0 0 0 1px var(--ui-primary);' : ''), ...inner)
|
||||||
|
const txt = (val, ph) => S('flex:1;min-width:0;padding:0 10px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;color:' + (val ? 'var(--ui-text-highlighted)' : 'var(--ui-text-muted)'), val || ph || '')
|
||||||
|
let ctl
|
||||||
|
if (t === 'boolean') ctl = Sw(v === 'true', v === 'true' ? 'On' : 'Off', null, o.dis)
|
||||||
|
else if (t === 'richtext') ctl = MdBox(o, v)
|
||||||
|
else if (t === 'number') ctl = box(txt(v, 'Enter a number'), D('display:flex;border-left:1px solid var(--ui-border);height:' + ih + 'px;color:var(--ui-text-muted)', S('width:' + (m ? 40 : 28) + 'px;display:flex;align-items:center;justify-content:center', I('minus', 14)), S('width:' + (m ? 40 : 28) + 'px;display:flex;align-items:center;justify-content:center;border-left:1px solid var(--ui-border)', I('plus', 14))))
|
||||||
|
else if (t === 'date') ctl = box(txt(v, 'Pick a date'), I('calendar', 14, 'margin-right:10px;color:var(--ui-text-muted)'))
|
||||||
|
else if (t === 'select') ctl = box(txt(v, 'Choose an option'), I('chevron-down', 14, 'margin-right:10px;color:var(--ui-text-muted)'))
|
||||||
|
else ctl = box(txt(v, ''))
|
||||||
|
const hp = o.help === undefined ? hint(f) : o.help
|
||||||
|
return D('display:flex;flex-direction:column;gap:6px;min-width:0;position:relative', lab, ctl, o.err && S('display:flex;gap:6px;align-items:flex-start;color:var(--ui-error);font-size:12px;line-height:18px', I('circle-alert', 14, 'margin-top:2px'), o.err), !o.err && hp && S('color:var(--ui-text-muted);font-size:12px;line-height:18px;text-wrap:pretty', hp), o.extra)
|
||||||
|
}
|
||||||
|
const Cell = (f, v) => {
|
||||||
|
if (v === undefined || v === null || v === '') return S('color:var(--ui-text-muted)', '–')
|
||||||
|
if (f.type === '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 === 'select') return S('height:20px;padding:0 6px;display:inline-flex;align-items:center;border:1px solid var(--ui-border-accented);color:var(--ui-text-toned);font-size:12px;justify-self:start', v)
|
||||||
|
if (f.type === 'number') return S('justify-self:end;font-variant-numeric:tabular-nums', v)
|
||||||
|
return S('overflow:hidden;text-overflow:ellipsis;white-space:nowrap;' + (f.type === 'richtext' ? 'color:var(--ui-text-toned)' : ''), v)
|
||||||
|
}
|
||||||
|
const mt = (k) => k === 'true' || k === 'false'
|
||||||
|
|
||||||
|
// ---------- pages
|
||||||
|
let main = null; const ov = []; let bare = false, bw = '1440px', bhh = '900px'
|
||||||
|
const v = s.v, k = s.k
|
||||||
|
|
||||||
|
// 1 schema list
|
||||||
|
const typesTable = (custom) => {
|
||||||
|
const cols = '24px minmax(0,1.4fr) minmax(0,1fr) 90px 150px 24px'
|
||||||
|
const hdr = D('display:grid;grid-template-columns:' + cols + ';gap:12px;height:36px;align-items:center;padding:0 12px;background:var(--ui-bg-elevated);color:var(--ui-text-muted);font-weight:500', S('', ''), S('', 'Name'), S('', 'Key'), S('', 'Fields'), S('', 'Last updated'), S('', ''))
|
||||||
|
const r = (name, key, n, up, built) => D('display:grid;grid-template-columns:' + cols + ';gap:12px;height:48px;align-items:center;padding:0 12px;border-top:1px solid var(--ui-border)', I(built ? 'lock' : 'file-stack', 16, 'color:var(--ui-text-muted)'), D('display:flex;align-items:center;gap:8px;min-width:0', S('font-weight:500;color:var(--ui-text-highlighted)', name), built && Bd('Built-in', 'built', 'lock')), S(mono + 'font-size:12px;color:var(--ui-text-muted)', key), S('', String(n)), S('color:var(--ui-text-muted)', up || 'Managed by RenewCMS'), I('chevron-right', 14, 'color:var(--ui-text-muted)'))
|
||||||
|
const mr = (name, key, n, up, built) => D('display:flex;align-items:center;gap:12px;padding:12px 8px 12px 16px;border-top:1px solid var(--ui-border);min-height:68px', D('flex:1;min-width:0;display:flex;flex-direction:column;gap:4px', D('display:flex;align-items:center;gap:8px;flex-wrap:wrap', S('font-weight:500;font-size:15px;line-height:21px;color:var(--ui-text-highlighted)', name), built && Bd('Built-in', 'built', 'lock')), S('font-size:12px;color:var(--ui-text-muted)', S(mono, key), ' · ' + n + ' fields' + (up ? ' · Updated ' + up : ''))), S('width:36px;height:44px;display:flex;align-items:center;justify-content:center;color:var(--ui-text-muted)', I('chevron-right', 18)))
|
||||||
|
const note = D('display:flex;align-items:center;gap:8px;padding:10px 12px;border-top:1px solid var(--ui-border);background:var(--ui-bg-muted);color:var(--ui-text-toned);font-size:12px;line-height:18px', I('lock', 14, 'flex-shrink:0'), S('', 'Built-in types are managed by RenewCMS. You can read their fields, but not change them.'))
|
||||||
|
const rr = m ? mr : r
|
||||||
|
return D('background:var(--ui-bg);border:1px solid var(--ui-border)', !m && hdr, ...(custom ? CUSTOM.map(x => rr(x[0], x[1], x[2], x[3])) : []), note, ...BUILTIN.map(x => rr(x[0], x[1], x[2], '', true)))
|
||||||
|
}
|
||||||
|
if (v === 'types') {
|
||||||
|
Object.assign(shell, { nav: 'schema', crumbs: ['Schema'], mTitle: 'Schema' })
|
||||||
|
const newBtn = B('New content type', { k: 'primary', icon: 'plus', px: 14, dis: k === 'loading' })
|
||||||
|
const impExp = s.later ? [B('Import', { icon: 'upload' }), B('Export', { icon: 'download' })] : []
|
||||||
|
if (k === 'forbidden') { shell.role = 'user'; shell.crumbs = ['Schema']; main = Center('lock', 'You don\'t have access to Schema', 'Only owners and admins can change content types. You can still add and edit entries from the Content menu.', B('Go to Home', { k: 'primary', px: 16 })) }
|
||||||
|
else if (k === 'builtin' || k === 'customro') {
|
||||||
|
const cr = k === 'customro'
|
||||||
|
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)'
|
||||||
|
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')),
|
||||||
|
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] : ''))))) :
|
||||||
|
D('background:var(--ui-bg);border:1px solid var(--ui-border)', D('display:grid;grid-template-columns:' + cols + ';gap:12px;height:36px;align-items:center;padding:0 12px;background:var(--ui-bg-elevated);color:var(--ui-text-muted);font-weight:500', S('', ''), S('', 'Label'), S('', 'Key'), S('', 'Type'), S('', 'Rules')), ...AF.map(f => D('display:grid;grid-template-columns:' + cols + ';gap:12px;height:48px;align-items:center;padding:0 12px;border-top:1px solid var(--ui-border)', I(FT[f[2]][0], 16, 'color:var(--ui-text-toned)'), S('font-weight:500', f[0]), S(mono + 'font-size:12px;color:var(--ui-text-muted)', f[1]), S('', FT[f[2]][1]), S('color:var(--ui-text-muted)', f[3] || '–')))), S('color:var(--ui-text-muted);font-size:12px', 'Entries of built-in types are managed from their own screens, like Articles and Authors.'))
|
||||||
|
} else {
|
||||||
|
const body = []
|
||||||
|
if (k === 'loading') body.push(D('background:var(--ui-bg);border:1px solid var(--ui-border)', ...Array.from({ length: m ? 6 : 8 }, (_, i) => D('height:' + (m ? 68 : 48) + 'px;display:flex;align-items:center;gap:16px;padding:0 16px;border-top:' + (i ? '1px solid var(--ui-border)' : 'none'), Skel('18px', 16), Skel(i % 2 ? '28%' : '20%'), Skel('14%', 12), !m && Skel('40px', 12), !m && Skel('90px', 12)))))
|
||||||
|
else if (k === 'error') body.push(Alert('error', 'circle-x', 'Couldn\'t load content types', 'GET /v1/content-type failed. Check your connection and try again.', 'Try again'))
|
||||||
|
else if (k === 'empty') body.push(Empty('shapes', 'No content types yet', 'Create a content type to manage your own kind of content, like events or recipes. The built-in types stay as they are.', 'New content type'), typesTable(false))
|
||||||
|
else body.push(typesTable(true), S('color:var(--ui-text-muted)', CUSTOM.length + ' content types · ' + BUILTIN.length + ' built-in'))
|
||||||
|
main = Page(pad, Title('Schema', 'Content types and the fields they are made of.', ...impExp, s.later && Later(), newBtn), ...body)
|
||||||
|
if (m && k !== 'loading' && k !== 'error' && k !== 'empty') ov.push(Fab('New content type'))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2 builder
|
||||||
|
const entN = v === 'review' && (k === 'mrefuse' || k === 'mclean') ? 12 : 37
|
||||||
|
const bld = () => {
|
||||||
|
let fl = EV, name = 'Events', key = 'events', sel = 0, st = 'clean', isNew = false, api = k === 'api', kb = -1, tErr = {}, banner = null, removed = null, cause = false, tip = false, toast = null, info = true, nErr = 0
|
||||||
|
if (v === 'review') { const rk = k; if (rk === 'confirm' || rk === 'fallback') { fl = RC; name = 'Recipes'; key = 'recipes'; info = false } else if (rk === 'blocked') { sel = 0 } else 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 === 'builder') {
|
||||||
|
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 (k === 'saved') { removed = null; st = 'saved'; fl = DIRTY.map(f => ({ ...f, isNew: false, changed: false, saved: true })); toast = Toast('success', 'circle-check', 'Content type saved', 'Events now has 8 fields.') }
|
||||||
|
if (k === 'fail') banner = Alert('error', 'circle-x', 'Couldn\'t save the content type', 'Something went wrong on our side. Your changes are still here. Try again in a moment.', 'Try again')
|
||||||
|
if (k === 'incompat') { banner = Alert('error', 'circle-x', 'Nothing was changed', 'Some entries don\'t fit the new fields, so the whole change was refused. RenewCMS can\'t tell which entries. The changes that can cause this are marked.', 'Review changes'); cause = true }
|
||||||
|
if (k === 'offline') { }
|
||||||
|
if (k === 'ferr') { fl = EV.map((f, i) => i === 2 ? { ...f, label: '', err: { label: 'Give the field a label.' } } : i === 4 ? { ...f, min: 6000, err: { min: 'Lowest value can\'t be above the highest value.' } } : i === 5 ? { ...f, opts: ['Talk', 'Workshop', '', 'Talk'], err: { choices: { 2: 'Choices can\'t be blank.', 3: 'Two choices are the same.' } } } : f); sel = 4; st = 'errs'; nErr = 3 }
|
||||||
|
if (k === 'choices') { fl = EV.map((f, i) => i === 5 ? { ...f, opts: ['Talk', 'Workshop', 'Meetup', '', 'Talk'], err: { choices: { 3: 'Choices can\'t be blank.', 4: 'Two choices are the same.' } } } : f); sel = 5; st = 'errs'; nErr = 1 }
|
||||||
|
if (k === 'fkey') { fl = [...EV, { key: '2nd-date', label: 'Second date', type: 'date', isNew: true, err: { key: 'Start with a letter. Use lowercase letters, digits and underscores.' } }]; sel = 7; st = 'errs'; nErr = 1 }
|
||||||
|
if (k === 'kb') { fl = [EV[0], EV[2], EV[1], ...EV.slice(3)]; sel = 1; kb = 1; st = 'dirty' }
|
||||||
|
if (k === 'new') { fl = [{ key: 'title', label: 'Title', type: 'text', isNew: true }]; name = ''; key = ''; isNew = true; sel = 0; st = 'clean'; info = false }
|
||||||
|
if (k === 'terr') { fl = []; name = ''; key = 'e'; isNew = true; sel = -1; st = 'errs'; nErr = 3; info = false; tErr = { name: 'Give the content type a name.', key: 'Use 2 to 40 lowercase letters, digits or hyphens.', fields: 'A content type needs at least one field.' } }
|
||||||
|
if (k === 'taken') { fl = [{ key: 'title', label: 'Title', type: 'text', req: true, isNew: true }, { key: 'starts_on', label: 'Starts on', type: 'date', isNew: true }]; name = 'Events'; key = 'events'; isNew = true; sel = 0; st = 'errs'; nErr = 1; info = false; tErr = { key: 'The key "events" is already used by another content type. Choose a different key.' } }
|
||||||
|
}
|
||||||
|
const f = fl[sel], dim = st === 'saving'
|
||||||
|
const nameF = F('Name', name, { req: true, err: tErr.name, ph: !name, phText: 'For example, Events', dis: dim })
|
||||||
|
const keyF = F('Key', key, { mono: true, lock: !isNew, auto: isNew && !!key && !tErr.key, err: tErr.key, ph: !key, phText: 'events', dis: dim, help: tErr.key ? '' : isNew ? 'Used in URLs and the API. Lowercase letters, digits and hyphens. It can\'t change after you save.' : null })
|
||||||
|
const save = D('display:flex;align-items:center;gap:' + (m ? 8 : 12) + 'px;flex-shrink:0', !m && stChip(st, nErr), !m && B('Discard', { dis: st === 'clean' || st === 'saving' || st === 'saved' || (st === 'errs' && isNew && k === 'new') }), !m && B(st === 'saving' ? 'Saving…' : 'Save', { k: 'primary', icon: st === 'saving' ? 'loader-circle' : null, px: 16, dis: st === 'clean' || st === 'saved' || st === 'saving' || st === 'errs' || st === 'offline' }))
|
||||||
|
const top = m ? D('display:flex;flex-direction:column;gap:12px;padding:16px;flex-shrink:0;background:var(--ui-bg);border-bottom:1px solid var(--ui-border)', nameF, keyF) : D('display:flex;align-items:flex-start;gap:16px;padding:16px 24px;flex-shrink:0;background:var(--ui-bg);border-bottom:1px solid var(--ui-border);position:relative', D('width:320px', nameF), D('width:320px', keyF), D('flex:1'), D('display:flex;align-items:center;gap:12px;height:32px;margin-top:26px', save, IB('ellipsis')), tip && D('position:absolute;left:352px;top:84px;z-index:30', Tip('The key is used in URLs and the API, so it can\'t change after the type is created.')))
|
||||||
|
const infoBar = info && !isNew && D('flex-shrink:0;display:flex;align-items:center;gap:8px;padding:8px ' + (m ? 16 : 24) + 'px;background:var(--rc-info-soft);color:var(--ui-info);font-size:12px;line-height:18px', I('info', 14, 'flex-shrink:0'), S('color:var(--ui-text-toned)', 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 live = kb >= 0 && D('padding:8px 10px;background:var(--ui-bg-inverted);color:var(--ui-text-inverted);font-size:12px;line-height:18px', S('font-weight:600', 'Moving Ends on. Position 2 of 7.'), ' Press Up or Down to move, Space to drop, Esc to cancel.')
|
||||||
|
const rows = fl.length ? fl.map((x, i) => FRow(x, i, { sel: m ? -1 : sel, kb, dim, cause })) : [D('display:flex;flex-direction:column;align-items:center;gap:8px;text-align:center;padding:32px 16px;border:1px dashed ' + (tErr.fields ? 'var(--ui-error)' : 'var(--ui-border-accented)'), I('rows-3', 20, 'color:var(--ui-text-muted)'), S('font-weight:600', 'No fields yet'), S('color:' + (tErr.fields ? 'var(--ui-error)' : 'var(--ui-text-muted)'), tErr.fields || 'Add the first field.'))]
|
||||||
|
const rem = removed && D('display:flex;align-items:center;gap:8px;min-height:44px;padding:0 12px;border:1px dashed var(--ui-border-accented);color:var(--ui-text-toned)', I('minus', 14), S('flex:1', removed.label + ' will be removed'), S('text-decoration:underline;text-underline-offset:3px;font-weight:500;color:var(--ui-text-highlighted)', 'Undo'))
|
||||||
|
const addB = B('Add field', { icon: 'plus', full: false, dis: dim })
|
||||||
|
const apiRow = m && D('display:flex;align-items:center;gap:10px;min-height:44px;padding:0 12px;border:1px solid var(--ui-border);background:var(--ui-bg);color:var(--ui-text-highlighted)', I('braces', 16), S('flex:1;font-weight:500', 'API preview'), I('chevron-right', 14, 'color:var(--ui-text-muted)'))
|
||||||
|
const list = D('display:flex;flex-direction:column;gap:8px;' + (m ? 'padding:16px;flex:1;min-height:0;overflow:hidden' : 'width:380px;flex-shrink:0;border-right:1px solid var(--ui-border);padding:16px;overflow:hidden;background:var(--ui-bg-muted)'), listHdr, live, ...rows, rem, addB, apiRow)
|
||||||
|
const inspPane = !m && D('flex:1;min-width:0;overflow:hidden;padding:16px 24px;background:var(--ui-bg);display:flex;flex-direction:column;gap:14px', f ? D('display:flex;align-items:center;gap:8px', S('font:600 15px/24px \'IBM Plex Sans\',sans-serif;color:var(--ui-text-highlighted)', 'Field: ' + (f.label || 'Untitled field')), f.isNew && Bd('New', 'neu')) : S('font:600 15px/24px \'IBM Plex Sans\',sans-serif;color:var(--ui-text-highlighted)', 'Field settings'), f ? D('opacity:' + (dim ? 0.6 : 1), Insp(f)) : S('color:var(--ui-text-muted)', 'Add a field, then choose its type and rules here.'))
|
||||||
|
const bar = m && D('flex-shrink:0;display:flex;align-items:center;gap:8px;padding:12px 16px;border-top:1px solid var(--ui-border);background:var(--ui-bg)', stChip(st, nErr), D('flex:1'), B('Discard', { dis: st === 'clean' || st === 'saved' || st === 'saving' || k === 'new' }), B(st === 'saving' ? 'Saving…' : 'Save', { k: 'primary', icon: st === 'saving' ? 'loader-circle' : null, px: 16, dis: ['clean', 'saved', 'saving', 'errs', 'offline'].includes(st) }))
|
||||||
|
shell.nav = 'schema'; shell.crumbs = ['Schema', isNew ? 'New content type' : name]; shell.mTitle = isNew ? 'New content type' : name; shell.mLead = 'arrow-left'; shell.mAction = 'ellipsis'
|
||||||
|
shell.offline = false
|
||||||
|
main = D('flex:1;min-width:0;min-height:0;display:flex;flex-direction:column;position:relative', st === 'offline' && Offline(), top, infoBar, banner && D('padding:12px ' + (m ? 16 : 24) + 'px 0', banner), D('flex:1;min-height:0;display:flex;' + (m ? 'flex-direction:column' : ''), list, inspPane), m ? bar : ApiPanel(fl, key || 'events', api))
|
||||||
|
if (m && f && (s.sheet || (v === 'builder' && ['edit-sheet', 'choices', '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 (toast) ov.push(toast)
|
||||||
|
}
|
||||||
|
if (v === 'builder') { bld() }
|
||||||
|
|
||||||
|
// 3 review
|
||||||
|
const chg = (icon, tone, title, text, flag, extra) => D('display:flex;gap:10px;padding:10px 12px;border:1px solid var(--ui-border);background:' + (flag ? 'var(--rc-warning-soft)' : 'var(--ui-bg)'), S('margin-top:2px;display:flex;color:' + (flag ? 'var(--ui-warning)' : 'var(--ui-text-toned)'), I(icon)), D('flex:1;min-width:0;display:flex;flex-direction:column;gap:2px', D('display:flex;align-items:center;gap:8px;flex-wrap:wrap', S('font-weight:600;color:var(--ui-text-highlighted)', title), flag && Bd(flag, 'warn', 'triangle-alert'), extra), S('color:var(--ui-text-toned);text-wrap:pretty', text)))
|
||||||
|
if (v === 'review') {
|
||||||
|
bld()
|
||||||
|
const sum = D('display:flex;flex-direction:column;gap:2px', S('font-weight:600;font-size:15px;color:var(--ui-text-highlighted)', 'Add 2 fields, change 1, remove 1'), S('color:var(--ui-text-muted)', 'Events has 37 entries. Each one is checked against the new fields when you apply.'))
|
||||||
|
const lat = t => k === 'later' ? Later(t) : null
|
||||||
|
const list = [chg('plus', 'n', 'Add Speaker', 'Text, optional.', null, lat('Affects 0 entries')), chg('plus', 'n', 'Add Room', 'Choice, required, default "Main hall". Existing entries get the default, so they still fit.', null, lat('Affects 37 entries')), chg('pencil', 'n', 'Change Capacity', 'Highest value goes from 5000 to 2000.', 'Entries may not fit', lat('Affects 3 entries')), chg('minus', 'n', 'Remove Description', 'Entries stop returning its values.', 'Removes data', lat('Affects 31 entries'))]
|
||||||
|
if (k === 'review' || k === 'later') ov.push(Shell({ title: 'Review changes to Events', desc: 'Apply them to save the content type.', w: k === 'later' ? 640 : 560, top: 60, cancel: 'Back to editing', confirm: 'Apply changes', later: false }, [sum, D('display:flex;flex-direction:column;gap:8px', ...list), k === 'later' ? D('display:flex;align-items:center;gap:8px', B('View full diff', { icon: 'git-compare', h: m ? 44 : 28, fs: 12, px: 10 }), Later('Per-change counts and diff come later')) : S('color:var(--ui-text-muted);font-size:12px;line-height:18px', 'Flagged changes can be refused if existing entries don\'t fit. If that happens, nothing is changed.')]))
|
||||||
|
if (k === 'applying') ov.push(Shell({ title: 'Review changes to Events', desc: 'Apply them to save the content type.', w: 560, top: 60, cancel: 'Back to editing', confirm: 'Applying…', loading: true, cdis: true }, [sum, D('display:flex;flex-direction:column;gap:8px', ...list)]))
|
||||||
|
if (k === 'refused') ov.push(Shell({ title: 'Nothing was changed', desc: 'RenewCMS refused the changes because some entries don\'t fit the new fields. It doesn\'t say which entries.', w: 560, top: 60, close: true, cancel: 'Discard changes', confirm: 'Back to editing' }, [Alert('error', 'circle-x', 'Your content type is as it was', 'No field was added, changed or removed.'), S('font-weight:600;color:var(--ui-text-highlighted)', 'The change that can cause this in your edit'), chg('pencil', 'n', 'Change Capacity', 'Highest value goes from 5000 to 2000. An entry may have a higher value.', 'Possible cause'), S('color:var(--ui-text-muted);font-size:12px;line-height:18px;text-wrap:pretty', 'This kind of change is refused when an entry is over the new limit, a new required field has no default, a field becomes unique while entries share a value, or a removed choice is still in use.')]))
|
||||||
|
if (k === 'blocked') ov.push(Shell({ title: 'You can\'t delete Events yet', desc: 'A content type can only be deleted when it has no entries.', close: true, cancel: 'Close', confirm: 'View entries' }, [Alert('warning', 'triangle-alert', 'Events has 37 entries', 'Delete all of its entries first, then delete the content type.')]))
|
||||||
|
if (k === 'confirm') ov.push(Shell({ title: 'Delete Recipes?', desc: 'Recipes has no entries. Its fields and its API routes will be deleted. This can\'t be undone.', close: true, cancel: 'Cancel', confirm: 'Delete content type', tone: 'danger' }, [S('color:var(--ui-text-toned)', 'Key: ', S(mono + 'font-size:12px', 'recipes'))]))
|
||||||
|
if (k === '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.')]))
|
||||||
|
}
|
||||||
|
|
||||||
|
// 4 gallery
|
||||||
|
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') {
|
||||||
|
bare = true; if (m) { bw = '390px'; bhh = '844px' }
|
||||||
|
const f = { ...GF[k], saved: false }, t = k, L = f.label
|
||||||
|
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 = { 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 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 = { 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 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 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 = { 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'), 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 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] === '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 head = D('display:flex;align-items:center;gap:14px;flex-shrink:0', S('width:44px;height:44px;display:flex;align-items:center;justify-content:center;background:var(--rc-sand);color:var(--rc-on-sand)', I(FT[t][0], 22)), D('flex:1;display:flex;flex-direction:column', S('font:600 ' + (m ? 20 : 24) + 'px/32px \'IBM Plex Sans\',sans-serif;color:var(--ui-text-highlighted)', FT[t][1]), S('color:var(--ui-text-muted)', FT[t][2])), !m && S(mono + 'font-size:12px;color:var(--ui-text-toned)', 'type: "' + t + '"'))
|
||||||
|
const inspCol = !m && sec('Inspector options', card(Insp(f, { one: true })))
|
||||||
|
main = D('position:absolute;inset:0;padding:' + (m ? '16px' : '32px') + ';display:flex;flex-direction:column;gap:' + (m ? 14 : 20) + 'px;overflow:hidden', head, m ? D('display:flex;flex-direction:column;gap:14px', ctlCol, listCol, errCol, filtCol) : D('display:grid;grid-template-columns:400px 440px minmax(0,1fr);gap:24px;align-items:start;flex:1;min-height:0;overflow:hidden', inspCol, D('display:flex;flex-direction:column;gap:20px;min-width:0', ctlCol, listCol), D('display:flex;flex-direction:column;gap:20px;min-width:0', errCol, filtCol)))
|
||||||
|
}
|
||||||
|
|
||||||
|
// 5 entries
|
||||||
|
const visCols = ['thumb', 'thumbcols', 'thumbtip'].includes(k) ? [EV[0], THUMB, EV[1], EV[5]] : [EV[0], EV[1], EV[2], EV[3]]
|
||||||
|
if (v === 'entries') {
|
||||||
|
shell.nav = 'content'; shell.crumbs = ['Content', 'Events']; shell.mTitle = 'Events'; shell.contentOn = k === 'notfound' ? null : 'events'
|
||||||
|
if (s.many && m) { shell.drawer = true; shell.contentOpen = true }
|
||||||
|
if (k === 'forbidden') main = Center('lock', 'You don\'t have access to Events', 'Your account can\'t open this content right now. If you think this is a mistake, ask an owner or an admin.', B('Go to Home', { k: 'primary', px: 16 }))
|
||||||
|
else if (k === 'notfound') { shell.crumbs = ['Content']; shell.mTitle = 'Content'; main = Center('file-x', 'Content type not found', 'It may have been deleted, or the address may be mistyped.', B('Go to Home', { k: 'primary', px: 16 })) }
|
||||||
|
else {
|
||||||
|
const paged = k === 'paged', total = paged ? 37 : 7, size = paged ? 5 : 25
|
||||||
|
const editB = B('Edit content type', { icon: 'settings-2', k: 'ghost' })
|
||||||
|
const sortB = D('display:flex;align-items:center;gap:8px;height:' + bh + 'px;padding:0 10px;border:1px solid var(--ui-border-accented);background:var(--ui-bg);color:var(--ui-text-highlighted);white-space:nowrap;' + (m ? 'flex:1' : 'width:220px;flex-shrink:0'), S('color:var(--ui-text-muted)', 'Sort by'), S('font-weight:500;flex:1', 'Last updated'), I('chevron-down', 14, 'color:var(--ui-text-muted)'))
|
||||||
|
const dirB = B(null, { icon: 'arrow-down-wide-narrow', w: bh, px: 0 }), colB = B(m ? null : 'Columns', { icon: 'columns-3', w: m ? 44 : null, px: m ? 0 : 12, ring: false })
|
||||||
|
const toolbar = D('display:flex;align-items:center;gap:8px;flex-shrink:0;position:relative', sortB, dirB, colB, !m && D('flex:1'), !m && editB)
|
||||||
|
let body
|
||||||
|
if (k === 'loading') body = D('background:var(--ui-bg);border:1px solid var(--ui-border);flex:1;min-height:0;overflow:hidden', ...Array.from({ length: m ? 6 : 8 }, (_, i) => D('height:' + (m ? 68 : 48) + 'px;display:flex;align-items:center;gap:20px;padding:0 16px;border-top:' + (i ? '1px solid var(--ui-border)' : 'none'), !m && Skel('32px', 12), Skel(i % 2 ? '30%' : '24%'), !m && Skel('90px', 12), !m && Skel('90px', 12), !m && Skel('50px', 12))))
|
||||||
|
else if (k === 'error') body = Alert('error', 'circle-x', 'Couldn\'t load entries', 'GET /v1/content-type/events/entry failed. Check your connection and try again.', 'Try again')
|
||||||
|
else if (k === 'empty') body = Empty('file-plus', 'No entries yet', 'Use New entry to add the first event. Each entry follows the fields of this content type.', 'New entry')
|
||||||
|
else {
|
||||||
|
const rows = ROWS.slice(0, size > 7 ? 7 : 5)
|
||||||
|
const gc = '48px ' + visCols.map((f, i) => i === 0 ? 'minmax(0,1.6fr)' : f.type === 'boolean' || f.type === 'number' || 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 tbl = D('background:var(--ui-bg);border:1px solid var(--ui-border)', D('display:grid;grid-template-columns:' + gc + ';gap:12px;height:36px;align-items:center;padding:0 12px;background:var(--ui-bg-elevated);color:var(--ui-text-muted);font-weight:500', hdrC('ID'), ...visCols.map(f => hdrC(f.label, { r: f.type === 'number' })), hdrC('Created'), hdrC('Updated', { sort: true }), hdrC('Updated by')),
|
||||||
|
...rows.map((r, i) => D('display:grid;grid-template-columns:' + gc + ';gap:12px;height:48px;align-items:center;padding:0 12px;border-top:1px solid var(--ui-border);background:' + (i === 0 && false ? 'var(--ui-bg-elevated)' : 'transparent'), S(mono + 'font-size:12px;color:var(--ui-text-muted)', String(r.id)), ...visCols.map((f, j) => D('min-width:0;' + (j === 0 ? 'font-weight:500;color:var(--ui-text-highlighted);display:flex' : 'display:grid'), Cell(f, r[f.key]))), S('color:var(--ui-text-muted);white-space:nowrap', r.c), S('color:var(--ui-text-muted);white-space:nowrap', r.u.split(',')[0]), S('overflow:hidden;text-overflow:ellipsis;white-space:nowrap', r.by))))
|
||||||
|
const cards = D('background:var(--ui-bg);border:1px solid var(--ui-border)', ...ROWS.slice(0, 6).map((r, i) => D('display:flex;align-items:center;gap:8px;padding:12px 4px 12px 16px;border-top:' + (i ? '1px solid var(--ui-border)' : 'none') + ';min-height:68px', 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 pager = !paged ? S('color:var(--ui-text-muted)', '7 entries') : m ? D('display:flex;align-items:center;justify-content:space-between;gap:8px', pgB('chevron-left', false, true), S('color:var(--ui-text-muted)', 'Page 1 of 8'), pgB('chevron-right')) : D('display:flex;align-items:center;gap:16px', S('flex:1;color:var(--ui-text-muted)', 'Showing 1–5 of 37'), D('display:flex;align-items:center;gap:8px;height:32px;padding:0 10px;border:1px solid var(--ui-border-accented);background:var(--ui-bg)', '5 per page', I('chevron-down', 14, 'color:var(--ui-text-muted)')), D('display:flex;gap:4px', pgB('chevrons-left', false, true), pgB('chevron-left', false, true), pgB('1', true), pgB('2'), pgB('3'), pgB('…'), pgB('8'), pgB('chevron-right'), pgB('chevrons-right')))
|
||||||
|
body = D('display:flex;flex-direction:column;gap:12px;min-height:0', m ? cards : tbl, pager)
|
||||||
|
}
|
||||||
|
main = Page(pad, Title('Events', 'events · 7 fields', !m && B('New entry', { k: 'primary', icon: 'plus', px: 14, dis: k === 'loading' })), ...(k === 'error' || k === 'empty' || k === 'loading' ? [k !== 'error' ? toolbar : null, body] : [toolbar, body]))
|
||||||
|
if (m && k !== 'error' && k !== 'loading') ov.push(Fab('New entry'))
|
||||||
|
if (k === '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'))
|
||||||
|
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')))
|
||||||
|
if (m) ov.push(Sheet({ title: 'Columns', z: 45 }, [S('color:var(--ui-text-muted)', 'Choose up to 6 fields to show. 4 selected.'), lst], [B('Reset', { full: true }), B('Done', { k: 'primary', full: true })]))
|
||||||
|
else ov.push(D('position:absolute;z-index:40;left:' + (224 + 24 + 330) + 'px;top:' + (48 + 24 + 28 + 18 + 16 + 40) + 'px;width:300px;background:var(--ui-bg);border:1px solid var(--ui-border);box-shadow:var(--rc-shadow-pop);padding:8px;display:flex;flex-direction:column;gap:8px', D('display:flex;justify-content:space-between;padding:4px 8px', S('font-weight:600', 'Columns'), S('color:var(--ui-text-muted);font-size:12px', '4 of 6')), lst, D('display:flex;justify-content:flex-end;padding:4px 8px', B('Reset', { h: 28, fs: 12 }))))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 6 entry
|
||||||
|
if (v === 'entry') {
|
||||||
|
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'
|
||||||
|
if (k === 'notfound') main = Center('file-x', 'Entry not found', 'It may have been deleted by someone else.', B('Back to Events', { k: 'primary', px: 16 }))
|
||||||
|
else {
|
||||||
|
const isNew = k === 'new' || k === 'required'
|
||||||
|
const val = { title: isNew ? '' : 'Lime plaster workshop', starts_on: isNew ? '' : '21 Nov 2026', ends_on: isNew ? '' : '22 Nov 2026', online: 'false', capacity: isNew ? '' : '18', category: isNew ? '' : 'Workshop', description: isNew ? '' : mdSample }
|
||||||
|
const E = {}
|
||||||
|
if (k === 'dirty' || k === 'saving' || k === 'fail') val.title = 'Lime plaster workshop, two days'
|
||||||
|
if (k === 'required') { E.title = 'Fill in Title.'; E.starts_on = 'Pick a date for Starts on.' }
|
||||||
|
if (k === 'rules') { val.title = 'Lime plaster workshop, two days of hands-on work with the whole team on site and lunch'; E.title = 'Title can be up to 80 characters.'; val.ends_on = '31/11/2026'; E.ends_on = 'Ends on must be a date, like 2026-11-21.'; val.capacity = '6000'; E.capacity = 'Capacity must be at most 5000.'; val.category = 'Seminar'; E.category = 'Choose one of: Talk, Workshop or Meetup.' }
|
||||||
|
if (k === 'unique') { val.title = 'Heat pumps: what the numbers say'; E.title = 'Another entry already uses this Title. Enter a different one.' }
|
||||||
|
const dis = k === 'saving' || k === 'changed'
|
||||||
|
const sk = k === 'dirty' ? 'dirty' : k === 'saving' ? 'saving' : k === 'saved' ? 'saved' : k === 'fail' ? 'fail' : (k === 'required' || k === 'rules' || k === 'unique' || mErr) ? 'fail' : 'clean'
|
||||||
|
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' || 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 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 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' && 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' }))
|
||||||
|
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 === 'saved') ov.push(Toast('success', 'circle-check', 'Entry saved', '"Lime plaster workshop" is up to date.'))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 7 relation (later)
|
||||||
|
if (v === 'rel') {
|
||||||
|
shell.nav = 'schema'
|
||||||
|
if (k === 'builder') {
|
||||||
|
shell.crumbs = ['Schema', 'Events']; shell.mTitle = 'Events'; shell.mLead = 'arrow-left'
|
||||||
|
const shape = (on, a, b, diag) => D('display:flex;flex-direction:column;gap:6px;padding:10px;border:1px solid ' + (on ? 'var(--ui-primary)' : 'var(--ui-border-accented)') + ';background:' + (on ? 'var(--rc-sand)' : 'var(--ui-bg)') + ';color:' + (on ? 'var(--rc-on-sand)' : 'var(--ui-text-highlighted)'), diag, S('font-weight:500', a), S('font-size:12px;line-height:16px;color:' + (on ? 'var(--rc-on-sand)' : 'var(--ui-text-muted)'), b))
|
||||||
|
const sq = (n, c) => D('display:flex;gap:3px', ...Array.from({ length: n }, () => S('width:10px;height:10px;background:' + c)))
|
||||||
|
const dg = (l, r) => D('display:flex;align-items:center;gap:6px', sq(l, 'currentColor'), S('width:20px;height:1px;background:currentColor'), sq(r, 'currentColor'))
|
||||||
|
const sel = (t) => S('display:inline-flex;align-items:center;gap:6px;height:28px;padding:0 8px;margin:0 4px;border:1px solid var(--ui-border-accented);background:var(--ui-bg);font-weight:500;color:var(--ui-text-highlighted)', t, I('chevron-down', 12))
|
||||||
|
const card_ = (t, ...c) => D('flex:1;min-width:0;padding:12px;background:var(--ui-bg);border:1px solid var(--ui-border);display:flex;flex-direction:column;gap:8px', S('font-weight:600;color:var(--ui-text-highlighted)', t), ...c)
|
||||||
|
const chipR = t => S('height:22px;padding:0 8px;display:inline-flex;align-items:center;gap:4px;background:var(--rc-sand);color:var(--rc-on-sand);font-size:12px;font-weight:500', t)
|
||||||
|
const insp = D('display:flex;flex-direction:column;gap:14px;min-width:0', D('display:flex;align-items:center;gap:8px', S('font:600 15px/24px \'IBM Plex Sans\',sans-serif;color:var(--ui-text-highlighted)', 'Field: Venue'), Later()), D('display:grid;grid-template-columns:' + (m ? '1fr' : '1fr 1fr') + ';gap:14px', F('Label', 'Venue', { req: true }), F('Key', 'venue', { mono: true, auto: true })),
|
||||||
|
D('display:flex;flex-direction:column;gap:6px', S('font-weight:500;color:var(--ui-text-highlighted)', 'Type'), D('display:grid;grid-template-columns:repeat(' + (m ? 2 : 4) + ',minmax(0,1fr));gap:8px', ...['text', 'number', 'date', 'select'].map(t => D('display:flex;gap:8px;align-items:center;padding:8px 10px;border:1px solid var(--ui-border-accented);opacity:.6', I(FT[t][0], 16), FT[t][1])), D('display:flex;gap:8px;align-items:center;padding:8px 10px;border:1px solid var(--ui-primary);background:var(--rc-sand);color:var(--rc-on-sand)', I('link', 16), S('font-weight:500', 'Relation'), S('margin-left:auto;font-size:11px', 'Later')))),
|
||||||
|
F('Related content type', 'Venue', { sel: true, help: 'Choose the content type this field points to.' }),
|
||||||
|
D('display:flex;flex-direction:column;gap:6px', S('font-weight:500;color:var(--ui-text-highlighted)', 'How are they connected?'), D('display:grid;grid-template-columns:' + (m ? '1fr' : 'repeat(3,minmax(0,1fr))') + ';gap:8px', shape(false, 'One to one', 'Each Event has one Venue, and each Venue has one Event.', dg(1, 1)), shape(true, 'One to many', 'Each Event has one Venue. A Venue has many Events.', dg(3, 1)), shape(false, 'Many to many', 'Each Event has many Venues, and each Venue has many Events.', dg(2, 2)))),
|
||||||
|
D('display:flex;flex-direction:column;gap:8px;padding:12px;background:var(--ui-bg-elevated)', S('', 'Each Event has', sel('one'), 'Venue'), S('', 'Each Venue has', sel('many'), 'Events', S('color:var(--ui-text-muted)', ' · shown on Venue as the field "Events"'))),
|
||||||
|
D('display:flex;gap:12px;flex-direction:' + (m ? 'column' : 'row'), card_('Event', S('color:var(--ui-text-muted);font-size:12px', 'Venue'), D('display:flex;gap:6px', chipR('Rue Verte hall'))), card_('Venue', S('color:var(--ui-text-muted);font-size:12px', 'Events'), D('display:flex;gap:6px;flex-wrap:wrap', chipR('Open day'), chipR('Lime plaster workshop'), S('font-size:12px;color:var(--ui-text-muted);align-self:center', '+1')))))
|
||||||
|
main = Page(pad, Title('Edit content type', 'Events · Relation field, shown as it will work later.'), D('background:var(--ui-bg);border:1px solid var(--ui-border);padding:16px;overflow:hidden', insp))
|
||||||
|
} else if (k === 'form') {
|
||||||
|
shell.nav = 'content'; shell.crumbs = ['Content', 'Events', 'Lime plaster workshop']; shell.mTitle = 'Lime plaster workshop'; shell.contentOn = 'events'
|
||||||
|
const res = D('position:absolute;left:0;right:0;top:64px;z-index:5;border:1px solid var(--ui-border);background:var(--ui-bg);box-shadow:var(--rc-shadow-pop);padding:4px', ...[['Rue Verte hall', 'Lyon · 120 seats'], ['Rue Verte yard', 'Lyon · outdoor'], ['Rue du Port studio', 'Nantes · 24 seats']].map(([a, b], i) => D('min-height:' + (m ? 48 : 40) + 'px;padding:4px 8px;display:flex;flex-direction:column;justify-content:center;background:' + (i === 0 ? 'var(--ui-bg-elevated)' : 'transparent'), S('font-weight:500', a), S('font-size:12px;color:var(--ui-text-muted)', b))))
|
||||||
|
const chipX = t => S('height:' + (m ? 32 : 24) + 'px;padding:0 4px 0 8px;display:inline-flex;align-items:center;gap:6px;background:var(--rc-sand);color:var(--rc-on-sand);font-weight:500', t, I('x', 14))
|
||||||
|
main = Page(pad, Title('Lime plaster workshop', 'Events · Entry 42', Later('Relation field: later')), D('background:var(--ui-bg);border:1px solid var(--ui-border);padding:' + (m ? 16 : 24) + 'px;display:flex;flex-direction:column;gap:' + (m ? 16 : 20) + 'px;max-width:760px;overflow:visible;flex:1;min-height:0', Ctl(EV[0], { v: 'Lime plaster workshop', count: '21 / 80' }),
|
||||||
|
D('display:flex;flex-direction:column;gap:6px;position:relative', S('font-weight:500;color:var(--ui-text-highlighted)', 'Venue'), F('', 'rue', { focus: true, ico: 'search' }), res, S('height:176px')),
|
||||||
|
D('display:flex;flex-direction:column;gap:6px', S('font-weight:500;color:var(--ui-text-highlighted)', 'Speakers'), D('display:flex;gap:6px;flex-wrap:wrap;align-items:center;min-height:' + ih + 'px;padding:4px 8px;border:1px solid var(--ui-border-accented)', chipX('Inès Duarte'), chipX('Jonas Pereira'), S('color:var(--ui-text-muted);margin-left:4px', 'Search to add')), S('color:var(--ui-text-muted);font-size:12px', 'An event can have many speakers.'))))
|
||||||
|
} else {
|
||||||
|
shell.nav = 'content'; shell.crumbs = ['Content', 'Events']; shell.mTitle = 'Events'; shell.contentOn = 'events'
|
||||||
|
const chipR = t => S('height:20px;padding:0 6px;display:inline-flex;align-items:center;background:var(--rc-sand);color:var(--rc-on-sand);font-size:12px;font-weight:500;white-space:nowrap', t)
|
||||||
|
const gc = '48px minmax(0,1.4fr) 110px 200px 200px'
|
||||||
|
const rr = [[42, 'Lime plaster workshop', '21 Nov 2026', [chipR('Rue Verte hall')], [chipR('Inès Duarte'), chipR('Jonas Pereira'), S('color:var(--ui-text-muted);font-size:12px', '+2')]], [41, 'Heat pumps: what the numbers say', '3 Nov 2026', [S('color:var(--ui-text-muted)', '–')], [chipR('Jonas Pereira')]], [40, 'Open day at the Rue Verte site', '12 Nov 2026', [chipR('Rue Verte yard')], [S('color:var(--ui-text-muted)', '–')]]]
|
||||||
|
main = Page(pad, Title('Events', 'events · 9 fields', Later('Relation columns: later')), m ? D('background:var(--ui-bg);border:1px solid var(--ui-border)', ...rr.map(r => D('padding:12px 16px;border-top:1px solid var(--ui-border);display:flex;flex-direction:column;gap:6px', S('font-weight:500;font-size:15px', r[1]), D('display:flex;gap:6px;align-items:center', S('font-size:12px;color:var(--ui-text-muted)', 'Venue'), ...r[3]), D('display:flex;gap:6px;align-items:center;flex-wrap:wrap', S('font-size:12px;color:var(--ui-text-muted)', 'Speakers'), ...r[4])))) : D('background:var(--ui-bg);border:1px solid var(--ui-border)', D('display:grid;grid-template-columns:' + gc + ';gap:12px;height:36px;align-items:center;padding:0 12px;background:var(--ui-bg-elevated);color:var(--ui-text-muted);font-weight:500', S('', 'ID'), S('', 'Title'), S('', 'Starts on'), S('', 'Venue'), S('', 'Speakers')), ...rr.map(r => D('display:grid;grid-template-columns:' + gc + ';gap:12px;height:48px;align-items:center;padding:0 12px;border-top:1px solid var(--ui-border)', S(mono + 'font-size:12px;color:var(--ui-text-muted)', String(r[0])), S('font-weight:500;color:var(--ui-text-highlighted);overflow:hidden;text-overflow:ellipsis;white-space:nowrap', r[1]), S('', r[2]), D('display:flex;gap:4px;align-items:center', ...r[3]), D('display:flex;gap:4px;align-items:center', ...r[4])))), S('color:var(--ui-text-muted);font-size:12px;line-height:18px', 'One chip for a single relation. Up to two chips and a "+N" for many. Empty shows a dash.'))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 8 permissions (later)
|
||||||
|
if (v === 'perms') {
|
||||||
|
shell.nav = 'settings'; shell.crumbs = ['Settings', 'Permissions']; shell.mTitle = 'Permissions'; shell.mLead = 'arrow-left'; shell.sideOpen = true
|
||||||
|
const ch = k === 'changed'
|
||||||
|
const rowsC = [['Events', 'events', [1, 1, 1, 1]], ['Recipes', 'recipes', ch ? [1, 1, 1, 0] : [1, 1, 1, 1]], ['Press mentions', 'press-mentions', ch ? [1, 0, 0, 0] : [1, 1, 1, 1]]]
|
||||||
|
const rowsB = [['Articles', [1, 1, 1, 1]], ['Authors', [1, 1, 1, 0]], ['Sites', [1, 0, 0, 0]], ['Media', [1, 1, 1, 1]], ['Users', [0, 0, 0, 0]]]
|
||||||
|
const A4 = ['Read', 'Create', 'Update', 'Delete']
|
||||||
|
const cols = 'minmax(0,1fr) 80px 80px 80px 80px'
|
||||||
|
const cellP = (on, lock, changed) => D('display:flex;align-items:center;justify-content:center;gap:4px;opacity:' + (lock ? 0.55 : 1), Chk(!!on), changed && S('width:6px;height:6px;background:var(--ui-info)'))
|
||||||
|
const desk = D('background:var(--ui-bg);border:1px solid var(--ui-border)', D('display:grid;grid-template-columns:' + cols + ';gap:8px;height:36px;align-items:center;padding:0 12px;background:var(--ui-bg-elevated);color:var(--ui-text-muted);font-weight:500', S('', 'Content type'), ...A4.map(a => S('text-align:center', a))),
|
||||||
|
...rowsC.map(r => D('display:grid;grid-template-columns:' + cols + ';gap:8px;height:44px;align-items:center;padding:0 12px;border-top:1px solid var(--ui-border)', D('display:flex;align-items:center;gap:8px', S('font-weight:500', r[0]), S(mono + 'font-size:12px;color:var(--ui-text-muted)', r[1])), ...r[2].map((x, i) => cellP(x, false, ch && ((r[0] === 'Recipes' && i === 3) || (r[0] === 'Press mentions' && i > 0)))))),
|
||||||
|
D('display:flex;align-items:center;gap:8px;padding:8px 12px;border-top:1px solid var(--ui-border);background:var(--ui-bg-muted);color:var(--ui-text-toned);font-size:12px', I('lock', 14), 'Built-in types. RenewCMS sets these rules.'),
|
||||||
|
...rowsB.map(r => D('display:grid;grid-template-columns:' + cols + ';gap:8px;height:44px;align-items:center;padding:0 12px;border-top:1px solid var(--ui-border)', D('display:flex;align-items:center;gap:8px', I('lock', 14, 'color:var(--ui-text-muted)'), S('font-weight:500', r[0]), Bd('Built-in', 'built')), ...r[1].map(x => cellP(x, true)))))
|
||||||
|
const mob = D('display:flex;flex-direction:column;gap:12px', ...rowsC.map(r => D('background:var(--ui-bg);border:1px solid var(--ui-border);padding:12px 16px;display:flex;flex-direction:column;gap:2px', S('font-weight:600;font-size:15px;color:var(--ui-text-highlighted)', r[0]), ...r[2].map((x, i) => D('display:flex;align-items:center;gap:12px;min-height:44px;border-top:' + (i ? '1px solid var(--ui-border-muted)' : 'none'), Chk(!!x), S('flex:1', A4[i]), ch && ((r[0] === 'Recipes' && i === 3) || (r[0] === 'Press mentions' && i > 0)) && Bd('Changed', 'chg'))))), D('background:var(--ui-bg);border:1px solid var(--ui-border);padding:12px 16px;display:flex;align-items:center;gap:10px;min-height:48px', I('lock', 16, 'color:var(--ui-text-muted)'), S('flex:1', '5 built-in types'), S('color:var(--ui-text-muted);font-size:12px', 'Set by RenewCMS'), I('chevron-right', 14, 'color:var(--ui-text-muted)')))
|
||||||
|
const foot = D('flex-shrink:0;display:flex;align-items:center;gap:8px;padding:12px ' + (m ? 16 : 24) + 'px;border-top:1px solid var(--ui-border);background:var(--ui-bg)', S('flex:1;font-size:12px;color:' + (ch ? 'var(--ui-warning)' : 'var(--ui-text-muted)'), ch ? '4 changes not saved' : 'No changes'), B('Discard', { dis: !ch }), B('Save permissions', { k: 'primary', dis: !ch }))
|
||||||
|
main = D('flex:1;min-width:0;min-height:0;display:flex;flex-direction:column', Page(pad, Title('Permissions', 'What each role can do with each content type.', Later()), Alert('info', 'info', 'Today\'s rules are the starting point', 'Owners and admins edit the schema. Any verified user can read, add, edit and delete entries.'), Seg([['owner', 'Owner'], ['admin', 'Admin'], ['user', 'User']], 'user', m ? '100%' : '320px'), m ? mob : desk, D('display:flex;align-items:center;gap:8px;color:var(--ui-text-toned);font-size:12px;line-height:18px;background:var(--ui-bg-elevated);padding:10px 12px', I('lock', 14), S('', 'Schema (create, edit and delete content types): owners and admins only. Set by RenewCMS.'))), foot)
|
||||||
|
}
|
||||||
|
|
||||||
|
// 9 export / import (later)
|
||||||
|
if (v === 'xport') {
|
||||||
|
Object.assign(shell, { nav: 'schema', crumbs: ['Schema'], mTitle: 'Schema' })
|
||||||
|
main = Page(pad, Title('Schema', 'Content types and the fields they are made of.', B('Import', { icon: 'upload' }), B('Export', { icon: 'download' }), Later(), B('New content type', { k: 'primary', icon: 'plus', px: 14 })), typesTable(true))
|
||||||
|
const rd = (on, t, sub) => D('display:flex;gap:10px;align-items:flex-start;padding:10px 12px;border:1px solid ' + (on ? 'var(--ui-primary)' : 'var(--ui-border-accented)') + ';background:' + (on ? 'var(--rc-sand)' : 'var(--ui-bg)') + ';color:' + (on ? 'var(--rc-on-sand)' : 'var(--ui-text-highlighted)'), S('width:16px;height:16px;margin-top:2px;flex-shrink:0;border:1px solid currentColor;display:flex;align-items:center;justify-content:center', on && S('width:8px;height:8px;background:currentColor')), D('display:flex;flex-direction:column', S('font-weight:500', t), S('font-size:12px;color:' + (on ? 'var(--rc-on-sand)' : 'var(--ui-text-muted)'), sub)))
|
||||||
|
if (k === 'export') ov.push(Shell({ title: 'Export schema', desc: 'Download the fields of your content types as a file. Entries aren\'t included.', close: true, later: true, cancel: 'Cancel', confirm: 'Download file' }, [D('display:flex;flex-direction:column;gap:8px', rd(true, 'All content types', '3 content types'), rd(false, 'One content type', 'Choose which one')), F('File name', 'renewcms-schema.json', { mono: true, dis: true, help: 'Import this file on another RenewCMS site to create the same content types.' })]))
|
||||||
|
else {
|
||||||
|
const ref = k === 'refused'
|
||||||
|
const rowI = (ic, t, text, flag, tag) => D('display:flex;gap:10px;padding:10px 12px;border:1px solid var(--ui-border);background:' + (flag ? 'var(--rc-warning-soft)' : 'var(--ui-bg)'), S('margin-top:2px;display:flex;color:' + (flag ? 'var(--ui-warning)' : 'var(--ui-text-toned)'), I(ic)), D('flex:1;min-width:0;display:flex;flex-direction:column;gap:2px', D('display:flex;align-items:center;gap:8px;flex-wrap:wrap', S('font-weight:600;color:var(--ui-text-highlighted)', t), tag && Bd(tag, 'chg'), flag && Bd(flag, 'warn', 'triangle-alert')), S('color:var(--ui-text-toned);text-wrap:pretty', text)))
|
||||||
|
ov.push(Shell({ title: 'Import schema', desc: 'renewcms-schema.json · 3 content types', w: 600, top: 70, close: true, later: true, cancel: 'Cancel', confirm: ref ? 'Try again' : 'Import schema', cdis: false }, [ref ? Alert('error', 'circle-x', 'Nothing was imported', 'Some entries on this site don\'t fit the imported fields. RenewCMS can\'t tell which entries. The flagged change can cause this.') : S('font-weight:600;font-size:15px;color:var(--ui-text-highlighted)', 'Create 1, change 1, no change 1'), D('display:flex;flex-direction:column;gap:8px', rowI('plus', 'Recipes', 'New content type with 4 fields.', null, 'Create'), rowI('pencil', 'Events', 'Add 2 fields, remove Description. Events has 37 entries on this site.', 'Removes data', 'Change'), rowI('equal', 'Press mentions', 'Same as on this site.', null, null)), S('color:var(--ui-text-muted);font-size:12px;line-height:18px', 'Existing entries are checked against the changes when you import. If any entry doesn\'t fit, nothing is imported.')]))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (m && v !== 'gallery' && s.drawer) shell.drawer = true
|
||||||
|
const framed = !bare
|
||||||
|
return { framed, bare, shell, mob: m, main, ov: D('display:contents', ...ov), bw, bh: bhh }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
@@ -0,0 +1,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."
|
||||||
|
]
|
||||||
|
]
|
||||||
|
}
|
||||||
|
]
|
||||||
@@ -0,0 +1,214 @@
|
|||||||
|
import { tables as mfTables } from './media-field-tables.js'
|
||||||
|
const N = 'available now', L = 'later'
|
||||||
|
const st = (name, scope, trigger, s, copy, o = {}) => ({ name, scope, trigger, s, copy, ...o })
|
||||||
|
|
||||||
|
export const groups = [
|
||||||
|
{ label: '1 Schema list', title: '1 Schema: list of types', route: '/schema, /schema/:key (built-in)', api: 'GET /v1/content-type', auth: 'Owner or admin', note: 'Sidebar entry "Schema" for owners and admins only. Built-in types are listed with a lock and a Built-in badge, always after the custom ones. They open a read-only view. Sample data: the field counts of built-ins are illustrative.', states: [
|
||||||
|
st('Populated', N, 'An owner or admin opens /schema.', { v: 'types', k: 'ok' }, 'Schema · Content types and the fields they are made of. · New content type · Name · Key · Fields · Last updated · Built-in types are managed by RenewCMS. You can read their fields, but not change them. · Built-in · 3 content types · 5 built-in'),
|
||||||
|
st('Loading', N, 'First load or retry. Skeleton rows appear after 150 ms. New content type is disabled.', { v: 'types', k: 'loading' }, '(skeleton) · New content type (disabled)'),
|
||||||
|
st('Empty: no custom type yet', N, 'GET /v1/content-type returns []. Built-ins are still listed below.', { v: 'types', k: 'empty' }, 'No content types yet · Create a content type to manage your own kind of content, like events or recipes. The built-in types stay as they are. · New content type'),
|
||||||
|
st('Error', N, '500 or network failure on the list request.', { v: 'types', k: 'error' }, 'Couldn\'t load content types · GET /v1/content-type failed. Check your connection and try again. · Try again'),
|
||||||
|
st('Forbidden (403)', N, 'A user who is not owner or admin types /schema. There is no sidebar entry, so the page explains instead of redirecting.', { v: 'types', k: 'forbidden' }, 'You don\'t have access to Schema · Only owners and admins can change content types. You can still add and edit entries from the Content menu. · Go to Home'),
|
||||||
|
st('Built-in type: read-only view', N, 'Click Articles in the list. No edit, no delete, no add field.', { v: 'types', k: 'builtin' }, 'Articles · Built-in · Managed by RenewCMS · Articles is a built-in type. You can read its fields here, but you can\'t edit it, delete it or add fields. · Label · Key · Type · Rules · Entries of built-in types are managed from their own screens, like Articles and Authors.'),
|
||||||
|
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: [
|
||||||
|
st('New type', N, '/schema/new. One starter field is added because a type needs at least one.', { v: 'builder', k: 'new' }, 'New content type · Name · For example, Events · Key · events · Used in URLs and the API. Lowercase letters, digits and hyphens. It can\'t change after you save. · Fields · 1 of 50 · Add field · Field: Title · Label · Key · The name used in the API. Starts with a letter. Lowercase letters, digits and underscores. · Type · Required · An entry can\'t be saved with this field empty. · Unique values · Default value · Used when an entry is created and this field is left out. · Shortest · Longest · Counted in characters. Entries show a counter. · Save · Discard'),
|
||||||
|
st('Editing an existing type', N, '/schema/events with 37 entries. Key is locked, saved field keys and types are locked.', { v: 'builder', k: 'edit' }, '37 entries use this content type. Changes are checked against them when you save. · Key (lock) · Used in the API, so it can\'t change. · Can\'t change after saving · Saved'),
|
||||||
|
st('Locked key: tooltip', N, 'Hover or focus the locked key.', { v: 'builder', k: 'locked' }, 'The key is used in URLs and the API, so it can\'t change after the type is created.'),
|
||||||
|
st('Unsaved changes', N, 'Two fields added, Capacity changed, Description removed. Rows carry New and Changed badges; removal shows an undo row.', { v: 'builder', k: 'dirty' }, 'Unsaved changes · New · Changed · Description will be removed · Undo · Save · Discard'),
|
||||||
|
st('Field errors', N, 'Checked as the user types, and again on Save. The row is outlined and shows an alert icon. Save is disabled until all are fixed.', { v: 'builder', k: 'ferr' }, '3 problems to fix · Give the field a label. · Lowest value can\'t be above the highest value. · Choices can\'t be blank. · Two choices are the same.'),
|
||||||
|
st('Type-level errors', N, 'New type with no name, a one-letter key and no fields.', { v: 'builder', k: 'terr' }, 'Give the content type a name. · Use 2 to 40 lowercase letters, digits or hyphens. · No fields yet · A content type needs at least one field. · 3 problems to fix'),
|
||||||
|
st('Field key error', N, 'A field added since the last save has an invalid key (hyphen). Checked as the user types. Field keys use underscores; type keys use hyphens.', { v: 'builder', k: 'fkey' }, 'Key · Start with a letter. Use lowercase letters, digits and underscores. · 1 problem to fix'),
|
||||||
|
st('Choice list editor', N, 'A Choice field is selected. Add, remove and reorder; blanks and duplicates are flagged per row.', { v: 'builder', k: 'choices', sheet: true }, 'Choices · 5 of 50 · Add a choice · Add · Add 1 to 50 choices. Each one needs a different name. Removing a choice that entries use will be refused when you save. · Choices can\'t be blank. · Two choices are the same.'),
|
||||||
|
st('Keyboard reorder', N, 'Focus the grip, press Space. Up and Down move, Space drops, Esc cancels. Move up, Move down and Remove buttons are on the selected row.', { v: 'builder', k: 'kb' }, 'Moving Ends on. Position 2 of 7. Press Up or Down to move, Space to drop, Esc to cancel. (live region, polite)'),
|
||||||
|
st('API preview open', N, 'The panel at the bottom. Updates as fields change. Copy JSON copies the sample entry.', { v: 'builder', k: 'api' }, 'API preview · Where entries of this type live · A sample entry. Values come from each field\'s type and default. · Updates as you edit. Fields you add or remove here appear after you save. · Copy JSON · Copied'),
|
||||||
|
st('Saving', N, 'PUT in flight. Inputs dim, Save shows the loader, nothing can be dragged.', { v: 'builder', k: 'saving' }, 'Saving…'),
|
||||||
|
st('Saved', N, '200. A toast confirms, the badges clear.', { v: 'builder', k: 'saved' }, 'Saved at 11:02 · Content type saved · Events now has 8 fields.'),
|
||||||
|
st('Save failed', N, '500 or network failure. Nothing was sent as saved; the edits stay.', { v: 'builder', k: 'fail' }, 'Save failed · Couldn\'t save the content type · Something went wrong on our side. Your changes are still here. Try again in a moment. · Try again'),
|
||||||
|
st('Key already taken', N, '409 content_type_key_taken on POST.', { v: 'builder', k: 'taken' }, 'The key "events" is already used by another content type. Choose a different key.'),
|
||||||
|
st('Schema incompatible', N, '422 schema_incompatible on PUT. The review dialog (group 3) closes into this state. Changes of the kinds that can cause it are marked.', { v: 'builder', k: 'incompat' }, 'Nothing was changed · Some entries don\'t fit the new fields, so the whole change was refused. RenewCMS can\'t tell which entries. The changes that can cause this are marked. · Review changes · Possible cause'),
|
||||||
|
st('Offline', N, 'navigator.onLine is false. Edits are kept; Save is disabled.', { v: 'builder', k: 'offline' }, 'You\'re offline. Changes will be saved when you reconnect. · Waiting for connection'),
|
||||||
|
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: [
|
||||||
|
st('Review before saving', N, 'Save on a type that has entries.', { v: 'review', k: 'review' }, 'Review changes to Events · Apply them to save the content type. · Add 2 fields, change 1, remove 1 · Events has 37 entries. Each one is checked against the new fields when you apply. · Add Speaker · Text, optional. · Add Room · Choice, required, default "Main hall". Existing entries get the default, so they still fit. · Change Capacity · Highest value goes from 5000 to 2000. · Entries may not fit · Remove Description · Entries stop returning its values. · Removes data · Flagged changes can be refused if existing entries don\'t fit. If that happens, nothing is changed. · Back to editing · Apply changes'),
|
||||||
|
st('Applying', N, 'PUT in flight. Dialog cannot be dismissed.', { v: 'review', k: 'applying' }, 'Applying…'),
|
||||||
|
st('Refused (schema_incompatible)', N, '422 schema_incompatible. States that nothing changed and names the kind of change that likely caused it, never an entry.', { v: 'review', k: 'refused' }, 'Nothing was changed · RenewCMS refused the changes because some entries don\'t fit the new fields. It doesn\'t say which entries. · Your content type is as it was · No field was added, changed or removed. · The change that can cause this in your edit · Possible cause · This kind of change is refused when an entry is over the new limit, a new required field has no default, a field becomes unique while entries share a value, or a removed choice is still in use. · Discard changes · Back to editing'),
|
||||||
|
st('Review with counts and diff', L, 'Per-change entry counts and a full diff need an API that does not exist yet.', { v: 'review', k: 'later' }, 'Affects 0 entries · Affects 37 entries · Affects 3 entries · Affects 31 entries · View full diff · Per-change counts and diff come later', { notNow: true }),
|
||||||
|
st('Delete type: blocked', N, 'Delete content type on a type with entries. No confirm button.', { v: 'review', k: 'blocked' }, 'You can\'t delete Events yet · A content type can only be deleted when it has no entries. · Events has 37 entries · Delete all of its entries first, then delete the content type. · Close · View entries'),
|
||||||
|
st('Delete type: confirm', N, 'Delete content type on an empty type.', { v: 'review', k: 'confirm' }, 'Delete Recipes? · Recipes has no entries. Its fields and its API routes will be deleted. This can\'t be undone. · Key: recipes · Cancel · Delete content type'),
|
||||||
|
st('Delete type: server fallback (409)', N, '409 content_type_has_entries. An entry was added after the page loaded.', { v: 'review', k: 'fallback' }, 'Recipes now has entries · Someone added an entry after this page loaded, so nothing was deleted. Delete the entries first, then try again. · Close · View entries'),
|
||||||
|
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', '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: [
|
||||||
|
st('Populated', N, '/content/events. 7 entries, one page: no pager, only the count.', { v: 'entries', k: 'ok' }, 'Content · Events · events · 7 fields · New entry · Sort by · Last updated · Columns · Edit content type · ID · Title · Starts on · Ends on · Online · Created · Updated · Updated by · 7 entries'),
|
||||||
|
st('Paginated, 5 per page', N, '/content/events?size=5. 37 entries.', { v: 'entries', k: 'paged' }, 'Showing 1–5 of 37 · 5 per page · Page 1 of 8 (mobile)'),
|
||||||
|
st('Columns menu', N, 'The Columns button. Popover on desktop, sheet on mobile. Created and updated always show.', { v: 'entries', k: 'cols' }, 'Columns · 4 of 6 · Choose up to 6 fields to show. 4 selected. · Created and updated dates always show · Reset · Done'),
|
||||||
|
st('Many types in the sidebar', N, '14 custom types. Long names truncate. Mobile shows the drawer with the group expanded.', { v: 'entries', k: 'ok', many: true }, 'Content · Frequently asked questions and answers (truncated) · Show all 14 · All content types 14 (mobile, collapsed)'),
|
||||||
|
st('Loading', N, 'First load or retry.', { v: 'entries', k: 'loading' }, '(skeleton)'),
|
||||||
|
st('Empty for this type', N, 'Total is 0. The hint points to New entry.', { v: 'entries', k: 'empty' }, 'No entries yet · Use New entry to add the first event. Each entry follows the fields of this content type. · New entry'),
|
||||||
|
st('Error', N, '500 or network failure.', { v: 'entries', k: 'error' }, 'Couldn\'t load entries · GET /v1/content-type/events/entry failed. Check your connection and try again. · Try again'),
|
||||||
|
st('Forbidden (403)', N, 'The API answers 403. Unverified accounts are redirected to /register/pending before this.', { v: 'entries', k: 'forbidden', role: 'user' }, 'You don\'t have access to Events · Your account can\'t open this content right now. If you think this is a mistake, ask an owner or an admin. · Go to Home'),
|
||||||
|
st('Type not found', N, '404 content_type_not_found on /content/unknown.', { v: 'entries', k: 'notfound' }, 'Content type not found · It may have been deleted, or the address may be mistyped. · Go to Home'),
|
||||||
|
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: [
|
||||||
|
st('New entry', N, '/content/events/new. Online is pre-filled from its default.', { v: 'entry', k: 'new' }, 'New entry · Events · Fields marked * are required. · Default · Each entry needs a different title. · Between 1 and 5000. · Choose an option · Pick a date · Save · Cancel · New entry · Not saved yet'),
|
||||||
|
st('Editing', N, '/content/events/42. Save is disabled until something changes.', { v: 'entry', k: 'edit' }, 'Lime plaster workshop · Events · Entry 42 · Saved · Delete · Cancel · Save · Created by · Updated by · Inès Duarte · 12 Oct 2026, 09:14 · Marta Alves · 15 Oct 2026, 11:02'),
|
||||||
|
st('Unsaved changes', N, 'Any edit.', { v: 'entry', k: 'dirty' }, 'Unsaved changes · 32 / 80'),
|
||||||
|
st('Markdown preview', N, 'The Preview tab of a rich text field.', { v: 'entry', k: 'preview' }, 'Write · Preview'),
|
||||||
|
st('Saving', N, 'PUT or POST in flight. Form dims.', { v: 'entry', k: 'saving' }, 'Saving…'),
|
||||||
|
st('Saved', N, '200.', { v: 'entry', k: 'saved' }, 'Saved at 11:02 · Entry saved · "Lime plaster workshop" is up to date.'),
|
||||||
|
st('Save failed', N, '500 or network failure. Values stay.', { v: 'entry', k: 'fail' }, 'Save failed · Couldn\'t save the entry · Something went wrong on our side. Your changes are still here. Try again in a moment. · Try again'),
|
||||||
|
st('Required fields empty', N, '422 invalid_entry: title: required, starts_on: required. The first field with an error takes focus.', { v: 'entry', k: 'required' }, 'Fill in Title. · Pick a date for Starts on. · Not saved'),
|
||||||
|
st('Rule errors', N, '422 invalid_entry for max, type, max and options. One rule per field is shown at a time.', { v: 'entry', k: 'rules' }, 'Title can be up to 80 characters. · 91 / 80 · Ends on must be a date, like 2026-11-21. · Capacity must be at most 5000. · Choose one of: Talk, Workshop or Meetup. · Not saved'),
|
||||||
|
st('Duplicate unique value (409)', N, '409 invalid_entry: title: unique.', { v: 'entry', k: 'unique' }, 'Not saved · Another entry already uses this title. Change it and save again. · Another entry already uses this Title. Enter a different one.'),
|
||||||
|
st('Entry not found', N, '404 entry_not_found, for example after a delete elsewhere.', { v: 'entry', k: 'notfound' }, 'Entry not found · It may have been deleted by someone else. · Back to Events'),
|
||||||
|
st('Schema changed since load', N, '422 invalid_entry: room: required, or unknown_field. The form is read-only until reloaded.', { v: 'entry', k: 'changed' }, 'The fields of Events changed · A field was removed and a new required field, Room, was added after you opened this form. Reload the form to continue. What you typed here can\'t be saved against the old fields. · Reload form'),
|
||||||
|
st('Delete entry: confirm', N, 'Delete.', { v: 'entry', k: 'delete' }, 'Delete this entry? · "Lime plaster workshop" will be deleted from Events. This can\'t be undone. · Cancel · Delete entry'),
|
||||||
|
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: [
|
||||||
|
st('Relation in the builder', L, 'A seventh type, Relation, in the type gallery.', { v: 'rel', k: 'builder' }, 'Relation · Related content type · How are they connected? · One to one · Each Event has one Venue, and each Venue has one Event. · One to many · Each Event has one Venue. A Venue has many Events. · Many to many · Each Event has many Venues, and each Venue has many Events. · Each Event has one Venue · Each Venue has many Events · shown on Venue as the field "Events"'),
|
||||||
|
st('Relation in the entry form', L, 'Search and pick; chips for many.', { v: 'rel', k: 'form' }, 'Venue · Speakers · Search to add · An event can have many speakers.'),
|
||||||
|
st('Relation in the list', L, 'One chip, two chips and +N, or a dash.', { v: 'rel', k: 'list' }, 'One chip for a single relation. Up to two chips and a "+N" for many. Empty shows a dash.')
|
||||||
|
] },
|
||||||
|
{ label: '8 Permissions', title: '8 Permissions grid', route: '/settings/permissions', api: 'not built', auth: 'Owner or admin', note: 'All later. Rows are types, columns are actions, one role at a time. Built-in rows are locked. Mobile collapses to one card per type with four checkboxes.', states: [
|
||||||
|
st('Default: today\'s rules', L, 'Role User selected. Everything on, as today.', { v: 'perms', k: 'default' }, 'Permissions · What each role can do with each content type. · Today\'s rules are the starting point · Owners and admins edit the schema. Any verified user can read, add, edit and delete entries. · Owner · Admin · User · Read · Create · Update · Delete · Built-in types. RenewCMS sets these rules. · Schema (create, edit and delete content types): owners and admins only. Set by RenewCMS. · No changes · Discard · Save permissions'),
|
||||||
|
st('Changed, not saved', L, 'Two types restricted for the User role.', { v: 'perms', k: 'changed' }, '4 changes not saved · Changed')
|
||||||
|
] },
|
||||||
|
{ label: '9 Export and import', title: '9 Schema export and import', route: '/schema (dialogs)', api: 'not built', auth: 'Owner or admin', note: 'All later. Dev-to-production flow: export a file, import it elsewhere, preview, same compatibility review as group 3, explicit confirm.', states: [
|
||||||
|
st('Export', L, 'Export on /schema.', { v: 'xport', k: 'export' }, 'Export schema · Download the fields of your content types as a file. Entries aren\'t included. · All content types · 3 content types · One content type · Choose which one · File name · renewcms-schema.json · Import this file on another RenewCMS site to create the same content types. · Cancel · Download file'),
|
||||||
|
st('Import preview', L, 'A file was chosen.', { v: 'xport', k: 'import' }, 'Import schema · renewcms-schema.json · 3 content types · Create 1, change 1, no change 1 · Recipes · New content type with 4 fields. · Events · Add 2 fields, remove Description. Events has 37 entries on this site. · Removes data · Press mentions · Same as on this site. · Existing entries are checked against the changes when you import. If any entry doesn\'t fit, nothing is imported. · Cancel · Import schema'),
|
||||||
|
st('Import refused', L, 'The server answers schema_incompatible.', { v: 'xport', k: 'refused' }, 'Nothing was imported · Some entries on this site don\'t fit the imported fields. RenewCMS can\'t tell which entries. The flagged change can cause this. · Try again')
|
||||||
|
] },
|
||||||
|
{ 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")
|
||||||
|
] }
|
||||||
|
]
|
||||||
|
|
||||||
|
export const tables = [
|
||||||
|
{ title: 'Scope: available now or later', tpl: '260px 110px minmax(0,1fr)', cols: ['Feature', 'Status', 'Notes'], rows: [
|
||||||
|
['1 Schema list, built-in rows, read-only view', 'Available now', 'Built-in list is static client data (see Needs backend)'],
|
||||||
|
['2 Schema builder, all states', 'Available now', ''],
|
||||||
|
['Live API preview', 'Available now', 'Built on the client from the field list'],
|
||||||
|
['Type-level and field-level validation', 'Available now', 'Same rules as the server, shown while typing'],
|
||||||
|
['3 Review step and Apply', 'Available now', 'Uses the total from the entry list response'],
|
||||||
|
['3 Refusal state, delete type, blocked delete', 'Available now', ''],
|
||||||
|
['3 Per-change entry counts, full diff', 'Later', 'The API does not return them'],
|
||||||
|
['4 Field-type gallery', 'Available now', 'Filter widgets inside it are Later'],
|
||||||
|
['5 Content group in the sidebar, entry list', 'Available now', 'No filter or search on custom fields'],
|
||||||
|
['6 Entry editor, all states', 'Available now', ''],
|
||||||
|
['7 Relation field and picker', 'Later', ''],
|
||||||
|
['8 Permissions grid', 'Later', ''],
|
||||||
|
['9 Schema export and import', 'Later', ''],
|
||||||
|
['Filters on custom fields', 'Later', ''],
|
||||||
|
['Publish and draft state for entries', 'Later', 'Not drawn'],
|
||||||
|
['Public (anonymous) read access', 'Later', 'Not drawn'],
|
||||||
|
['Activity log entries for types and entries', 'Later', 'Not drawn']] },
|
||||||
|
{ title: 'Routes', tpl: '190px 280px 200px minmax(0,1fr)', cols: ['Route', 'Screen', 'Auth', 'API'], rows: [
|
||||||
|
['/schema', 'Schema list', 'Owner or admin. Others get the 403 page', 'GET /v1/content-type'],
|
||||||
|
['/schema/new', 'Schema builder, new type', 'Owner or admin', 'POST /v1/content-type'],
|
||||||
|
['/schema/:key', 'Schema builder (custom type) or read-only view (built-in)', 'Owner or admin', 'GET, PUT, DELETE /v1/content-type/{key}'],
|
||||||
|
['/content/:key', 'Entry list', 'Any verified user', 'GET /v1/content-type/{key}, GET /v1/content-type/{key}/entry'],
|
||||||
|
['/content/:key/new', 'New entry', 'Any verified user', 'POST /v1/content-type/{key}/entry'],
|
||||||
|
['/content/:key/:id', 'Entry editor', 'Any verified user', 'GET, PUT, DELETE /v1/content-type/{key}/entry/{id}'],
|
||||||
|
['/settings/permissions (later)', 'Permissions grid', 'Owner or admin', 'Not built'],
|
||||||
|
['/content/:key query', 'page, size (5, 25, 50, 100; default 25), sort=<id|created_at|updated_at>:<asc|desc>, default updated_at:desc', 'Any verified user', 'Defaults omitted from the URL. Query: page, size, sort=<id|created_at|updated_at>:<asc|desc>, default updated_at:desc. The response carries total, page, size and sort']] },
|
||||||
|
{ title: 'New components and their Nuxt UI mapping', tpl: '210px 110px 330px minmax(0,1fr)', cols: ['Component', 'Status', 'Nuxt UI', 'Why an existing one does not fit'], rows: [
|
||||||
|
['SchemaTable', 'New', 'UTable; below 640 px a list of UCard', 'Same pattern as SitesTable. Built-in rows add the lock and a Built-in badge'],
|
||||||
|
['BuiltInBadge', 'New', 'UBadge outline + lock icon', 'Existing badges have no lock; same size as the Linked badge'],
|
||||||
|
['FieldList', 'New', 'List of UButton rows, useSortable, UBadge', 'No Nuxt UI sortable list. Keyboard: the grip is a button; Space picks up, arrows move, Space drops, Esc cancels. Move up and Move down buttons on the selected row. Same approach as AuthorList'],
|
||||||
|
['FieldInspector', 'New', 'UForm, UFormField, UInput, UInputNumber, UInputDate, USelect, UTextarea, USwitch', 'Composition only. Controls follow the field type'],
|
||||||
|
['FieldTypePicker', 'New', 'URadioGroup variant="card" in a grid, icon in the label', 'Existing radio cards fit; only the icon and the lock state are added'],
|
||||||
|
['KeyField', 'Existing', 'SlugField (UInput + UButton + UBadge)', 'Reused for the type key and field keys. Locked variant already exists'],
|
||||||
|
['ChoicesEditor', 'New', 'UInput + UButton rows, useSortable', 'UInputTags can\'t reorder or flag a blank or duplicate per row'],
|
||||||
|
['ApiPreview', 'New', 'UCollapsible + CodeSnippet + UButton', 'CodeSnippet is reused. Sheet on mobile'],
|
||||||
|
['ChangeReview', 'New', 'UModal (sheet on mobile), UBadge, list rows', 'Dialog pattern unchanged. Rows reuse the UAlert-style row of SuggestionList'],
|
||||||
|
['SchemaRefusal, DeleteTypeDialog', 'New', 'UModal + UAlert', 'Dialog pattern unchanged. Delete uses color="error"'],
|
||||||
|
['ContentNavGroup', 'New', 'UNavigationMenu group "Content" (NavGroup)', 'Adds the 5 + selected cap, "Show all N" and the collapsed mobile row'],
|
||||||
|
['EntryTable', 'New', 'UTable with column visibility', 'Cells per field type (FieldCell). Cards on mobile'],
|
||||||
|
['ColumnPicker', 'New', 'UPopover + UCheckbox list; bottom sheet on mobile', 'UDropdownMenu closes on each pick and has no cap message'],
|
||||||
|
['SortSelect', 'New', 'USelect + UButton icon', 'ID, Created and Updated only'],
|
||||||
|
['FieldControl', 'New', 'UInput, UInputNumber, UInputDate, USelect, USwitch (the single toggle), MarkdownField', 'One switch per field type, generated from the schema'],
|
||||||
|
['MarkdownField', 'New', 'UTextarea + UTabs (Write, Preview) + toolbar of UButton', 'The article editor is a full document editor. This is a compact one'],
|
||||||
|
['FieldCell', 'New', 'text, UBadge outline (choice), icon + text (yes or no)', 'Renders one value per type, with the empty dash'],
|
||||||
|
['EntryForm', 'New', 'UForm generated from the schema', 'Provenance footer, schema-changed alert'],
|
||||||
|
['RelationPicker (later)', 'New', 'URadioGroup card + USelect', 'Sentence preview is text'],
|
||||||
|
['RelationField (later)', 'New', 'UInputMenu multiple', 'Chips and search'],
|
||||||
|
['PermissionsGrid (later)', 'New', 'UTable + UCheckbox; UCard list on mobile', ''],
|
||||||
|
['SchemaImportDialog (later)', 'New', 'UModal + UFileUpload', '']] },
|
||||||
|
{ title: 'Errors to copy', tpl: '300px 70px minmax(0,1fr)', cols: ['Error', 'HTTP', 'Copy and place'], rows: [
|
||||||
|
['content_type_not_found', '404', 'Page: "Content type not found · It may have been deleted, or the address may be mistyped."'],
|
||||||
|
['entry_not_found', '404', 'Page: "Entry not found · It may have been deleted by someone else."'],
|
||||||
|
['content_type_key_taken', '409', 'Under the key: "The key "events" is already used by another content type. Choose a different key."'],
|
||||||
|
['content_type_has_entries', '409', 'Delete dialog: "Recipes now has entries · Someone added an entry after this page loaded, so nothing was deleted. Delete the entries first, then try again."'],
|
||||||
|
['invalid_content_type_key', '400', 'Under the key: "Use 2 to 40 lowercase letters, digits or hyphens."'],
|
||||||
|
['invalid_field', '400', 'On the marked field, per rule (label, key, limits, default, choices). If the client missed one: "Check the fields marked in the list."'],
|
||||||
|
['schema_incompatible', '422', 'Refusal dialog: "Nothing was changed · RenewCMS refused the changes because some entries don\'t fit the new fields. It doesn\'t say which entries."'],
|
||||||
|
['invalid_entry: key: required', '422', '"Fill in Title." (date: "Pick a date for Starts on.", choice: "Choose an option for Category.")'],
|
||||||
|
['invalid_entry: key: type', '422', '"Title must be text." / "must be a number." / "must be yes or no." / "must be a date, like 2026-11-21."'],
|
||||||
|
['invalid_entry: key: min, max', '422', 'Text: "needs at least N characters", "can be up to N characters". Number: "must be at least N", "must be at most N". Date: "can\'t be before D", "can\'t be after D"'],
|
||||||
|
['invalid_entry: key: options', '422', '"Choose one of: Talk, Workshop or Meetup."'],
|
||||||
|
['invalid_entry: key: unique', '409', '"Another entry already uses this Title. Enter a different one." plus the alert "Not saved"'],
|
||||||
|
['invalid_entry: key: unknown_field', '422', 'Alert "The fields of Events changed", button Reload form'],
|
||||||
|
['401', '401', 'Existing: redirect to /login?redirect=…&reason=expired'],
|
||||||
|
['403', '403', 'Unverified: redirect to /register/pending. Wrong role on /schema: "You don\'t have access to Schema"'],
|
||||||
|
['400, 500', '', 'Existing table. Saves: "Couldn\'t save the … Something went wrong on our side. Your changes are still here. Try again in a moment."']] },
|
||||||
|
{ title: 'Needs backend', tpl: '40px minmax(0,1fr)', cols: ['#', 'What the design assumes'], rows: [
|
||||||
|
['1', 'Built-in types and their fields. GET /v1/content-type returns custom types only, so the read-only views use static client data (sample counts on the board are illustrative). To be closed in a backend slice before the SPA work.'],
|
||||||
|
['2', 'Display names for created_by and updated_by. They are user ids and the user list is not open to every role. To be closed in the same slice.'],
|
||||||
|
['3', 'A per-type icon. It does not exist, so the sidebar uses one default icon. To be closed in the same slice.'],
|
||||||
|
['4', 'Later: per-change entry counts and diff (the API does not return them), relations, permissions, export and import, filters on custom fields, publish and draft, public read, activity log.']] },
|
||||||
|
{ title: 'Decisions to confirm', tpl: '40px minmax(0,1fr)', cols: ['#', 'Decision'], rows: [
|
||||||
|
['1', 'Confirmed: field keys and types lock per field once saved. Fields added since the last save can still change both. This is a client rule: a PUT with a changed key would remove one field and add another, and the server does not reject it.'],
|
||||||
|
['2', 'Confirmed: the review opens only when the type already has entries (the list response total tells the client). A type without entries saves directly.'],
|
||||||
|
['3', 'Confirmed: a new type starts with one field (Title), because a type needs at least one field.'],
|
||||||
|
['4', 'Confirmed: the type key is 2 to 40 lowercase letters, digits and hyphens, the same slug rule as Sites. A field key is different: lowercase letters, digits and underscores, starts with a letter, up to 40. The two inputs show their own rule.'],
|
||||||
|
['5', 'Yes or no is the label for the boolean type, Choice for select, Rich text for richtext.'],
|
||||||
|
['6', 'Required fields carry * and the line "Fields marked * are required." Optional fields carry nothing.'],
|
||||||
|
['7', 'A yes or no field with default false and one with no default look the same in the API sample. The inspector offers "On by default" only; no default means off. Confirm that no null default is needed.'],
|
||||||
|
['8', 'The client does not know when the schema changes while a form is open. The design relies on 422 invalid_entry (required, unknown_field) on save and then shows the reload alert.'],
|
||||||
|
['9', 'The Schema item sits after Users in the sidebar. The Content group sits under the main items.'],
|
||||||
|
['10', 'The list shows 4 field columns by default and at most 6.']] },
|
||||||
|
{ title: 'Accessibility', tpl: '220px minmax(0,1fr)', cols: ['Topic', 'Rule'], rows: [
|
||||||
|
['Reorder', 'The grip is a button with aria-label "Move Ends on". Space picks up, Up and Down move, Space drops, Esc cancels, with a polite live region ("Moving Ends on. Position 2 of 7."). Move up, Move down and Remove buttons exist on the selected row and in the mobile sheet.'],
|
||||||
|
['Focus order', 'Name, key, Save, Discard, field list (one tab stop, arrows move between rows), inspector top to bottom, API preview. Opening the inspector sheet on mobile moves focus to its title; closing returns it to the row.'],
|
||||||
|
['Focus', '2 px --ui-primary, offset 2 px, as everywhere.'],
|
||||||
|
['Labels and errors', 'Every control has a visible label. Error text is tied to its input with aria-describedby and aria-invalid. Rows with errors also show an icon, not only a red border.'],
|
||||||
|
['Type picker', 'A radio group. The locked state sets aria-disabled and the line "Can\'t change after saving" is read with the group.'],
|
||||||
|
['Counters', 'Character counters are polite live regions on pause, not on every key.'],
|
||||||
|
['Contrast', 'Tokens already computed in foundations.md. Muted text is never placed on sand; selected tiles use --rc-on-sand for their description.'],
|
||||||
|
['Touch', 'Controls are 44 px on mobile. The inspector, columns and API preview are bottom sheets.']] },
|
||||||
|
...mfTables
|
||||||
|
]
|
||||||
|
|
||||||
@@ -54,6 +54,19 @@ Glossary pass 2, changes made: activity log lines "Removed N expired invites" an
|
|||||||
| 404 site_not_found (sitemap) | GET /v1/site/{key}/sitemap, unknown key. The body is the code `site_not_found`, shown on Integration in the code style (not rewritten as prose). |
|
| 404 site_not_found (sitemap) | GET /v1/site/{key}/sitemap, unknown key. The body is the code `site_not_found`, shown on Integration in the code style (not rewritten as prose). |
|
||||||
| 400 (sitemap page or size) | "The request cannot be processed due to a mismatch in the format of the body." (same text as the other routes on Integration) |
|
| 400 (sitemap page or size) | "The request cannot be processed due to a mismatch in the format of the body." (same text as the other routes on Integration) |
|
||||||
| 403 owner_only vs article SEO | Integration note under the 403 row: "Site SEO defaults are owner only. Article SEO fields need only the right to edit the article." |
|
| 403 owner_only vs article SEO | Integration note under the 403 row: "Site SEO defaults are owner only. Article SEO fields need only the right to edit the article." |
|
||||||
|
| 404 content_type_not_found | Page: "Content type not found · It may have been deleted, or the address may be mistyped." |
|
||||||
|
| 404 entry_not_found | Page: "Entry not found · It may have been deleted by someone else." |
|
||||||
|
| 409 content_type_key_taken | Under the key: "The key "events" is already used by another content type. Choose a different key." |
|
||||||
|
| 409 content_type_has_entries | Delete dialog: "Recipes now has entries · Someone added an entry after this page loaded, so nothing was deleted. Delete the entries first, then try again." |
|
||||||
|
| 400 invalid_content_type_key | Under the key: "Use 2 to 40 lowercase letters, digits or hyphens." |
|
||||||
|
| 400 invalid_field | On the marked field, per rule (label, key, limits, default, choices). If the client missed one: "Check the fields marked in the list." |
|
||||||
|
| 409 schema_incompatible | Refusal dialog: "Nothing was changed · RenewCMS refused the changes because some entries don't fit the new fields. It doesn't say which entries." |
|
||||||
|
| 422 invalid_entry: key: required | "Fill in Title." (date: "Pick a date for Starts on.", choice: "Choose an option for Category.") |
|
||||||
|
| 422 invalid_entry: key: type | "Title must be text." / "must be a number." / "must be yes or no." / "must be a date, like 2026-11-21." |
|
||||||
|
| 422 invalid_entry: key: min, max | Text: "needs at least N characters", "can be up to N characters". Number: "must be at least N", "must be at most N". Date: "can't be before D", "can't be after D" |
|
||||||
|
| 422 invalid_entry: key: options | "Choose one of: Talk, Workshop or Meetup." |
|
||||||
|
| 409 invalid_entry: key: unique | "Another entry already uses this Title. Enter a different one." plus the alert "Not saved" |
|
||||||
|
| 422 invalid_entry: key: unknown_field | Alert "The fields of Events changed", button Reload form |
|
||||||
| 500 – | "Couldn't save the site. Your changes are still here. Try again in a moment." / "Couldn't save the author. Your changes are still here. Try again in a moment." / "Couldn't create the author" / "The article is unchanged. Try again in a moment." (notice inside the panel or dialog) |
|
| 500 – | "Couldn't save the site. Your changes are still here. Try again in a moment." / "Couldn't save the author. Your changes are still here. Try again in a moment." / "Couldn't create the author" / "The article is unchanged. Try again in a moment." (notice inside the panel or dialog) |
|
||||||
|
|
||||||
## Public image 400 bodies
|
## Public image 400 bodies
|
||||||
@@ -79,3 +92,18 @@ screens/<name>.md, section "Copy per state" (generated from the board source).
|
|||||||
|
|
||||||
## SEO round
|
## SEO round
|
||||||
Frames: Editor: search and sharing (24), Editor: what the frontend gets (6), Sites: SEO defaults (5), Articles: search status (3). Each is drawn desktop and mobile; light and dark follow the theme switch. None is clock-sensitive: dates in the API preview are fixed sample values. Disabled state: all fields at 40% while saving. Validation: slug taken, canonical not absolute, title template without %title%, excerpt over 300. Suggestions never block saving or publishing. Copy per state: screens/editor.md, articles.md, sites.md.
|
Frames: Editor: search and sharing (24), Editor: what the frontend gets (6), Sites: SEO defaults (5), Articles: search status (3). Each is drawn desktop and mobile; light and dark follow the theme switch. None is clock-sensitive: dates in the API preview are fixed sample values. Disabled state: all fields at 40% while saving. Validation: slug taken, canonical not absolute, title template without %title%, excerpt over 300. Suggestions never block saving or publishing. Copy per state: screens/editor.md, articles.md, sites.md.
|
||||||
|
|
||||||
|
|
||||||
|
## Custom content types
|
||||||
|
Groups on `RenewCMS Screens Schema.dc.html`: 1 Schema list (6), 2 Schema builder (16), 3 Review and delete (7), 4 Field types (6), 5 Content and entry list (9), 6 Entry editor (13), 7 Relations (3), 8 Permissions (2), 9 Export and import (3). 65 states, 56 available now and 9 later. Each has a 1440 and a 390 frame; light and dark follow the theme switch. Nothing is clock-sensitive. Tag per state: "Available now" or "Later". Copy per state: screens/schema.md, content.md, entry.md, schema-later.md.
|
||||||
|
|
||||||
|
Roles: owners and admins see Schema and edit types. Any verified user sees the Content group and reads and writes entries. A user who is not owner or admin and opens /schema gets "You don't have access to Schema".
|
||||||
|
|
||||||
|
Keys: a type key is 2 to 40 lowercase letters, digits and hyphens (chosen at creation, never changes). A field key is lowercase letters, digits and underscores, starts with a letter, up to 40 (editable until its field is first saved). The two inputs show their own rule.
|
||||||
|
|
||||||
|
Schema changes with entries: Save opens the review ("Add 2 fields, change 1, remove 1"); Apply sends the PUT; schema_incompatible shows "Nothing was changed" and names the kind of change that likely caused it, never an entry. A type with entries cannot be deleted ("You can't delete Events yet").
|
||||||
|
|
||||||
|
Entry rules, 422 except unique (409): required, type, min, max, options, unique, unknown_field. Messages are per type and drawn in the field-type gallery (group "Field types").
|
||||||
|
|
||||||
|
## 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).
|
||||||
@@ -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
|
||||||
|
|||||||
@@ -0,0 +1,77 @@
|
|||||||
|
# Privacy and personal data
|
||||||
|
|
||||||
|
This page is for operators: whoever runs a RenewCMS instance is the data controller for it under the GDPR. It lists what the software stores about people, where, for how long, and what it sends elsewhere, so you can fill in your record of processing (art. 30), write your privacy notice (art. 13) and answer requests from the people concerned. It describes the software, not your obligations; it is not legal advice.
|
||||||
|
|
||||||
|
## Who is concerned
|
||||||
|
|
||||||
|
- **Back-office users**: the owner and the admins they invite.
|
||||||
|
- **Invitees** who have not accepted yet.
|
||||||
|
- **People named in content**: authors, and anyone your editors write about or photograph.
|
||||||
|
- **Anyone who performs an audited action** (logging in, failing to log in, changing anything) has their IP address and browser recorded in the activity log.
|
||||||
|
|
||||||
|
Readers of your public site are not tracked by RenewCMS: the public routes set no cookie and log nothing in production.
|
||||||
|
|
||||||
|
## What is stored, and for how long
|
||||||
|
|
||||||
|
| Data | Where | Kept |
|
||||||
|
|---|---|---|
|
||||||
|
| Username, email, display name, role, bcrypt password hash | `users` table | Until the account is deleted (see [Gaps](#gaps)). |
|
||||||
|
| Verification and password-reset codes | `users` table, bcrypt-hashed | Verification: until the account is verified. Reset: one hour, then useless; cleared when used. |
|
||||||
|
| Unverified sign-ups | `users` table | Deleted automatically 7 days after their verification code expired. |
|
||||||
|
| Invites: invitee email, hashed code, inviter | `invites` table | Deleted automatically 30 days after they expired or were accepted. |
|
||||||
|
| Sessions | The `jwt` cookie in the user's browser, valid 24 hours | Logging out revokes the session on the server; the revocation (a random id and an expiry, nothing else) is deleted once the session would have expired anyway. |
|
||||||
|
| API keys: name, prefix, SHA-256 hash, creator, last use | `api_keys` table | Until revoked. A revoked key stays listed. |
|
||||||
|
| Activity log: who (user id and name, API key name, or the username typed at a failed login), what, when, IP address, browser (user agent, truncated to 255 characters) | `audit_events` table | Settings → Activity: 30, 90 (default), 365 days or forever, and an optional size cap. Cleaned up once a night, at 03:00 server time. |
|
||||||
|
| Authors: name, slug, bio, avatar, website, social links; the linked user's email is shown to admins | `authors` table | Until deleted. |
|
||||||
|
| Articles and custom entries | `articles`, `entries` tables | Deleted articles are soft-deleted: the row and its content stay in the database (see [Gaps](#gaps)). |
|
||||||
|
| Uploaded images | `UPLOAD_DIR` or the S3 bucket, plus the `images` table (file name, size, uploader) | Until deleted from the media library. Deleted images are soft-deleted in the table; the file itself is removed. |
|
||||||
|
|
||||||
|
### Photo metadata
|
||||||
|
|
||||||
|
Since this version, uploads are cleaned before they are stored. JPEG, PNG and WebP files lose their EXIF (GPS position, camera serial number, date), XMP, IPTC, comments and text chunks; only the orientation is kept, so rotated photos still display correctly. The pixels are not re-encoded. SVG files are stored as uploaded. **Images uploaded with an earlier version are not cleaned retroactively**: if they may carry GPS positions, download, clean and re-upload them, or merge them into a cleaned copy from the media library.
|
||||||
|
|
||||||
|
### Activity log retention
|
||||||
|
|
||||||
|
For security logs, the CNIL generally recommends keeping access logs between six months and a year. The default of 90 days is shorter; choose 365 days in Settings if that suits your purpose. Avoid "Forever": it keeps IP addresses indefinitely, which the storage-limitation principle rarely justifies.
|
||||||
|
|
||||||
|
## Cookies and browser storage
|
||||||
|
|
||||||
|
- `jwt`: the session cookie. HttpOnly, `SameSite=Lax`, `Secure` in production, 24 hours. Strictly necessary for the back office, so it needs no consent (ePrivacy art. 5(3); in France, Loi Informatique et Libertés art. 82).
|
||||||
|
- `localStorage` on the user's device holds interface choices only: language (`renewcms-language`), page sizes, open or collapsed panels, dismissed hints and columns. `sessionStorage` holds unsaved article drafts until the tab closes. None of it is sent to the server or to anyone else, and it needs no consent either.
|
||||||
|
|
||||||
|
RenewCMS sets no analytics, advertising or third-party cookie, so no consent banner is needed for the back office. Your public site may need one if *it* adds trackers.
|
||||||
|
|
||||||
|
## What leaves the server
|
||||||
|
|
||||||
|
| Destination | When | What |
|
||||||
|
|---|---|---|
|
||||||
|
| Your SMTP provider (`SMTP_HOST`) | Sign-up, invite, password reset | Recipient address, the message (with a one-time link). STARTTLS or implicit TLS is required for any non-loopback host unless you set `SMTP_ALLOW_INSECURE=true`. |
|
||||||
|
| Your S3 provider, if `STORAGE_DRIVER=s3` | Every upload and image read | The image files. |
|
||||||
|
| `UPDATE_FEED_URL` (default `https://git.floriansylvain.fr`) | Only when the owner clicks "Check for updates" or downloads one | The server's IP address and a standard HTTP request. No account or content data. |
|
||||||
|
|
||||||
|
The back office loads nothing from third parties: fonts, icons and scripts are served by RenewCMS itself, and the Content-Security-Policy forbids any other source. Pick EU-based SMTP and storage providers, or make sure transfer safeguards (art. 44 and following) cover them, and list them as processors.
|
||||||
|
|
||||||
|
## Security measures you can cite (art. 32)
|
||||||
|
|
||||||
|
- Passwords are hashed with bcrypt (cost 12). One-time codes are random UUIDs, stored hashed, single-use and short-lived. API keys are 256-bit random values stored as SHA-256 hashes.
|
||||||
|
- Login, password-reset and invite routes are rate-limited per client IP; failed logins are recorded as security events.
|
||||||
|
- Sessions are revocable: logout ends one session, a password reset ends all of them and revokes the user's API keys.
|
||||||
|
- Cross-site writes are refused, cookies are `SameSite=Lax`, and a strict Content-Security-Policy, `X-Frame-Options: DENY` and HSTS (in production) are sent.
|
||||||
|
- The server refuses to start with a short or example `JWT_SECRET`.
|
||||||
|
- Release binaries are signed (ed25519) and checked before a browser update is installed.
|
||||||
|
|
||||||
|
## Answering requests from the people concerned
|
||||||
|
|
||||||
|
- **Access and portability (art. 15 and 20)**: there is no self-service export yet. The data of a user is their row in `users`, their author profile, their API keys and the activity events where they are the actor; an owner can export the activity log as CSV from the Activity page and filter it by person.
|
||||||
|
- **Rectification (art. 16)**: users can change their display name and author profile themselves. Changing an email address currently needs a database edit.
|
||||||
|
- **Erasure (art. 17)**: an unverified account can cancel its own registration. Deleting a verified user has no button yet; see [Gaps](#gaps).
|
||||||
|
|
||||||
|
## Gaps
|
||||||
|
|
||||||
|
These are known and tracked; until they are fixed, handle them by hand.
|
||||||
|
|
||||||
|
- No way to delete a verified user or remove an admin from the interface.
|
||||||
|
- No self-service export or email change.
|
||||||
|
- Soft-deleted articles and images keep their rows indefinitely.
|
||||||
|
- The username typed at a failed login is stored as typed, so a password typed in the wrong field can end up in the activity log; clean such events by hand if it happens.
|
||||||
|
- Images uploaded before metadata stripping keep their metadata.
|
||||||
@@ -40,3 +40,6 @@ Each body lives in `docs/releases/<tag>.md`. Publish with `tea releases create -
|
|||||||
| `v3.2.0-beta` | Article lists, editor links and activity export |
|
| `v3.2.0-beta` | Article lists, editor links and activity export |
|
||||||
| `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.1-beta` | Media field and security updates |
|
||||||
|
| `v3.4.2-beta` | Security and privacy hardening |
|
||||||
@@ -0,0 +1,70 @@
|
|||||||
|
This release adds custom content types: owners and admins define structured types such as Events or Recipes, and any verified user creates, edits and deletes their entries from the app or through a generic API. The built-in articles, authors, sites, media and users are unchanged.
|
||||||
|
|
||||||
|
## New
|
||||||
|
|
||||||
|
**Custom content types**
|
||||||
|
|
||||||
|
- A content type is a name, a key, an optional icon and an ordered list of 1 to 50 fields. The key is a slug of 2 to 40 characters and cannot be changed after creation.
|
||||||
|
- A field has a key, a label, one of six types (text, rich text, number, boolean, date or select) and the options that fit its type: required, unique, a default value, a minimum and a maximum, and a list of choices for a select.
|
||||||
|
- Changing a type that already has entries is checked first. A new required field needs a default, a removed select choice cannot still be in use, a lowered maximum cannot be below a stored value, and a field cannot become unique while stored values collide. Changing a field's type is refused. Removing a field drops its values from the entries the next time they are read or saved.
|
||||||
|
- A content type with entries cannot be deleted.
|
||||||
|
|
||||||
|
**Schema screens**
|
||||||
|
|
||||||
|
- The new Schema item in the sidebar, after Users, opens a screen that lists every content type, custom and built-in, for owners and admins. Other users get a 403 page and no sidebar entry.
|
||||||
|
- The schema builder creates and edits a custom type: add, remove and reorder fields, pick an icon, set each field's options in an inspector, and see the effect of a change before applying it. When the type already has entries, a review step shows how many entries are affected and names what the save will refuse.
|
||||||
|
- A type is deleted from its builder, with a confirmation, and a type that still has entries explains why it cannot be deleted and links to them.
|
||||||
|
- The built-in types (articles, authors, sites, media and users) can be opened read-only to see their fields.
|
||||||
|
- The sidebar has a Content group with your custom types, showing the first few and a "Show all" link when there are many.
|
||||||
|
|
||||||
|
**Entries**
|
||||||
|
|
||||||
|
- The entry list at `/content/<key>` shows a table on desktop and cards on mobile. It is paged (5, 25, 50 or 100) and sortable by last updated, created or id, and the page, size and sort are kept in the address so a reload or a shared link opens the same view.
|
||||||
|
- A Columns menu chooses which fields to show, up to six, and remembers the choice per type on this browser. By default the first four fields are shown.
|
||||||
|
- The entry editor at `/content/<key>/new` and `/content/<key>/<id>` builds its form from the type. Each field type has its own control: a text box, a Markdown editor with a toolbar and preview, a number input, a switch, a date picker and a select.
|
||||||
|
- Defaults are pre-filled and tagged. Rules (required, minimum, maximum, choices) are checked when you save, every error is shown at once, and focus goes to the first one. A message from the server, such as a duplicate value in a unique field, is shown on its field.
|
||||||
|
- "Saved at" shows the time the server answered. A form with unsaved changes asks before you leave it. Deleting an entry asks for confirmation.
|
||||||
|
- When the type's fields changed since the form was opened, the form is locked and offers "Reload form".
|
||||||
|
- The entry list and editor show who created and last updated each entry, by display name.
|
||||||
|
|
||||||
|
## Improvements and fixes
|
||||||
|
|
||||||
|
- Every page-size menu now centres its items vertically.
|
||||||
|
- The Columns and Sort menus of the entry list align their items correctly.
|
||||||
|
- The builder's accessibility issues from the design review are fixed.
|
||||||
|
- Markdown in entries is rendered with raw HTML disabled, images disabled and only http, https and mailto links active.
|
||||||
|
|
||||||
|
## API
|
||||||
|
|
||||||
|
- `GET /v1/content-type` lists the custom content types and `GET /v1/content-type/{key}` reads one. Both are open to any verified user or API key. A missing type answers `404` `content_type_not_found`.
|
||||||
|
- `POST /v1/content-type`, `PUT /v1/content-type/{key}` and `DELETE /v1/content-type/{key}` are for owners and admins. A key already in use answers `409` `content_type_key_taken`, an invalid key `400` `invalid_content_type_key`, an invalid field list or icon `422` `invalid_field`, a change the stored entries cannot take `409` `schema_incompatible`, and deleting a type with entries `409` `content_type_has_entries`. A delete answers `204`.
|
||||||
|
- A content type response has `id`, `key`, `name`, `icon`, `fields`, `created_at` and `updated_at`. The icon is `null` or a lowercase name of up to 40 characters, and a `PUT` replaces the whole type, so an absent icon clears it.
|
||||||
|
- `GET /v1/content-type/{key}/entry` lists entries as `{ items, total, page, size }`, with `page`, `size` (5, 25, 50 or 100, default 25) and `sort` (`id`, `created_at` or `updated_at`, then `:asc` or `:desc`, default `updated_at:desc`). An invalid value answers `400`, and a page past the end answers an empty `items` with the real `total`.
|
||||||
|
- `POST /v1/content-type/{key}/entry` creates an entry from `{ "data": { ... } }`, applying defaults, and `PUT /v1/content-type/{key}/entry/{id}` replaces its data. `GET` and `DELETE` on `/v1/content-type/{key}/entry/{id}` read and delete it, and a delete answers `204`. An entry that breaks the schema answers `422` `invalid_entry: <field>: <rule>`, a duplicate in a unique field `409` with the same shape, and a missing entry `404` `entry_not_found`.
|
||||||
|
- An entry response has `id`, `content_type` (the type's key), `data`, `created_by`, `updated_by`, `created_at` and `updated_at`.
|
||||||
|
- `GET /v1/builtin-type` and `GET /v1/builtin-type/{key}` return the read-only description of the built-in types. An unknown key answers `404` `builtin_type_not_found`.
|
||||||
|
- `GET /v1/user/lookup?ids=1,2,3` resolves display names for the users who created or updated entries. It is open to any verified user or API key.
|
||||||
|
|
||||||
|
## Under the hood
|
||||||
|
|
||||||
|
- Content types and entries live in two generic tables, with the fields and the entry data stored as JSON, so no schema change runs at runtime and the SQL stays portable across SQLite, MySQL, MariaDB and PostgreSQL.
|
||||||
|
- Schema and entry validation lives in the domain and the use cases, and the new handlers only decode requests and map errors.
|
||||||
|
- The app has one registry of field types, used by the builder, the list cells and the entry form.
|
||||||
|
- The list, builder and editor share their delete, save and unsaved-changes machinery, and the dashboard shell no longer calls the logout API or preloads content types itself.
|
||||||
|
- New dependency: `markdown-it`, with its type definitions, for the Markdown preview.
|
||||||
|
- Feature specs and QA procedures for each slice are in `features/`.
|
||||||
|
|
||||||
|
## Upgrading
|
||||||
|
|
||||||
|
- Replace the binary, or pull the new image. Back up the database first as usual.
|
||||||
|
- The first start after the upgrade creates the two new tables for content types and entries. Nothing else changes, existing data is untouched, and a second start changes nothing.
|
||||||
|
- No new environment variable is needed.
|
||||||
|
|
||||||
|
## Known limitations
|
||||||
|
|
||||||
|
- Entries cannot be filtered or searched by their field values yet.
|
||||||
|
- There are no relations between types, no media fields and no permissions grid, so every verified user can read and write the entries of every type.
|
||||||
|
- A type cannot be exported or imported yet.
|
||||||
|
- The key `new` is not reserved, so a type with that key cannot be opened from its entry list.
|
||||||
|
- On mobile, the entry list has no link to the builder; open the Schema item from the menu instead.
|
||||||
|
- Moving from one entry to another by editing the address drops unsaved edits without asking.
|
||||||
@@ -0,0 +1,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.
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
This release hardens sign-in, sessions and mail against common attacks, and reduces the personal data RenewCMS keeps or shares, following a security, GDPR and CNIL review.
|
||||||
|
|
||||||
|
## Improvements and fixes
|
||||||
|
|
||||||
|
- Signing out now ends the session on the server. A copied session cookie stops working at once, while the same user's other sessions keep working.
|
||||||
|
- The limit on login, password reset and invitation attempts now applies per client address. Before, opening a new connection reset the count, so the limit could be bypassed.
|
||||||
|
- Requests that change data and come from another website are refused, and the session cookie is now `SameSite=Lax`. A malicious page can no longer act on behalf of a signed-in user.
|
||||||
|
- A session made stale by a password reset can no longer read draft articles.
|
||||||
|
- Signing in with an unknown username now takes as long as signing in with a wrong password, so response times no longer reveal which usernames exist.
|
||||||
|
- A password longer than 72 bytes is refused with a clear message, where it used to cause a server error.
|
||||||
|
- Uploaded JPEG, PNG and WebP images lose their hidden metadata (GPS position, camera serial number, dates, comments) before they are stored. Pixels and colour profiles are untouched, and rotated photos keep their orientation.
|
||||||
|
- The back office no longer loads its fonts from Google. The fonts ship with RenewCMS, so no visitor IP address is sent to a third party.
|
||||||
|
- Unverified sign-ups are deleted 7 days after their verification code expired, and invitations 30 days after they expired or were accepted.
|
||||||
|
- Exported activity CSV files also neutralise cells starting with a tab or a carriage return, which spreadsheets could otherwise treat as formulas.
|
||||||
|
|
||||||
|
## API
|
||||||
|
|
||||||
|
- Changed: `POST`, `PUT`, `PATCH` and `DELETE` requests sent by a browser from another origin without an `Authorization` header answer `403` "Cross-origin requests are not allowed." Scripts on other origins must send their API key.
|
||||||
|
- Changed: `POST /v1/auth/logout` revokes the presented session. It answers `500` only when the revocation cannot be stored, and clears the cookie either way.
|
||||||
|
- `POST /v1/auth/register`, `POST /v1/auth/password-reset/confirm` and `POST /v1/auth/invite/accept` answer `400` "The password must be 72 bytes or fewer." for longer passwords.
|
||||||
|
|
||||||
|
## Under the hood
|
||||||
|
|
||||||
|
- A new `docs/privacy.md` lists the personal data RenewCMS stores, how long it is kept, the cookies, what leaves the server and how to answer access or erasure requests. It is meant to help operators with their record of processing and privacy notice.
|
||||||
|
- Cross-origin protection uses the Go standard library, so no dependency was added.
|
||||||
|
- New feature specs and tests cover the hardening, in `features/security_privacy_hardening.feature`.
|
||||||
|
|
||||||
|
## Upgrading
|
||||||
|
|
||||||
|
- Replace the binary, or pull the new image. Back up the database first as usual.
|
||||||
|
- A new `revoked_sessions` table is created automatically at startup.
|
||||||
|
- The server now refuses to start when `JWT_SECRET` is shorter than 32 bytes or is still an example value. Generate one with `openssl rand -hex 32`. Changing it signs everyone out.
|
||||||
|
- Mail to an SMTP server on another host now requires encryption (STARTTLS, or port 465). If your relay offers neither, set the new `SMTP_ALLOW_INSECURE=true`. Credentials are still never sent unencrypted.
|
||||||
|
- Sessions created before v3.4.1-beta, which carry no expiry, are refused. Those users sign in once more.
|
||||||
|
|
||||||
|
## Known limitations
|
||||||
|
|
||||||
|
- Images uploaded before this release keep their metadata. Re-upload them if they may contain GPS positions.
|
||||||
|
- Verified users still cannot be deleted from the interface, and there is no self-service data export yet.
|
||||||
@@ -358,6 +358,8 @@ Feature: The back-office keeps an append-only activity log that owners can read
|
|||||||
| target | +1+1 | '+1+1 |
|
| target | +1+1 | '+1+1 |
|
||||||
| target | -2 | '-2 |
|
| target | -2 | '-2 |
|
||||||
| actor | @SUM(A1) | '@SUM(A1) |
|
| actor | @SUM(A1) | '@SUM(A1) |
|
||||||
|
| target | \t=cmd | '\t=cmd |
|
||||||
|
| target | \r=cmd | '\r=cmd |
|
||||||
| target | Spring release | Spring release |
|
| target | Spring release | Spring release |
|
||||||
| target | a=b | a=b |
|
| target | a=b | a=b |
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,469 @@
|
|||||||
|
Feature: Entry editor of a custom content type
|
||||||
|
As a verified user
|
||||||
|
I want to create, edit and delete an entry of a custom content type
|
||||||
|
So that the content follows the fields of its type
|
||||||
|
|
||||||
|
Background:
|
||||||
|
Given the SPA calls the API with relative URLs under /v1 and the "jwt" HttpOnly cookie
|
||||||
|
And API errors are plain text
|
||||||
|
And the routes are /content/:key/new and /content/:key/:id with meta auth "verified" and title "Content", per docs/design/screens/entry.md group "6 Entry editor", states 1 to 13
|
||||||
|
And the structural prep of this slice is done first: ContentEntries is presentational with one owner of the list-view state, useContentTypes is split into entry and user-lookup parts, and one field-type registry (lib/fieldTypes) serves the schema builder, the list cells and this form
|
||||||
|
And the page requests GET /v1/content-type/{key} (the type) and, on /content/:key/:id, GET /v1/content-type/{key}/entry/{id} at the same time
|
||||||
|
And an entry is {id, content_type, data, created_by, updated_by, created_at, updated_at}, with content_type the key string
|
||||||
|
And POST /v1/content-type/{key}/entry answers 201 with the entry, PUT .../entry/{id} answers 200 with the entry and DELETE answers 204 with no body
|
||||||
|
And POST and PUT take {"data": {...}}; PUT replaces the whole entry and keeps created_by and created_at
|
||||||
|
And the API refuses with 404 content_type_not_found, 404 entry_not_found, 400 for an id that is not a uint32, 401, 403, 409 "invalid_entry: <key>: unique" and 422 "invalid_entry: <key>: <required|type|min|max|options|unknown_field>", and the body names only one field per answer
|
||||||
|
And any verified user may read and write entries; there is no owner or admin gate in the SPA
|
||||||
|
And a "/content/:key/:id" whose id is not made of digits or does not fit a uint32 shows "Entry not found" with no entry request, and "new" is the literal route
|
||||||
|
And the form is generated from the type's fields in schema order through the fieldTypes registry, with the six types text, richtext, number, boolean, date and select
|
||||||
|
And the data sent holds exactly one key per field of the loaded type, with the value or null for an empty optional field, so no default is applied by the server to a field the user cleared and no unknown key is ever sent
|
||||||
|
And a text or richtext value is counted in characters (code points) like the server, and is not trimmed
|
||||||
|
And a required field is empty when it is null, undefined or an empty string; false and 0 are values
|
||||||
|
And validation is done by the client against the loaded type before any request (required, type, min, max, options), one rule per field at a time in that order, and the server's single answer is mapped to its field when it gets past the client
|
||||||
|
And "Created by" and "Updated by" names come from GET /v1/user/lookup?ids=<distinct created_by and updated_by> sent once after the entry answers, as in features/content_entry_list.feature; a missing name reads "–" with the date kept
|
||||||
|
And dates in the footer are "12 Oct 2026, 09:14" (local time zone, 24 h)
|
||||||
|
And the leave guard is useUnsavedChangesGuard, the same "Leave without saving?" dialog as features/schema_builder_edit.feature
|
||||||
|
And the status chip is the builder's: "Saved", "Saved at HH:MM" (never "N min ago"), "Unsaved changes", "Saving…", "Save failed", plus "New entry" and "Not saved"
|
||||||
|
And the SPA adds no beforeunload prompt, as nothing else in web/src does
|
||||||
|
And Markdown is rendered with markdown-it with raw HTML disabled and only http, https and mailto links active
|
||||||
|
And every string goes through t() and has a French entry in i18n/messages.ts
|
||||||
|
And a copy tagged "(proposed copy)" is not in the design and is the coder's single point of change
|
||||||
|
|
||||||
|
Scenario: 1 New entry
|
||||||
|
Given GET /v1/content-type/events resolves 200 with the 7 fields Title, Starts on, Ends on, Online, Capacity, Category, Description
|
||||||
|
When the user navigates to /content/events/new
|
||||||
|
Then the breadcrumb reads "Content", "Events", "New entry" and the title row reads "New entry" with the subtitle "Events · Fields marked * are required."
|
||||||
|
And no entry request is sent
|
||||||
|
And the chip reads "New entry", "Cancel" and "Save" are shown, and "Delete" is not
|
||||||
|
And "Save" is enabled although nothing was typed
|
||||||
|
And each required label carries " *"
|
||||||
|
And the control of Online is Off and carries the tag "Default"
|
||||||
|
And the help under Title reads "Each entry needs a different title.", under Capacity "Between 1 and 5000.", the placeholders read "Choose an option" (Category) and "Pick a date" (Starts on, Ends on)
|
||||||
|
And the footer reads "Entry" "Not saved yet", "Created by" "–", "Updated by" "–"
|
||||||
|
And on mobile the topbar reads "New entry" with an arrow-left and no action, the chip sits under the title row, and the bottom bar holds "Cancel" and "Save"
|
||||||
|
|
||||||
|
Scenario Outline: Defaults on a new entry
|
||||||
|
Given the type has a field <field> with default <default>
|
||||||
|
When the user opens /content/events/new
|
||||||
|
Then the control holds <shown> and the tag "Default" shows next to the label
|
||||||
|
When the user changes the value
|
||||||
|
Then the tag goes
|
||||||
|
And when the user restores the default value the tag shows again
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| field | default | shown |
|
||||||
|
| Online (boolean) | false | Off |
|
||||||
|
| Capacity (number) | 100 | 100 |
|
||||||
|
| Category (select) | Talk | Talk |
|
||||||
|
| Starts on (date) | 2026-11-21 | 21 Nov 2026 |
|
||||||
|
| Title (text) | Untitled | Untitled |
|
||||||
|
| Description (richtext) | none | an empty textarea, no tag |
|
||||||
|
|
||||||
|
Scenario: Defaults are shown only on create
|
||||||
|
When the user opens /content/events/42
|
||||||
|
Then no field carries the tag "Default" and the values are those of the entry
|
||||||
|
|
||||||
|
Scenario: 2 Editing
|
||||||
|
Given GET .../entry/42 resolves 200 with the entry "Lime plaster workshop" created by 3 on 2026-10-12 09:14 and updated by 5 on 2026-10-15 11:02, and the lookup names 3 "Inès Duarte" and 5 "Marta Alves"
|
||||||
|
When the user navigates to /content/events/42
|
||||||
|
Then the breadcrumb reads "Content", "Events", "Lime plaster workshop" and the title reads "Lime plaster workshop" with the subtitle "Events · Entry 42"
|
||||||
|
And the chip reads "Saved"
|
||||||
|
And "Delete", "Cancel" and "Save" are shown, "Save" is disabled
|
||||||
|
And the controls hold the entry's values
|
||||||
|
And the footer reads "Entry" "events / 42" (mono), "Created by" "Inès Duarte · 12 Oct 2026, 09:14", "Updated by" "Marta Alves · 15 Oct 2026, 11:02"
|
||||||
|
And on mobile the topbar reads the title with an arrow-left and a trash-2 action, the chip sits under the title row, and the bottom bar holds "Cancel" and "Save" (disabled)
|
||||||
|
|
||||||
|
Scenario Outline: The page title
|
||||||
|
Given the entry 42 whose first field <first> holds <value>
|
||||||
|
When the user opens /content/events/42
|
||||||
|
Then the title and the last breadcrumb read <title>
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| first | value | title |
|
||||||
|
| Title (text) | "Lime plaster workshop" | Lime plaster workshop |
|
||||||
|
| Title (text) | null | Entry 42 |
|
||||||
|
| Body (richtext) | "First line\n\nSecond" | First line |
|
||||||
|
| Seats (number) | 18 | 18 |
|
||||||
|
|
||||||
|
Scenario: The title does not change while typing
|
||||||
|
Given /content/events/42
|
||||||
|
When the user types in Title
|
||||||
|
Then the title row and the breadcrumb keep "Lime plaster workshop" until a save answers
|
||||||
|
|
||||||
|
Scenario Outline: Form controls per field type
|
||||||
|
Given a field of type <type>
|
||||||
|
Then the control is <control> with <detail>
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| type | control | detail |
|
||||||
|
| text | UInput | a counter "n / max" when max is set |
|
||||||
|
| richtext | MarkdownField | tabs "Write" and "Preview", the toolbar bold, italic, heading, link, list, the placeholder "Write in Markdown", the help "Markdown. Switch to Preview to check the result." and a counter when max is set |
|
||||||
|
| number | UInputNumber | the placeholder "Enter a number" and minus and plus buttons; decimals are accepted |
|
||||||
|
| boolean | USwitch | the text "On" or "Off" next to it |
|
||||||
|
| date | UInputDate | the placeholder "Pick a date" and a calendar; the value is "YYYY-MM-DD" with no time-zone shift |
|
||||||
|
| select | USelect | the placeholder "Choose an option", the choices in schema order, and for an optional field a first item "None" (proposed copy) that clears it |
|
||||||
|
|
||||||
|
Scenario Outline: Help lines
|
||||||
|
Given a field <field>
|
||||||
|
Then the help under it reads <help>, and is replaced by the error when there is one
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| field | help |
|
||||||
|
| text, unique | Each entry needs a different title. (the label in lower case) |
|
||||||
|
| number, min 1, max 5000 | Between 1 and 5000. |
|
||||||
|
| number, min 1 | At least 1. (proposed copy) |
|
||||||
|
| number, max 5000 | At most 5000. (proposed copy) |
|
||||||
|
| date, min 2026-01-01, max 2027-12-31 | From 1 Jan 2026 until 31 Dec 2027. (proposed copy) |
|
||||||
|
| richtext | Markdown. Switch to Preview to check the result. |
|
||||||
|
| text, no unique, no number or date bounds | no help line |
|
||||||
|
|
||||||
|
Scenario: Layout of the generated form
|
||||||
|
Given the 7 fields of Events on a 1440 px viewport
|
||||||
|
Then Title is full width, Starts on and Ends on share a row, Online and Capacity share a row, Category and Description are each full width, in a column of at most 760 px
|
||||||
|
And a date, number or boolean field pairs with the next one if that one is also a date, number or boolean, text, richtext and select are always full width
|
||||||
|
And below md every field is full width
|
||||||
|
|
||||||
|
Scenario: 3 Unsaved changes and the counter
|
||||||
|
Given /content/events/42 with Title "Lime plaster workshop" (21 characters, max 80)
|
||||||
|
When the user types ", two days" in Title
|
||||||
|
Then the counter beside the label reads "32 / 80" in mono, muted
|
||||||
|
And the chip reads "Unsaved changes" and "Save" is enabled
|
||||||
|
And a counter over the limit reads "91 / 80" in the error colour, and typing is not blocked
|
||||||
|
And a counter shows only for a text or richtext field with a max
|
||||||
|
|
||||||
|
Scenario: An edit that is reverted is not an unsaved change
|
||||||
|
Given the user changed Capacity from 18 to 20
|
||||||
|
When the user sets it back to 18
|
||||||
|
Then the chip reads "Saved", "Save" is disabled and the leave guard does not prompt
|
||||||
|
|
||||||
|
Scenario: Cancel
|
||||||
|
Given /content/events/42, opened from the list /content/events?page=2&sort=id:asc
|
||||||
|
When the user activates "Cancel"
|
||||||
|
Then the router returns to /content/events?page=2&sort=id:asc when the previous history entry is the list of this type, else it navigates to /content/events
|
||||||
|
And the leave guard runs first when there are unsaved changes
|
||||||
|
|
||||||
|
Scenario: 4 Markdown preview
|
||||||
|
Given a richtext field holding "Two days of hands-on work with **lime putty** and old stone.\n\n- Bring work clothes\n- Lunch is included"
|
||||||
|
When the user activates the "Preview" tab
|
||||||
|
Then the textarea and the toolbar are replaced by the rendered text with a bold "lime putty" and a bulleted list of two items, in a box at least 96 px high (120 px on mobile)
|
||||||
|
And raw HTML in the value is shown as text, never rendered, and only http, https and mailto links are active
|
||||||
|
And the tab state is not an edit, and switching back to "Write" restores the textarea with its value, caret kept
|
||||||
|
And an empty value in Preview reads "Nothing to preview yet." (proposed copy)
|
||||||
|
|
||||||
|
Scenario Outline: The Markdown toolbar
|
||||||
|
Given the Write tab with the selection <selection>
|
||||||
|
When the user activates <button>
|
||||||
|
Then the textarea holds <result> and keeps the focus
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| selection | button | result |
|
||||||
|
| "lime" | Bold | **lime** |
|
||||||
|
| "lime" | Italic | _lime_ |
|
||||||
|
| "lime" | Heading | ## lime |
|
||||||
|
| "lime" | Link | [lime](url) |
|
||||||
|
| "lime" | List | - lime |
|
||||||
|
|
||||||
|
Scenario: Payload of a create
|
||||||
|
Given /content/events/new with Title "Open day", Starts on 2026-11-21, Online left at its default false, Ends on, Capacity, Category and Description left empty
|
||||||
|
When the user activates "Save"
|
||||||
|
Then POST /v1/content-type/events/entry is sent once with {"data": {"title": "Open day", "starts_on": "2026-11-21", "ends_on": null, "online": false, "capacity": null, "category": null, "description": null}}
|
||||||
|
And a number is sent as a JSON number, a boolean as true or false, a date as "YYYY-MM-DD", a select as the choice text
|
||||||
|
|
||||||
|
Scenario: Payload of an edit
|
||||||
|
Given /content/events/42 with only Capacity changed from 18 to 20
|
||||||
|
When the user activates "Save"
|
||||||
|
Then PUT /v1/content-type/events/entry/42 is sent once with every field of the type, the unchanged ones with their loaded values
|
||||||
|
And a key that the entry holds but the type no longer has is not sent
|
||||||
|
|
||||||
|
Scenario Outline: A boolean that was never set
|
||||||
|
Given a boolean field <kind> and the user never touched it
|
||||||
|
When the entry is saved
|
||||||
|
Then the data holds <sent> for it
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| kind | sent |
|
||||||
|
| optional, no default | null |
|
||||||
|
| optional, loaded as null | null |
|
||||||
|
| required, no default | false |
|
||||||
|
| optional, default true | true |
|
||||||
|
|
||||||
|
Scenario: 5 Saving
|
||||||
|
Given the PUT has not answered
|
||||||
|
Then the chip reads "Saving…" with a loader, "Save" reads "Saving…" with a loader and is disabled, "Cancel" and "Delete" are disabled
|
||||||
|
And the form is dimmed to 70 % and every control is disabled
|
||||||
|
And a second activation of "Save", or Enter in a field, sends no second request
|
||||||
|
|
||||||
|
Scenario: 6 Saved (edit)
|
||||||
|
Given /content/events/42 with Title changed to "Lime plaster workshop, two days"
|
||||||
|
When the PUT answers 200 with updated_by 5 and updated_at 2026-10-19 11:02 local
|
||||||
|
Then a success toast "Entry saved" with "\"Lime plaster workshop, two days\" is up to date." is shown
|
||||||
|
And the chip reads "Saved at 11:02", "Save" is disabled and the controls hold the answered values
|
||||||
|
And the title, the breadcrumb and the footer "Updated by" read the answered entry ("Marta Alves · 19 Oct 2026, 11:02")
|
||||||
|
And no "Leave without saving?" prompt is shown afterwards
|
||||||
|
And a later edit returns the chip to "Unsaved changes"
|
||||||
|
|
||||||
|
Scenario: Saved (create)
|
||||||
|
Given /content/events/new with the required fields filled
|
||||||
|
When the POST answers 201 with id 43
|
||||||
|
Then the router replaces the URL with /content/events/43 and no entry request is made for it, the answered entry is used
|
||||||
|
And the same toast, the chip "Saved at HH:MM" and the footer ("Entry" "events / 43", "Created by" and "Updated by" the current user) show
|
||||||
|
And "Delete" now shows and a Back from there goes to the page before the new form
|
||||||
|
And no "Leave without saving?" prompt is shown
|
||||||
|
|
||||||
|
Scenario: Where "Saved at" comes from
|
||||||
|
Given the answered entry has updated_at 2026-10-19T11:02:00 in the local time zone
|
||||||
|
Then the chip text is "Saved at 11:02" built from that timestamp, never from the clock
|
||||||
|
And a Saved chip never turns into "Saved N min ago"
|
||||||
|
And a test builds its expected text with the same local formatter from the mocked updated_at and pins the time zone; no test freezes the system date
|
||||||
|
|
||||||
|
Scenario Outline: 7 Save failed
|
||||||
|
Given the save <failure>
|
||||||
|
Then an error alert titled "Couldn't save the entry" shows "Something went wrong on our side. Your changes are still here. Try again in a moment." with a "Try again" action
|
||||||
|
And the chip reads "Save failed" in the error colour, the values stay, "Save" is enabled and the form is not dimmed
|
||||||
|
When the user activates "Try again"
|
||||||
|
Then the same body is sent again and the alert clears while it is in flight
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| failure |
|
||||||
|
| answers 500 |
|
||||||
|
| never reaches the server |
|
||||||
|
| answers 400 |
|
||||||
|
| answers 422 "invalid_entry" with no field |
|
||||||
|
|
||||||
|
Scenario: 8 Required fields empty
|
||||||
|
Given /content/events/new with Title and Starts on empty
|
||||||
|
When the user activates "Save"
|
||||||
|
Then no request is sent
|
||||||
|
And "Fill in Title." shows under Title and "Pick a date for Starts on." under Starts on, each with the error colour on the control
|
||||||
|
And the chip reads "Not saved" in the error colour with a circle-alert icon
|
||||||
|
And focus moves to the Title control, the first field in schema order with an error, and the page scrolls to it
|
||||||
|
And the controls carry aria-invalid and the message is tied to them by aria-describedby
|
||||||
|
|
||||||
|
Scenario Outline: Required messages
|
||||||
|
Given an empty required field of type <type> labelled <label>
|
||||||
|
When the user saves
|
||||||
|
Then the message under it reads <message>
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| type | label | message |
|
||||||
|
| text | Title | Fill in Title. |
|
||||||
|
| richtext | Notes | Fill in Notes. (proposed copy) |
|
||||||
|
| number | Capacity | Fill in Capacity. (proposed copy)|
|
||||||
|
| date | Starts on | Pick a date for Starts on. |
|
||||||
|
| select | Category | Choose an option for Category. |
|
||||||
|
|
||||||
|
Scenario: A required boolean refused by the server
|
||||||
|
Given /content/events/42 where Online is a required boolean the user never touched
|
||||||
|
When the server answers 422 "invalid_entry: online: required"
|
||||||
|
Then the message under Online reads "Choose yes or no for Online."
|
||||||
|
And a required boolean is never refused on the client: an untouched one is sent as false
|
||||||
|
|
||||||
|
Scenario: 9 Rule errors
|
||||||
|
Given /content/events/42 with Title of 91 characters, Ends on holding a value the server refuses as a date, Capacity 6000 and Category "Seminar" which is not a choice
|
||||||
|
When the user activates "Save"
|
||||||
|
Then only one message shows per field: "Title can be up to 80 characters." with the counter "91 / 80", "Ends on must be a date, like 2026-11-21.", "Capacity must be at most 5000.", "Choose one of: Talk, Workshop or Meetup."
|
||||||
|
And the chip reads "Not saved" and focus is on Title
|
||||||
|
|
||||||
|
Scenario Outline: Messages per rule and type
|
||||||
|
Given a field <field> and the value <value>
|
||||||
|
When the entry is saved
|
||||||
|
Then the message under it reads <message>
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| field | value | message |
|
||||||
|
| Title, text, min 3 | "ab" | Title needs at least 3 characters. |
|
||||||
|
| Title, text, max 80 | 91 characters | Title can be up to 80 characters. |
|
||||||
|
| Title, text | 5 (server type) | Title must be text. |
|
||||||
|
| Capacity, number, min 1 | 0 | Capacity must be at least 1. |
|
||||||
|
| Capacity, number, max 5000 | 6000 | Capacity must be at most 5000. |
|
||||||
|
| Capacity, number | "4" (server type) | Capacity must be a number. |
|
||||||
|
| Online, boolean | "yes" (server type) | Online must be yes or no. |
|
||||||
|
| Starts on, date, min 2026-01-01 | 2025-12-31 | Starts on can't be before 1 Jan 2026. |
|
||||||
|
| Starts on, date, max 2027-12-31 | 2028-01-01 | Starts on can't be after 31 Dec 2027. |
|
||||||
|
| Starts on, date | 2026-02-30 (server type)| Starts on must be a date, like 2026-11-21. |
|
||||||
|
| Category, select | "Seminar" | Choose one of: Talk, Workshop or Meetup. |
|
||||||
|
|
||||||
|
Scenario Outline: A server answer that gets past the client
|
||||||
|
Given the client found no error and the request is sent
|
||||||
|
When the server answers <status> "invalid_entry: <key>: <rule>" for a key of the loaded type
|
||||||
|
Then the message of the table above shows under the field of <key>, the chip reads "Not saved", focus moves to that field and the values stay
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| status | key | rule |
|
||||||
|
| 422 | title | min |
|
||||||
|
| 422 | capacity | max |
|
||||||
|
| 422 | ends_on | type |
|
||||||
|
| 422 | category | options |
|
||||||
|
| 422 | title | required|
|
||||||
|
|
||||||
|
Scenario: Errors clear field by field
|
||||||
|
Given the errors of state 8 are shown
|
||||||
|
When the user edits Title
|
||||||
|
Then the message under Title goes and the chip reads "Unsaved changes"
|
||||||
|
And the message under Starts on stays until Starts on is edited or the next save
|
||||||
|
And nothing is validated on blur
|
||||||
|
|
||||||
|
Scenario: 10 Duplicate unique value (409)
|
||||||
|
Given /content/events/new with Title "Heat pumps: what the numbers say" and another entry holds it
|
||||||
|
When the POST answers 409 "invalid_entry: title: unique"
|
||||||
|
Then an error alert titled "Not saved" shows "Another entry already uses this title. Change it and save again."
|
||||||
|
And under Title "Another entry already uses this Title. Enter a different one." shows, with the counter "n / 80", and the chip reads "Not saved"
|
||||||
|
And focus moves to Title and the values stay
|
||||||
|
And the alert goes when Title is edited
|
||||||
|
|
||||||
|
Scenario Outline: The unique message per type
|
||||||
|
Given a unique <type> field labelled <label>
|
||||||
|
When the server answers 409 "invalid_entry: <key>: unique"
|
||||||
|
Then the message under it reads <message> and the alert reads <alert>
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| type | label | key | message | alert |
|
||||||
|
| text | Title | title | Another entry already uses this Title. Enter a different one. | Another entry already uses this title. Change it and save again. |
|
||||||
|
| select | Category | category | Another entry already uses this choice for Category. | Another entry already uses this choice. Change it and save again. (proposed copy) |
|
||||||
|
| number | Capacity | capacity | Another entry already uses this Capacity. Enter a different one. (proposed copy) | Another entry already uses this capacity. Change it and save again. (proposed copy) |
|
||||||
|
|
||||||
|
Scenario Outline: 11 Entry not found
|
||||||
|
Given <where>
|
||||||
|
Then a centered state with the file-x icon reads "Entry not found" with "It may have been deleted by someone else." and a primary "Back to Events"
|
||||||
|
And the breadcrumb reads "Content" then "Events" and the mobile title is "Events"
|
||||||
|
And "Back to Events" navigates to /content/events
|
||||||
|
And the leave guard does not prompt on that navigation
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| where |
|
||||||
|
| GET .../entry/999 answers 404 entry_not_found |
|
||||||
|
| a PUT answers 404 entry_not_found (edits discarded with the page) |
|
||||||
|
| the URL is /content/events/abc or /content/events/4294967296 (no request) |
|
||||||
|
|
||||||
|
Scenario Outline: Other answers while loading or saving
|
||||||
|
Given any request of the editor
|
||||||
|
When it answers <status> <body>
|
||||||
|
Then <result>
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| status | body | result |
|
||||||
|
| 404 | content_type_not_found | the page "Content type not found" of features/content_entry_list.feature state 9 |
|
||||||
|
| 403 | any | the page "You don't have access to Events" of features/content_entry_list.feature state 8 |
|
||||||
|
| 401 | any | the existing redirect to /login with the expired reason |
|
||||||
|
|
||||||
|
Scenario Outline: Loading the entry fails (proposed, not drawn)
|
||||||
|
Given GET .../entry/42 or the type <failure>
|
||||||
|
Then an error alert reads "Couldn't load the entry" (proposed copy) with "GET /v1/content-type/events/entry/42 failed. Check your connection and try again." and a "Try again" action
|
||||||
|
And no form shows and "Try again" sends only the failed request again
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| failure |
|
||||||
|
| answers 500 |
|
||||||
|
| never reaches the server |
|
||||||
|
|
||||||
|
Scenario: Loading (proposed, not drawn)
|
||||||
|
Given the type and the entry have not resolved
|
||||||
|
Then the title row shows a skeleton, the form is skeleton rows with aria-busy="true", and "Save" and "Delete" are not shown
|
||||||
|
|
||||||
|
Scenario: 12 Schema changed since load
|
||||||
|
Given /content/events/new was opened with the 7 fields, then Room (required) was added and Description removed
|
||||||
|
When the POST answers 422 "invalid_entry: room: required"
|
||||||
|
Then a warning alert titled "The fields of Events changed" shows "A field was removed and a new required field, Room, was added after you opened this form. Reload the form to continue. What you typed here can't be saved against the old fields." with a "Reload form" action
|
||||||
|
And every control is disabled, the form is dimmed, "Save" is disabled
|
||||||
|
And the values stay visible
|
||||||
|
And the chip reads "Not saved" (the board draws "Saved" here) and "Cancel" stays enabled
|
||||||
|
|
||||||
|
Scenario Outline: What counts as a schema change
|
||||||
|
Given the editor holds the type as loaded
|
||||||
|
When the server answers 422 "invalid_entry: <key>: <rule>"
|
||||||
|
Then <result>
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| key | rule | result |
|
||||||
|
| room | required | the key is not a field of the loaded type: state 12 |
|
||||||
|
| description | unknown_field | state 12 |
|
||||||
|
| colour | unknown_field | state 12 |
|
||||||
|
| title | required | state 8 on Title (the key is known) |
|
||||||
|
| room | unique | state 12 (409) |
|
||||||
|
|
||||||
|
Scenario: The alert names what changed only when the SPA can tell
|
||||||
|
Given the type is fetched again by "Reload form"
|
||||||
|
Then the alert copy of the design is used as is; the SPA never builds a diff of fields, since the design text names Room and the removed field only as a sample
|
||||||
|
|
||||||
|
Scenario: Reload form
|
||||||
|
Given state 12
|
||||||
|
When the user activates "Reload form"
|
||||||
|
Then GET /v1/content-type/events is sent again and, on /content/:key/:id, GET .../entry/42 too
|
||||||
|
And the form is rebuilt from the new type with defaults on a new entry, or the stored values on an edit; what was typed is dropped
|
||||||
|
And the alert goes, the chip reads "New entry" or "Saved", and the URL is unchanged
|
||||||
|
And a failure of the reload shows the load error of this slice
|
||||||
|
|
||||||
|
Scenario: 13 Delete entry: confirm
|
||||||
|
Given /content/events/42 with no unsaved changes
|
||||||
|
When the user activates "Delete" (the trash-2 action on mobile)
|
||||||
|
Then no request is sent
|
||||||
|
And the dialog "Delete this entry?" opens with "\"Lime plaster workshop\" will be deleted from Events. This can't be undone." (a bottom sheet on mobile)
|
||||||
|
And the actions are "Cancel" and "Delete entry" (error colour, never the initial focus)
|
||||||
|
And Cancel, the close icon and Esc close it with nothing sent and focus back on "Delete"
|
||||||
|
|
||||||
|
Scenario: Deleting
|
||||||
|
Given the dialog is open
|
||||||
|
When the user activates "Delete entry"
|
||||||
|
Then DELETE /v1/content-type/events/entry/42 is sent once
|
||||||
|
And the button reads "Deleting…" with a loader, Cancel is disabled, Esc, the close icon and the overlay do not dismiss, and a second activation sends nothing
|
||||||
|
|
||||||
|
Scenario: Deleted
|
||||||
|
Given DELETE answers 204
|
||||||
|
Then the dialog closes and the router replaces the URL with /content/events with no "Leave without saving?" prompt
|
||||||
|
And a success toast "Entry deleted" with "\"Lime plaster workshop\" was deleted from Events." (proposed copy) is shown
|
||||||
|
And the list loads its own data, so the entry is gone from it
|
||||||
|
|
||||||
|
Scenario Outline: Other answers of DELETE
|
||||||
|
Given the dialog is open and DELETE <outcome>
|
||||||
|
Then <result>
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| outcome | result |
|
||||||
|
| answers 404 entry_not_found | the dialog closes and the page "Entry not found" shows |
|
||||||
|
| answers 404 content_type_not_found| the dialog closes and the page "Content type not found" shows |
|
||||||
|
| answers 403 | the dialog closes and the page "You don't have access to Events" shows |
|
||||||
|
| answers 401 | the existing redirect to /login with the expired reason |
|
||||||
|
| answers 500 or fails (network) | the dialog stays with an error alert "Couldn't delete the entry" (proposed copy) and "Something went wrong on our side. Nothing was deleted. Try again in a moment."; the buttons are enabled again |
|
||||||
|
|
||||||
|
Scenario: Delete with unsaved edits
|
||||||
|
Given /content/events/42 with unsaved edits
|
||||||
|
When the user opens the delete dialog
|
||||||
|
Then its copy uses the saved title, it does not save or discard the edits, and Cancel leaves them exactly as they were
|
||||||
|
And on 204 the router leaves with no leave prompt
|
||||||
|
|
||||||
|
Scenario Outline: Leaving with unsaved edits
|
||||||
|
Given <state>
|
||||||
|
When the user leaves through the breadcrumb, the mobile arrow, "Cancel", the sidebar or the browser back
|
||||||
|
Then <result>
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| state | result |
|
||||||
|
| no edit | the router navigates with no prompt |
|
||||||
|
| an edit on /content/events/42 | the dialog "Leave without saving?" with "Keep editing" and "Discard changes" |
|
||||||
|
| any typed value on /content/events/new | the same dialog |
|
||||||
|
| /content/events/new untouched, defaults only | no prompt |
|
||||||
|
| after Save answered 200 or 201 | no prompt |
|
||||||
|
| after Delete answered 204 | no prompt |
|
||||||
|
| state 12 with typed values | the same dialog |
|
||||||
|
|
||||||
|
Scenario: Switching to another entry or type reuses nothing
|
||||||
|
Given the user edited /content/events/42 and discarded the edits to leave
|
||||||
|
When the user opens /content/events/43 or /content/recipes/new
|
||||||
|
Then the form is built from that route alone, with no value, error or chip carried over
|
||||||
|
|
||||||
|
Scenario: Stale answers are ignored
|
||||||
|
Given a GET for /content/events/42 is in flight
|
||||||
|
When the user navigates to /content/events/43 and the first answer arrives later
|
||||||
|
Then it is dropped
|
||||||
|
|
||||||
|
Scenario: Reaching the editor from the list
|
||||||
|
Given the list of features/content_entry_list.feature
|
||||||
|
When the user activates "New entry" or a row
|
||||||
|
Then the editor opens at /content/events/new or /content/events/42, no longer the catch-all 404
|
||||||
|
|
||||||
|
Scenario: Accessibility
|
||||||
|
Then every control has a visible label tied to it, the required mark " *" is hidden from assistive technology and the control carries aria-required
|
||||||
|
And the chip is a polite live region
|
||||||
|
And the Preview tabs are a tablist with arrow-key movement, and the toolbar buttons have accessible names (Bold, Italic, Heading, Link, List)
|
||||||
|
And dialogs trap focus, open with focus on the title and return it to the opener on close; the destructive button is never the initial focus
|
||||||
|
And controls are 44 px high on mobile and focus is a 2 px --ui-primary outline with a 2 px offset
|
||||||
@@ -0,0 +1,69 @@
|
|||||||
|
# QA: Entry editor of a custom content type (SPA slice 7)
|
||||||
|
|
||||||
|
Runner: Vitest + Vue Test Utils (`task test:web`). No Go test: the five entry endpoints and /v1/user/lookup already exist and the backend does not change. Kit: reuse `views/__tests__/schemaTestKit.ts` and add GET/POST/PUT/DELETE handlers for `/v1/content-type/{key}/entry[/{id}]` with the plain-text bodies `entry_not_found`, `content_type_not_found`, `invalid_entry: <key>: <rule>`, and the Events type with its 7 fields and entry 42 of SchemaFrame.dc.html. Pin the time zone. Never freeze the system date: "Saved at" is derived from the mocked `updated_at`, so the expected text is built with the same local formatter from that value.
|
||||||
|
|
||||||
|
## Automated
|
||||||
|
|
||||||
|
1. Registry (lib/fieldTypes spec, it.each over the six types): empty value, default pre-fill, control component, help line, counter rule, validate (required, type, min, max, options), message text, payload value (null for empty, false for a required boolean). The builder and the list cells still pass on the same registry.
|
||||||
|
2. Entry API (composable spec): getEntry, createEntry, saveEntry, deleteEntry; the body is {data}; error parsing of "invalid_entry: key: rule" with status 422 and 409 into {key, rule, status}; 404 bodies; 400, 401, 403 and NetworkError pass through; lookupUsers is sent once with distinct ids.
|
||||||
|
3. Route resolution (it.each): "new", "42", "abc", "0" (resolves to id 0, sent as is: the API answers 404 entry_not_found), "4294967296", "-1".
|
||||||
|
4. State 1 New entry: title, subtitle, chip "New entry", asterisks, Default tag on Online, helps, placeholders, footer "Not saved yet" and "–", Save enabled, Delete absent; mobile layout.
|
||||||
|
5. Defaults (it.each from the feature table): value shown, tag shown, tag leaves on change and returns on restore; no tag in edit.
|
||||||
|
6. State 2 Editing: breadcrumb, title, "Entry 42", chip "Saved", Save disabled, footer names and dates after the lookup; "–" with the date kept when the lookup fails or lacks an id; mobile trash-2 action.
|
||||||
|
7. Page title (it.each): text, null → "Entry 42", richtext first line, number; unchanged while typing.
|
||||||
|
8. Controls and help lines (it.each): one control per type, placeholders, Off/On text, empty select "None" item on optional select only.
|
||||||
|
9. Layout rule (pairing of date, number, boolean; full width for text, richtext, select; single column below md).
|
||||||
|
10. State 3 Unsaved: counter "32 / 80", "91 / 80" in the error colour without blocking, no counter without max, chip, Save enabled, revert returns to clean.
|
||||||
|
11. State 4 Preview: rendering of bold and list, raw HTML shown as text, unsafe links inert, empty preview, tab switch keeps value and caret, toolbar inserts (it.each).
|
||||||
|
12. Payloads: create and edit bodies exactly as in the feature, explicit nulls, no unknown key, boolean table.
|
||||||
|
13. State 5 Saving: chip, button, dimming, disabled controls, no second request on click or Enter.
|
||||||
|
14. State 6 Saved: edit and create; toast; chip "Saved at HH:MM" from the answer; footer update; create replaces the URL to /content/events/43 with no extra GET; no leave prompt; edit after save is dirty again.
|
||||||
|
15. State 7 Save failed (500, network, 400, 422 with no field): alert copy, chip, values kept, Try again resends the same body.
|
||||||
|
16. State 8 Required: no request, all messages, chip "Not saved", `document.activeElement` is the first erroring control in schema order for each type (input, textarea, select trigger, date segment), aria-invalid and aria-describedby, per-type required messages (it.each).
|
||||||
|
17. State 9 Rules: one message per field, message table (it.each), server answers that pass the client map to their field and take focus.
|
||||||
|
18. Errors clear per field; chip returns to "Unsaved changes"; no blur validation.
|
||||||
|
19. State 10 Unique (409): alert and field message, per-type messages, alert clears when the field is edited.
|
||||||
|
20. State 11 Not found: GET 404, PUT 404, DELETE 404 and bad ids with no request; "Back to Events" goes to /content/events with no prompt.
|
||||||
|
21. Content type 404, 403 and 401; load failure variants with "Try again" resending only the failed request; loading skeleton with aria-busy.
|
||||||
|
22. State 12 Schema changed: unknown key, unknown_field, required on an unknown key, 409 on an unknown key; read-only form; Save disabled; Cancel enabled; chip "Not saved"; "Reload form" refetches the type (and the entry) and rebuilds the form; reload failure.
|
||||||
|
23. State 13 Delete: dialog copy, focus on Cancel, Cancel/Esc/close, no request; Deleting lock; 204 replaces the URL and shows the toast; 404, 403, 401, 500 and network outcomes; delete with unsaved edits.
|
||||||
|
24. Leave guard (it.each from the feature table), including defaults-only new form untouched, and Cancel history rule (previous entry is the list vs not).
|
||||||
|
25. Stale answers dropped; navigating between routes carries nothing.
|
||||||
|
26. Reaching the editor from the list: "New entry" and row links resolve to the editor (update the slice-6 specs that expected the catch-all 404). The slice-6 Background wording about `content_type_id` and `sort` is checked against the Go handler and corrected with the list code and tests if it differs.
|
||||||
|
27. Accessibility: labels, aria-required, live-region chip, tablist keyboard, toolbar names, dialog focus.
|
||||||
|
28. French: every new string has an entry (i18n completeness spec passes).
|
||||||
|
|
||||||
|
## Visual (task visual:check -- entry)
|
||||||
|
|
||||||
|
Register the group "6 Entry editor" in `extraSources` if needed. Every capture within 10 %, desktop and mobile, light and dark. Mock the sidebar's GET /v1/content-type and /v1/user/lookup. No state is clock-sensitive: "Saved at" comes from the response timestamp. If the runner cannot pin the zone, build `updated_at` as the builder's Saved setup does.
|
||||||
|
|
||||||
|
| Board state | Setup in web/visual/states.ts | Board sample data |
|
||||||
|
|---|---|---|
|
||||||
|
| 1 New entry | /content/events/new, Events type | "New entry", "Not saved yet", Online Off + "Default" |
|
||||||
|
| 2 Editing | /content/events/42, lookup 3 and 5 | "Lime plaster workshop", "Entry 42", "Inès Duarte · 12 Oct 2026, 09:14", "Marta Alves · 15 Oct 2026, 11:02" |
|
||||||
|
| 3 Unsaved changes | step: type ", two days" in Title | "Lime plaster workshop, two days", "32 / 80", focus ring on Title |
|
||||||
|
| 4 Markdown preview | step: click "Preview" on Description | "Two days of hands-on work with lime putty and old stone." and the two bullets |
|
||||||
|
| 5 Saving | PUT `hang: true` after an edit | "Saving…" |
|
||||||
|
| 6 Saved | PUT 200 with updated_at 2026-10-19 11:02 local, updated_by 5 | "Saved at 11:02", "Entry saved", "Marta Alves · 19 Oct 2026, 11:02" |
|
||||||
|
| 7 Save failed | PUT 500 after an edit | "Couldn't save the entry" |
|
||||||
|
| 8 Required fields empty | /content/events/new, click Save | "Fill in Title.", "Pick a date for Starts on." |
|
||||||
|
| 9 Rule errors | /content/events/42 with the board's values typed, PUT 422 for any server-side one | "91 / 80", "Capacity must be at most 5000.", "Choose one of: Talk, Workshop or Meetup." |
|
||||||
|
| 10 Duplicate (409) | /content/events/new, title "Heat pumps: what the numbers say", POST 409 | "Another entry already uses this Title. Enter a different one." |
|
||||||
|
| 11 Entry not found | /content/events/999, entry 404 entry_not_found | "Entry not found" |
|
||||||
|
| 12 Schema changed | /content/events/new, POST 422 invalid_entry: room: required | "The fields of Events changed" |
|
||||||
|
| 13 Delete entry: confirm | /content/events/42, step: click "Delete" | "Delete this entry?" |
|
||||||
|
|
||||||
|
Board caveats to report, never hide:
|
||||||
|
- State 9 draws `31/11/2026` as text in Ends on; a segmented date control cannot hold it, so that field will differ.
|
||||||
|
- State 11's breadcrumb shows the entry title, unknown on a 404.
|
||||||
|
- State 12's chip is drawn "Saved" and its Cancel is drawn disabled; the spec uses "Not saved" and an enabled Cancel (user decision).
|
||||||
|
- Mobile in state 9 depends on the chosen layout rule.
|
||||||
|
|
||||||
|
## Manual
|
||||||
|
|
||||||
|
- Real backend with two users: create an entry; Back from it returns to the list, not the empty form; edit; delete; the list shows the change.
|
||||||
|
- Two tabs: change the type's fields in one (add a required field), save the entry in the other: state 12, "Reload form". Delete the entry in one tab and save in the other: state 11.
|
||||||
|
- Duplicate a unique title for a real 409.
|
||||||
|
- Keyboard: tab order across fields, toolbar, tabs, footer buttons; Enter in a single-line field saves; focus lands on the first error; dialogs trap focus.
|
||||||
|
- Markdown with raw HTML and `javascript:` links stays inert in Preview.
|
||||||
|
- Reload on /content/events/42 keeps the page; the browser back from a saved new entry goes to the page before the new form.
|
||||||
@@ -0,0 +1,224 @@
|
|||||||
|
Feature: Entry list of a custom content type
|
||||||
|
As a verified user
|
||||||
|
I want to browse the entries of a custom content type
|
||||||
|
So that I can find an entry before editing it
|
||||||
|
|
||||||
|
Background:
|
||||||
|
Given the SPA calls the API with relative URLs under /v1 and the "jwt" HttpOnly cookie
|
||||||
|
And API errors are plain text
|
||||||
|
And the route is /content/:key with meta auth "verified" and title "Content", per docs/design/screens/content.md group "5 Content and entry list", states 1 to 9
|
||||||
|
And the page requests GET /v1/content-type/{key} (the type) and GET /v1/content-type/{key}/entry?page=P&size=S&sort=O (the entries) at the same time; the entries answer {items, total, page, size} (no sort) and each item is {id, content_type (the type key), data, created_by, updated_by, created_at, updated_at}
|
||||||
|
And the sidebar Content group of features/schema_list_and_content_nav.feature is reused unchanged; this slice only checks it in the "Many types" state
|
||||||
|
And page, size and sort live in the URL (/content/events?page=2&size=50&sort=created_at:desc), the defaults (page 1, size 25, sort updated_at:desc) are omitted from the URL, and the request always carries explicit page and size
|
||||||
|
And size is one of 5, 25, 50, 100; sort is <id|created_at|updated_at>:<asc|desc>; an invalid value is replaced silently by the default in the URL and in the request, so the API never answers 400 here
|
||||||
|
And a size or sort change resets page to 1; the URL changes when a response succeeds, not when the request is sent
|
||||||
|
And the pager, the page-size select, the summary, the loading page, the page error notice and the out-of-range redirect behave as in features/articles_pagination_screen.feature scenarios 1 to 7, 10, 10b and 11, with the content URL and request
|
||||||
|
And the page size is not remembered
|
||||||
|
And the columns are ID, up to 6 chosen field columns (default: the first 4 fields of the type, fewer if the type has fewer), Created, Updated and Updated by; ID, Created, Updated and Updated by are always shown
|
||||||
|
And a field cell shows: Text truncated on one line with the full text as tooltip; Rich text as its first line in plain text, truncated; Number right-aligned with tabular figures; Yes or no as an icon plus "Yes" or "No"; Date as day, month and year ("21 Nov 2026") with no time-zone shift; Choice as a small outline tag; an empty value as "–"
|
||||||
|
And Created reads "12 Oct 2026" and Updated reads "15 Oct 2026" (date only, local time zone), ID is mono and muted
|
||||||
|
And "Updated by" is the display_name from one GET /v1/user/lookup?ids=<distinct updated_by of the page> sent after the entries answer; until it resolves, and if it fails or does not know the id, the cell shows a muted "–"
|
||||||
|
And the desktop list is a table with a 36 px header and 48 px rows; below md it is a card list with 68 px cards, each card a link with a chevron-right, showing the first field, the second field, the first Choice field as a tag if the type has one, and "· {Updated by}"; cards ignore the column picker
|
||||||
|
And every row is a link to /content/:key/:id (a link on the first field cell on desktop, the whole card on mobile); the click uses the router
|
||||||
|
And "New entry" (primary, plus icon, in the title row on desktop; a floating button on mobile) navigates to /content/:key/new
|
||||||
|
And /content/:key/new and /content/:key/:id are not routed in this slice and land on the catch-all 404 until the entry editor slice
|
||||||
|
And "Edit content type" (ghost, settings-2 icon, right of the toolbar) navigates to /schema/:key; it is shown to owner and admin only and not on mobile
|
||||||
|
And no filter or search exists
|
||||||
|
And every string goes through t() and has a French entry in i18n/messages.ts
|
||||||
|
And a copy tagged "(proposed copy)" is not in the design and is the coder's single point of change
|
||||||
|
|
||||||
|
Scenario: 1 Populated, one page
|
||||||
|
Given GET /v1/content-type/events resolves 200 with 7 fields and GET .../entry?page=1&size=25&sort=updated_at:desc resolves 200 with 7 items and total 7
|
||||||
|
When the user navigates to /content/events
|
||||||
|
Then the breadcrumb reads "Content" then "Events", the title "Events" with the subtitle "events · 7 fields"
|
||||||
|
And "New entry" is in the title row and the toolbar reads "Sort by" "Last updated", a direction button, "Columns", then "Edit content type" at the right
|
||||||
|
And the table headers read "ID" "Title" "Starts on" "Ends on" "Online" "Created" "Updated" "Updated by" and the Updated header shows an arrow-down icon
|
||||||
|
And 7 rows show, the first row ID 42 "Lime plaster workshop" "21 Nov 2026" "22 Nov 2026" "No" "12 Oct 2026" "15 Oct 2026" "Marta Alves"
|
||||||
|
And no pager, no page-size select, only the text "7 entries" ("1 entry" for one, proposed copy)
|
||||||
|
And the sidebar row Events is the current page and the URL has no query
|
||||||
|
|
||||||
|
Scenario: 2 Paginated, 5 per page
|
||||||
|
Given GET .../entry?page=1&size=5&sort=updated_at:desc resolves 200 with 5 items and total 37
|
||||||
|
When the user navigates to /content/events?size=5
|
||||||
|
Then the summary reads "Showing 1–5 of 37", the page-size select reads "5 per page" and the paginator shows First, Previous (both disabled), 1 (current), 2, an ellipsis, 8, Next, Last
|
||||||
|
And on mobile the paginator reads Previous (disabled), "Page 1 of 8", Next
|
||||||
|
And activating Next sends page=2 and, on success, the URL is /content/events?size=5&page=2
|
||||||
|
|
||||||
|
Scenario: 3 Columns menu
|
||||||
|
Given the populated state of the 7-field type Events
|
||||||
|
When the user activates "Columns"
|
||||||
|
Then a popover opens on desktop and a bottom sheet on mobile, titled "Columns" with "4 of 6"
|
||||||
|
And the sheet adds the text "Choose up to 6 fields to show. 4 selected." and the actions "Reset" and "Done"; the popover has "Reset" only
|
||||||
|
And each of the 7 fields is a checkbox row with its type icon, its label and its key in mono, in schema order; Title, Starts on, Ends on and Online are checked
|
||||||
|
And a last row with a clock icon reads "Created and updated dates always show" with a disabled, unchecked checkbox
|
||||||
|
When the user checks "Capacity"
|
||||||
|
Then the table gets a Capacity column (right-aligned) at once, with no request, and the count reads "5 of 6"
|
||||||
|
And Esc, a click outside or "Done" closes it and returns focus to "Columns"
|
||||||
|
|
||||||
|
Scenario Outline: The column cap and the stored choice
|
||||||
|
Given the 7-field type Events and <before>
|
||||||
|
When <action>
|
||||||
|
Then <after>
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| before | action | after |
|
||||||
|
| 6 fields checked | the user opens the menu | the unchecked fields are disabled and the text "You can show up to 6 fields." (proposed copy) shows |
|
||||||
|
| 5 fields checked | the user checks a 6th | it is checked and the others become disabled |
|
||||||
|
| 6 fields checked | the user unchecks one | the others are enabled again |
|
||||||
|
| the default 4 and nothing stored | the user checks "Capacity" | localStorage renewcms-content-columns-events is ["title","starts_on","ends_on","online","capacity"] |
|
||||||
|
| a stored selection | the user activates "Reset" | the default 4 apply and the stored key is removed |
|
||||||
|
| stored ["title","gone","capacity"] | the page loads | the columns are Title and Capacity, and nothing is written |
|
||||||
|
| stored with 8 valid keys | the page loads | the first 6 in schema order show |
|
||||||
|
| stored "not json" or [] | the page loads | the default 4 show |
|
||||||
|
| localStorage throws or is undefined | the user changes the selection | the columns change for this visit and no error shows |
|
||||||
|
| stored for events | the user opens /content/recipes | Recipes uses its own key and its default |
|
||||||
|
|
||||||
|
Scenario: The last field column cannot be unchecked
|
||||||
|
Given the 7-field type Events with exactly one field checked
|
||||||
|
When the user opens the Columns menu
|
||||||
|
Then that field's checkbox is disabled, so at least one field column always shows and every row has its link
|
||||||
|
And a stored empty selection loads as the default 4
|
||||||
|
|
||||||
|
Scenario: A type with fewer than 4 fields
|
||||||
|
Given a type with 2 fields
|
||||||
|
When the user opens its list
|
||||||
|
Then both field columns show and "of 6" in the menu still reads the cap
|
||||||
|
|
||||||
|
Scenario Outline: Sort control
|
||||||
|
Given GET .../entry resolves 200 and the user is on /content/events?page=3
|
||||||
|
When the user chooses "<option>" in the "Sort by" select
|
||||||
|
Then GET ...&sort=<sort>&page=1 is sent and, on success, the URL is <url>
|
||||||
|
And the sorted column header shows the arrow icon of its direction
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| option | sort | url |
|
||||||
|
| ID | id:desc | /content/events?sort=id:desc |
|
||||||
|
| Created | created_at:desc | /content/events?sort=created_at:desc |
|
||||||
|
| Last updated | updated_at:desc | /content/events |
|
||||||
|
|
||||||
|
Scenario Outline: Direction button
|
||||||
|
Given the user is on <from>
|
||||||
|
When the user activates the direction button
|
||||||
|
Then GET ...&sort=<sort>&page=1 is sent and, on success, the URL is <url>
|
||||||
|
And the button shows arrow-up-narrow-wide when ascending and arrow-down-wide-narrow when descending, with the accessible name "Sort ascending" or "Sort descending" for the next action (proposed copy)
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| from | sort | url |
|
||||||
|
| /content/events | updated_at:asc | /content/events?sort=updated_at:asc |
|
||||||
|
| /content/events?sort=updated_at:asc | updated_at:desc | /content/events |
|
||||||
|
| /content/events?sort=id:desc | id:asc | /content/events?sort=id:asc |
|
||||||
|
|
||||||
|
Scenario Outline: Sort values in the URL
|
||||||
|
When the user navigates to /content/events?sort=<value>
|
||||||
|
Then <result>
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| value | result |
|
||||||
|
| created_at:asc | GET carries sort=created_at:asc and the select reads "Created" with the ascending direction icon |
|
||||||
|
| title:asc | GET carries sort=updated_at:desc and the URL is replaced by /content/events |
|
||||||
|
| data:asc | GET carries sort=updated_at:desc and the URL is replaced by /content/events |
|
||||||
|
| id | GET carries sort=updated_at:desc and the URL is replaced by /content/events |
|
||||||
|
|
||||||
|
Scenario: Sort is kept across paging and size changes
|
||||||
|
Given the URL is /content/events?sort=id:asc
|
||||||
|
When the user activates Next, or changes the size
|
||||||
|
Then every request carries sort=id:asc and the URL keeps it (a size change also resets the page)
|
||||||
|
|
||||||
|
Scenario: Switching to another type resets the page
|
||||||
|
Given the user is on /content/events?page=3&size=50&sort=id:asc
|
||||||
|
When the user opens /content/recipes from the sidebar
|
||||||
|
Then the requests are for recipes with page=1, size=25 and sort=updated_at:desc, its own columns apply and no Events row shows meanwhile
|
||||||
|
|
||||||
|
Scenario: 4 Many types in the sidebar
|
||||||
|
Given GET /v1/content-type returns 14 custom types, the 4th named "Frequently asked questions and answers"
|
||||||
|
When the user opens /content/events
|
||||||
|
Then on desktop the Content group shows "Content", the first 5 types and the selected one, the long name truncated, and "Show all 14"
|
||||||
|
And on mobile the drawer shows the group expanded with "All content types 14" collapsed row
|
||||||
|
And behaviour is as in features/schema_list_and_content_nav.feature
|
||||||
|
|
||||||
|
Scenario: 5 Loading
|
||||||
|
Given the type and the entries have not resolved
|
||||||
|
When the user navigates to /content/events
|
||||||
|
Then the title row shows "Events" once the type has resolved and a skeleton until then, "New entry" is disabled and the toolbar is shown
|
||||||
|
And the list is 8 skeleton rows on desktop (6 on mobile) with a 48 px row (68 px on mobile) and aria-busy="true"
|
||||||
|
And when both resolve the rows replace the skeleton
|
||||||
|
|
||||||
|
Scenario: 6 Empty for this type
|
||||||
|
Given GET .../entry resolves 200 with items [] and total 0
|
||||||
|
When the user navigates to /content/events
|
||||||
|
Then the empty state reads "No entries yet" with "Use New entry to add the first entry. Each entry follows the fields of this content type." and a "New entry" action
|
||||||
|
And the toolbar stays, the pager, the summary and the count text do not show
|
||||||
|
And "New entry" navigates to /content/events/new
|
||||||
|
And an out-of-range page with total 0 shows this state and the URL becomes /content/events
|
||||||
|
|
||||||
|
Scenario Outline: 7 Error loading entries
|
||||||
|
Given the type resolves 200 and GET .../entry <failure>
|
||||||
|
When the user navigates to /content/events
|
||||||
|
Then an error alert reads "Couldn't load entries" with "GET /v1/content-type/events/entry failed. Check your connection and try again." and a "Try again" action
|
||||||
|
And no toolbar, no list and no pager show; the title row stays
|
||||||
|
When the user activates "Try again"
|
||||||
|
Then the skeleton (state 5) shows and the failed request is sent again
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| failure |
|
||||||
|
| resolves with a 500 response |
|
||||||
|
| never reaches the server |
|
||||||
|
|
||||||
|
Scenario: Error loading the type
|
||||||
|
Given GET /v1/content-type/events answers 500
|
||||||
|
Then the same alert shows with "GET /v1/content-type/events failed. Check your connection and try again." (proposed copy)
|
||||||
|
And "Try again" sends only the failed request again
|
||||||
|
|
||||||
|
Scenario Outline: 8 Forbidden (403)
|
||||||
|
Given <which> answers 403
|
||||||
|
When the user navigates to /content/events
|
||||||
|
Then a centered state with the lock icon reads "You don't have access to Events" with "Your account can't open this content right now. If you think this is a mistake, ask an owner or an admin." and "Go to Home"
|
||||||
|
And no toolbar or list shows and "Go to Home" navigates to /home
|
||||||
|
And the title uses the type name when the type loaded, else the key
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| which |
|
||||||
|
| the entries request |
|
||||||
|
| the type request |
|
||||||
|
|
||||||
|
Scenario Outline: 9 Type not found
|
||||||
|
Given <which> answers 404 content_type_not_found
|
||||||
|
When the user navigates to /content/unknown
|
||||||
|
Then a centered state with the file-x icon reads "Content type not found" with "It may have been deleted, or the address may be mistyped." and "Go to Home"
|
||||||
|
And the breadcrumb reads "Content" only, the mobile title is "Content" and no sidebar row is current
|
||||||
|
And "Go to Home" navigates to /home
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| which |
|
||||||
|
| the type request |
|
||||||
|
| the entries request |
|
||||||
|
|
||||||
|
Scenario: A deleted type behind the sidebar
|
||||||
|
Given Recipes was deleted in features/schema_builder_delete.feature
|
||||||
|
When the user opens /content/recipes
|
||||||
|
Then the "Content type not found" state shows with no further request than the type's
|
||||||
|
|
||||||
|
Scenario: Session expired
|
||||||
|
Given any of the requests answers 401
|
||||||
|
Then the existing redirect to /login with the expired reason happens
|
||||||
|
|
||||||
|
Scenario: Stale answers are ignored
|
||||||
|
Given a request for page 2 is in flight
|
||||||
|
When the user changes the sort and that request resolves later
|
||||||
|
Then its answer is dropped and only the latest request updates the list and the URL
|
||||||
|
|
||||||
|
Scenario: Updated by lookup
|
||||||
|
Given the page has entries by users 3, 3 and 5
|
||||||
|
Then GET /v1/user/lookup?ids=3,5 is sent once after the entries answer and the cells read the display names
|
||||||
|
And when it answers 500 or lacks id 5 the cells read "–" and no error shows
|
||||||
|
|
||||||
|
Scenario: Navigation actions
|
||||||
|
Given the populated state and an owner
|
||||||
|
Then "New entry" and the first-cell links go to /content/events/new and /content/events/42, "Edit content type" goes to /schema/events
|
||||||
|
And with a role other than owner or admin "Edit content type" is not rendered
|
||||||
|
And below md "Edit content type" is not rendered and the New entry button is a floating button (hidden while loading and in the error state)
|
||||||
|
|
||||||
|
Scenario: Accessibility
|
||||||
|
Then the table has a visually hidden caption "Events, sorted by last updated, newest first" ("sorted by {id|created|updated}, {ascending|descending}" otherwise; proposed copy, French entry)
|
||||||
|
And "Columns", the direction button and the select have accessible names; the picker traps focus on mobile and is operable with Space and Esc
|
||||||
|
And controls are 44 px on mobile and focus is a 2 px --ui-primary outline with a 2 px offset
|
||||||
@@ -0,0 +1,52 @@
|
|||||||
|
# QA: Entry list of a custom content type (SPA slice 6)
|
||||||
|
|
||||||
|
Runner: Vitest + Vue Test Utils (`task test:web`). No Go test: both endpoints and /v1/user/lookup already exist and the backend does not change. Kit: reuse `views/__tests__/schemaTestKit.ts` (add GET /v1/content-type/{key}, GET .../entry with page/size/sort, and /v1/user/lookup handlers; Events with the 7 fields and 7/37 entries of SchemaFrame.dc.html). Pin the time zone; never freeze the system date.
|
||||||
|
|
||||||
|
## Automated
|
||||||
|
|
||||||
|
1. Composable (useContentTypes.spec): `getContentType(key)`; `listEntries(key, {page,size,sort})` builds the query, returns {items,total,page,size,sort}, passes status and plain text through (403, 404, 500), NetworkError passes through. `lookupUsers(ids)` sends the distinct ids once and returns display names.
|
||||||
|
2. URL parsing (it.each): invalid/missing page, size, sort fall back to 1, 25, updated_at:desc and are replaced in the URL; defaults omitted; size and sort change reset page; the URL changes on success only.
|
||||||
|
3. State 1 Populated: title, subtitle "events · 7 fields", toolbar, headers, first row values, "7 entries", no pager; singular "1 entry".
|
||||||
|
4. State 2 Paginated (size=5, total 37): "Showing 1–5 of 37", "5 per page", pager; mobile "Page 1 of 8"; Next sends page=2 and updates the URL on success.
|
||||||
|
5. Reuse of Articles pager behaviours (it.each): last page, loading page (aria-busy, disabled controls, "Loading page 2…"), error keeps rows with Retry, out-of-range redirect with notice, total 0 on out-of-range shows empty.
|
||||||
|
6. Cells (it.each per field type): truncation, rich text first line, number alignment, Yes/No icon, date without shift, Choice tag, empty "–"; Created and Updated formats.
|
||||||
|
7. Updated by: one lookup with distinct ids after the entries; "–" before it resolves, on failure and for an unknown id.
|
||||||
|
8. State 3 Columns: popover on desktop (Reset only), sheet on mobile (Reset and Done); "4 of 6", sentence, rows with icon, label and key; the Created/updated row disabled; live column change with no request; cap at 6 with message and disabled rows; Esc/outside/Done close and return focus.
|
||||||
|
9. Column persistence (it.each from the feature table): writes, Reset removes, unknown keys dropped, more than 6 truncated, invalid JSON, per-type keys, throwing/undefined localStorage, load never writes.
|
||||||
|
10. Sort: the three options and the direction button (it.each), accessible names, URL and request, header arrow, sort kept across paging, invalid URL values replaced.
|
||||||
|
11. State 4: with 14 types the sidebar shows 5 + selected + "Show all 14"; mobile drawer collapsed row "All content types 14" (sidebar logic itself stays in ContentNav.spec).
|
||||||
|
12. State 5 Loading: skeleton rows (8 / 6), aria-busy, "New entry" disabled.
|
||||||
|
13. State 6 Empty: copy, "New entry" navigates to /content/events/new, no pager.
|
||||||
|
14. State 7 Error (500 and network): copy, "Try again" sends the failed request again; type-load failure variant.
|
||||||
|
15. State 8 Forbidden (entries 403, type 403): copy, name fallback to the key, "Go to Home" goes to /home.
|
||||||
|
16. State 9 Not found (type 404, entries 404): copy, breadcrumb "Content", no current sidebar row; deleted-type scenario.
|
||||||
|
17. Navigation: New entry, first-cell links, mobile card link, "Edit content type" to /schema/events; hidden for a non-owner/admin and on mobile; mobile floating button hidden in loading and error.
|
||||||
|
18. 401 redirect; stale answer dropped after a sort change; switching type resets page/size/sort and columns.
|
||||||
|
19. Accessibility: caption text per sort, accessible names, keyboard on the picker and the select.
|
||||||
|
20. French: every new string has an entry (i18n completeness spec passes).
|
||||||
|
|
||||||
|
## Visual (task visual:check -- content)
|
||||||
|
|
||||||
|
Register the group "5 Content and entry list" in `extraSources` if not registered. Every capture within 10 %, desktop and mobile, light and dark. Nothing is clock-sensitive. Mock every /v1 call including the sidebar's GET /v1/content-type and /v1/user/lookup.
|
||||||
|
|
||||||
|
| Board state | Setup in web/visual/states.ts | Board sample data |
|
||||||
|
|---|---|---|
|
||||||
|
| 1 Populated | /content/events, 7 entries (ROWS of SchemaFrame.dc.html), owner session | "Lime plaster workshop", "Marta Alves", "events · 7 fields", "7 entries" |
|
||||||
|
| 2 Paginated, 5 per page | /content/events?size=5, total 37, 5 items | "Showing 1–5 of 37", "Page 1 of 8" (mobile) |
|
||||||
|
| 3 Columns menu | /content/events, step: click "Columns" | "4 of 6", Title, Starts on, Ends on, Online checked |
|
||||||
|
| 4 Many types | /content/events with 14 types (CT list of the board); mobile: open the drawer and expand the group | "Frequently asked questions and answers", "Show all 14" |
|
||||||
|
| 5 Loading | entries `hang: true` | skeleton rows |
|
||||||
|
| 6 Empty | entries total 0 | "No entries yet" |
|
||||||
|
| 7 Error | entries 500 | "Couldn't load entries" |
|
||||||
|
| 8 Forbidden | entries 403 | "You don't have access to Events" |
|
||||||
|
| 9 Type not found | /content/unknown, type 404 content_type_not_found | "Content type not found" |
|
||||||
|
|
||||||
|
Board caveats to report, never hide: the mobile card shows a Category tag that the default 4 columns do not include; the desktop picker is drawn without Done; the mobile frames hide "Edit content type", so mobile has no path to the builder (design follow-up).
|
||||||
|
|
||||||
|
## Manual
|
||||||
|
|
||||||
|
- Real backend, owner and a non-owner/admin if one exists: list a type with 37 entries; sort, page, change size; reload keeps the URL state.
|
||||||
|
- Columns: choose 6, reload, switch type and back; clear localStorage and see the default.
|
||||||
|
- Click "New entry" and a row: the 404 page is expected until the editor slice; Back returns to the list with its URL.
|
||||||
|
- Keyboard: tab order toolbar (select, direction, Columns, Edit), table links, pager; the picker and the sheet focus order; hover tooltip on truncated text.
|
||||||
|
- Delete a type in another tab, then reload /content/<key>: not found page.
|
||||||
@@ -0,0 +1,355 @@
|
|||||||
|
Feature: Owners and admins define custom content types, and users manage entries of those types through a generic /v1 API
|
||||||
|
|
||||||
|
As a site owner or admin
|
||||||
|
I want to define content types made of ordered scalar fields, and then create entries of those types
|
||||||
|
So that I can store structured content beyond articles, with the schema enforced by the server
|
||||||
|
|
||||||
|
Background:
|
||||||
|
Given internal/domain/contenttype defines the entity ContentType with ID uint32, Key, Name,
|
||||||
|
Fields []Field, CreatedAt and UpdatedAt, with snake_case json tags
|
||||||
|
And Field is a value object, ordered by its position in ContentType.Fields, with Key, Label,
|
||||||
|
Type, Required, Unique, Default, Min, Max and Options
|
||||||
|
And the field types are "text", "richtext", "number", "boolean", "date" and "select"
|
||||||
|
And a content type key matches the domain slug rule and has 2 to 40 characters
|
||||||
|
And a field key matches ^[a-z][a-z0-9_]{0,39}$, is unique within its type, and a type has 1 to 50 fields
|
||||||
|
And internal/domain/contenttype defines the sentinels ErrContentTypeNotFound, ErrKeyTaken,
|
||||||
|
ErrInvalidKey, ErrInvalidField, ErrHasEntries and ErrSchemaIncompatible
|
||||||
|
And internal/domain/contenttype defines the interface Repository with Create, GetByKey, List,
|
||||||
|
Update and Delete
|
||||||
|
And internal/domain/entry defines the entity Entry with ID uint32, ContentTypeID, Data
|
||||||
|
(a JSON object), CreatedBy, UpdatedBy, CreatedAt and UpdatedAt
|
||||||
|
And internal/domain/entry defines the sentinels ErrEntryNotFound, ErrInvalidEntry and
|
||||||
|
ErrUniqueViolation, and the interface Repository with Create, Get, ListPage, Update, Delete,
|
||||||
|
DeleteByContentType, CountByContentType and FindByFieldValue(contentTypeID, fieldKey, value, excludeID)
|
||||||
|
And schema validation of a field list and of an entry's data lives in the domain/use cases,
|
||||||
|
never in handlers, and handler request structs still use validate tags
|
||||||
|
And the use cases CreateContentType, ListContentTypes, GetContentType, UpdateContentType,
|
||||||
|
DeleteContentType, CreateEntry, GetEntry, ListEntries, UpdateEntry and DeleteEntry depend only
|
||||||
|
on the two domain repositories and an injected clock
|
||||||
|
And persistence stores content types in one table with the fields as a JSON text column, and
|
||||||
|
entries in one generic table with the data as a JSON text column, so no DDL runs at runtime
|
||||||
|
and the SQL is portable across SQLite, MySQL/MariaDB and PostgreSQL
|
||||||
|
And both GORM models are added to the AutoMigrate list and wired only in api/dependecyInjection.go
|
||||||
|
And the built-in articles, authors, sites, media and users are not part of this engine
|
||||||
|
And the routes are mounted under /v1/content-type in a router with jwtauth.Verifier, apiKeyAuth,
|
||||||
|
AuditContext, RequireSignedIn, jwtauth.Authenticator, RequireCurrentToken and
|
||||||
|
RequireVerifiedUser, and POST /v1/content-type, PUT /v1/content-type/{key} and
|
||||||
|
DELETE /v1/content-type/{key} additionally sit behind RequireOwnerOrAdmin
|
||||||
|
And a content type response has exactly the keys id, key, name, icon, fields, created_at, updated_at
|
||||||
|
And a field response has exactly the keys key, label, type, required, unique, default, min, max,
|
||||||
|
options, with null for an unset default, min and max and [] for no options
|
||||||
|
And an entry response has exactly the keys id, content_type, data, created_by, updated_by,
|
||||||
|
created_at, updated_at, media, where content_type is the type's key
|
||||||
|
And errors are plain text from http.Error, and the new apperr strings are
|
||||||
|
content_type_not_found, content_type_key_taken, content_type_has_entries,
|
||||||
|
invalid_content_type_key, invalid_field, schema_incompatible, entry_not_found and invalid_entry
|
||||||
|
And users: owner id 1 "marta" (verified), admin id 2 "dev" (verified), unverified id 4 "quinn"
|
||||||
|
And the sample type "recipe" has the fields, in order:
|
||||||
|
| key | type | required | unique | default | min | max | options |
|
||||||
|
| title | text | true | true | | 3 | 80 | |
|
||||||
|
| servings | number | false | false | 4 | 1 | 50 | |
|
||||||
|
| vegetarian | boolean | false | false | false | | | |
|
||||||
|
| published_on | date | false | false | | | | |
|
||||||
|
| difficulty | select | true | false | | | | easy, medium, hard |
|
||||||
|
| notes | richtext | false | false | | | 500 | |
|
||||||
|
|
||||||
|
Scenario: Creating a content type
|
||||||
|
Given a valid jwt cookie for admin 2
|
||||||
|
When the client sends POST /v1/content-type with body
|
||||||
|
{"key": "recipe", "name": "Recipe", "fields": [<the sample fields>]}
|
||||||
|
Then the response status is 201
|
||||||
|
And the body has exactly the keys id, key, name, icon, fields, created_at, updated_at
|
||||||
|
And key is "recipe" and the fields come back in the order sent
|
||||||
|
And each field has exactly the keys key, label, type, required, unique, default, min, max, options
|
||||||
|
|
||||||
|
Scenario Outline: Creating a content type with an invalid body is refused and stores nothing
|
||||||
|
Given a valid jwt cookie for admin 2
|
||||||
|
When the client sends POST /v1/content-type with <body>
|
||||||
|
Then the response status is <status>
|
||||||
|
And the response body is <message>
|
||||||
|
And no content type exists in the repository
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| body | status | message |
|
||||||
|
| body not-json | 400 | apperr.BodyErrorMessage |
|
||||||
|
| body {} | 400 | text containing 'Key' and 'required' |
|
||||||
|
| {"key": "Recipe!", "name": "R", "fields": [<one text field>]} | 400 | invalid_content_type_key |
|
||||||
|
| {"key": "r", "name": "R", "fields": [<one text field>]} | 400 | invalid_content_type_key |
|
||||||
|
| {"key": "recipe", "name": "", "fields": [<one text field>]} | 400 | text containing 'Name' and 'required' |
|
||||||
|
| {"key": "recipe", "name": "R", "fields": []} | 422 | invalid_field |
|
||||||
|
| {"key": "recipe", "name": "R", "fields": [<51 fields>]} | 422 | invalid_field |
|
||||||
|
| a field key "Title" or "1st" or "a-b" | 422 | invalid_field |
|
||||||
|
| two fields with the key "title" | 422 | invalid_field |
|
||||||
|
| a field type "integer" | 422 | invalid_field |
|
||||||
|
| a select field with no options, an empty option, or a duplicated option | 422 | invalid_field |
|
||||||
|
| options on a non-select field | 422 | invalid_field |
|
||||||
|
| min or max on a boolean or select field | 422 | invalid_field |
|
||||||
|
| min greater than max | 422 | invalid_field |
|
||||||
|
| a negative or fractional min or max on a text or richtext field | 422 | invalid_field |
|
||||||
|
| a non-date min or max on a date field | 422 | invalid_field |
|
||||||
|
| unique true on a richtext or boolean field | 422 | invalid_field |
|
||||||
|
| a default of the wrong type, outside min/max, or not in the options | 422 | invalid_field |
|
||||||
|
| a default on a unique field | 422 | invalid_field |
|
||||||
|
|
||||||
|
Scenario: A content type key can't be reused
|
||||||
|
Given the content type "recipe" exists
|
||||||
|
When admin 2 sends POST /v1/content-type with the key "recipe"
|
||||||
|
Then the response status is 409
|
||||||
|
And the response body is content_type_key_taken
|
||||||
|
And only one content type exists
|
||||||
|
|
||||||
|
Scenario Outline: Writing content types needs a verified owner or admin
|
||||||
|
Given <caller>
|
||||||
|
When the client sends POST /v1/content-type with a valid body
|
||||||
|
Then the response status is <status>
|
||||||
|
And the response body is <message>
|
||||||
|
And no content type exists in the repository
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| caller | status | message |
|
||||||
|
| no credentials | 401 | the existing Authenticator response |
|
||||||
|
| a jwt cookie for user 4 | 403 | apperr.VerificationRequiredErrorMessage |
|
||||||
|
| a stale token_version cookie | 401 | the existing Authenticator response |
|
||||||
|
|
||||||
|
Scenario: An API key acts as its creator on the content type routes
|
||||||
|
Given an active key created by admin 2
|
||||||
|
When the client sends POST /v1/content-type with that key and no cookie and a valid body
|
||||||
|
Then the response status is 201
|
||||||
|
|
||||||
|
Scenario: Listing and reading content types
|
||||||
|
Given the content types "recipe" and "event" exist
|
||||||
|
And a valid jwt cookie for any verified user
|
||||||
|
When the client sends GET /v1/content-type
|
||||||
|
Then the response status is 200
|
||||||
|
And the body is a JSON array of both content types, ordered by name
|
||||||
|
When the client sends GET /v1/content-type/recipe
|
||||||
|
Then the response status is 200 and the body is the "recipe" content type
|
||||||
|
|
||||||
|
Scenario Outline: Reading a content type that doesn't exist or with a bad key
|
||||||
|
Given a valid jwt cookie for admin 2
|
||||||
|
When the client sends <method> /v1/content-type/<key> <body>
|
||||||
|
Then the response status is <status>
|
||||||
|
And the response body is <message>
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| method | key | body | status | message |
|
||||||
|
| GET | nope | | 404 | content_type_not_found |
|
||||||
|
| PUT | nope | and a valid schema body | 404 | content_type_not_found |
|
||||||
|
| DELETE | nope | | 404 | content_type_not_found |
|
||||||
|
| GET | Bad_Key | | 404 | content_type_not_found |
|
||||||
|
|
||||||
|
Scenario: Updating a content type before it has entries
|
||||||
|
Given the content type "recipe" exists with no entries
|
||||||
|
When admin 2 sends PUT /v1/content-type/recipe with a new name, a removed field, a reordered
|
||||||
|
list and a changed field type
|
||||||
|
Then the response status is 200
|
||||||
|
And the body shows the new name, the new field order and the new field type
|
||||||
|
And the key is still "recipe"
|
||||||
|
|
||||||
|
Scenario: The key of a content type can't be changed
|
||||||
|
Given the content type "recipe" exists
|
||||||
|
When admin 2 sends PUT /v1/content-type/recipe with body key "dish"
|
||||||
|
Then the response status is 200
|
||||||
|
And the key is still "recipe"
|
||||||
|
|
||||||
|
Scenario Outline: Updating a content type that has entries
|
||||||
|
Given the content type "recipe" has an entry {"title": "Pad thai", "difficulty": "easy"}
|
||||||
|
When admin 2 sends PUT /v1/content-type/recipe with <change>
|
||||||
|
Then the response status is <status>
|
||||||
|
And the response body is <message>
|
||||||
|
And the stored schema is <outcome>
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| change | status | message | outcome |
|
||||||
|
| a field's type changed from text to number | 422 | invalid_field | unchanged |
|
||||||
|
| a new required field without a default | 409 | schema_incompatible | unchanged |
|
||||||
|
| a new required field with a default | 200 | | updated |
|
||||||
|
| a new optional field | 200 | | updated |
|
||||||
|
| the field "notes" removed | 200 | | updated |
|
||||||
|
| the option "easy" removed from difficulty | 409 | schema_incompatible | unchanged |
|
||||||
|
| the option "hard" removed from difficulty | 200 | | updated |
|
||||||
|
| title max lowered below the stored title's length | 409 | schema_incompatible | unchanged |
|
||||||
|
| label, order or name changed | 200 | | updated |
|
||||||
|
|
||||||
|
Scenario: Making a field unique is refused when stored values collide
|
||||||
|
Given the type "recipe" has two entries with the title "Pad thai" and the title is not unique
|
||||||
|
When admin 2 sends PUT /v1/content-type/recipe making title unique
|
||||||
|
Then the response status is 409 with schema_incompatible and the schema is unchanged
|
||||||
|
|
||||||
|
Scenario: Values of a removed field are no longer returned
|
||||||
|
Given an entry with notes "Soak overnight" and a schema update that removes "notes"
|
||||||
|
When a user sends GET on that entry
|
||||||
|
Then data has no "notes" key
|
||||||
|
When the entry is saved again through PUT
|
||||||
|
Then the stored document has no "notes" key
|
||||||
|
|
||||||
|
Scenario: Deleting a content type
|
||||||
|
Given the content type "event" exists with no entries
|
||||||
|
When admin 2 sends DELETE /v1/content-type/event
|
||||||
|
Then the response status is 204 and the body is empty
|
||||||
|
And GET /v1/content-type/event returns 404 with content_type_not_found
|
||||||
|
|
||||||
|
Scenario: A content type with entries can't be deleted
|
||||||
|
Given the content type "recipe" has one entry
|
||||||
|
When admin 2 sends DELETE /v1/content-type/recipe
|
||||||
|
Then the response status is 409
|
||||||
|
And the response body is content_type_has_entries
|
||||||
|
And the type and its entry still exist
|
||||||
|
|
||||||
|
Scenario: Creating an entry applies defaults
|
||||||
|
Given the content type "recipe" exists and a valid jwt cookie for admin 2
|
||||||
|
When the client sends POST /v1/content-type/recipe/entry with body
|
||||||
|
{"data": {"title": "Pad thai", "difficulty": "easy"}}
|
||||||
|
Then the response status is 201
|
||||||
|
And the body has exactly the keys id, content_type, data, created_by, updated_by, created_at, updated_at, media
|
||||||
|
And content_type is "recipe", created_by and updated_by are 2
|
||||||
|
And data is {"title": "Pad thai", "difficulty": "easy", "servings": 4, "vegetarian": false}
|
||||||
|
And data has no "published_on" and no "notes" key
|
||||||
|
|
||||||
|
Scenario: An explicit value overrides the default and an explicit null is kept
|
||||||
|
Given the content type "recipe" exists
|
||||||
|
When the client creates an entry with {"title": "Soup", "difficulty": "easy", "servings": 2, "published_on": null}
|
||||||
|
Then data servings is 2 and published_on is null and no default is applied to published_on
|
||||||
|
|
||||||
|
Scenario Outline: Creating an entry that breaks the schema is refused and stores nothing
|
||||||
|
Given the content type "recipe" exists and a valid jwt cookie
|
||||||
|
When the client sends POST /v1/content-type/recipe/entry with <body>
|
||||||
|
Then the response status is <status>
|
||||||
|
And the response body is <message>
|
||||||
|
And no entry exists
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| body | status | message |
|
||||||
|
| body not-json | 400 | apperr.BodyErrorMessage |
|
||||||
|
| {} | 400 | apperr.BodyErrorMessage |
|
||||||
|
| {"data": "x"} | 400 | apperr.BodyErrorMessage |
|
||||||
|
| {"data": {"difficulty": "easy"}} | 422 | invalid_entry: title: required |
|
||||||
|
| {"data": {"title": null, "difficulty": "easy"}} | 422 | invalid_entry: title: required |
|
||||||
|
| {"data": {"title": 5, "difficulty": "easy"}} | 422 | invalid_entry: title: type |
|
||||||
|
| {"data": {"title": "ab", "difficulty": "easy"}} | 422 | invalid_entry: title: min |
|
||||||
|
| {"data": {"title": "<81 runes>", "difficulty": "easy"}} | 422 | invalid_entry: title: max |
|
||||||
|
| {"data": {"title": "Soup", "difficulty": "extreme"}} | 422 | invalid_entry: difficulty: options |
|
||||||
|
| {"data": {"title": "Soup", "difficulty": "easy", "servings": 0}} | 422 | invalid_entry: servings: min |
|
||||||
|
| {"data": {"title": "Soup", "difficulty": "easy", "servings": 51}} | 422 | invalid_entry: servings: max |
|
||||||
|
| {"data": {"title": "Soup", "difficulty": "easy", "servings": "4"}} | 422 | invalid_entry: servings: type |
|
||||||
|
| {"data": {"title": "Soup", "difficulty": "easy", "vegetarian": "yes"}} | 422 | invalid_entry: vegetarian: type |
|
||||||
|
| {"data": {"title": "Soup", "difficulty": "easy", "published_on": "2026-02-30"}} | 422 | invalid_entry: published_on: type |
|
||||||
|
| {"data": {"title": "Soup", "difficulty": "easy", "published_on": "2026-02-01T10:00:00Z"}} | 422 | invalid_entry: published_on: type |
|
||||||
|
| {"data": {"title": "Soup", "difficulty": "easy", "notes": "<501 runes>"}} | 422 | invalid_entry: notes: max |
|
||||||
|
| {"data": {"title": "Soup", "difficulty": "easy", "colour": "red"}} | 422 | invalid_entry: colour: unknown_field |
|
||||||
|
|
||||||
|
Scenario: Boundary values are accepted
|
||||||
|
Given the content type "recipe" exists
|
||||||
|
When entries are created with a title of exactly 3 runes, exactly 80 runes, servings 1 and servings 50
|
||||||
|
Then each response status is 201
|
||||||
|
|
||||||
|
Scenario: Unique fields reject duplicates and ignore the entry itself
|
||||||
|
Given the content type "recipe" has an entry 7 with the title "Pad thai"
|
||||||
|
When the client sends POST /v1/content-type/recipe/entry with the title "Pad thai"
|
||||||
|
Then the response status is 409
|
||||||
|
And the response body is "invalid_entry: title: unique"
|
||||||
|
When the client sends PUT /v1/content-type/recipe/entry/7 with the same title "Pad thai" and a new servings
|
||||||
|
Then the response status is 200
|
||||||
|
|
||||||
|
Scenario: Unique values are scoped to their content type and ignore nulls
|
||||||
|
Given a content type "dish" with a unique text field "title" and an entry titled "Pad thai"
|
||||||
|
And the content type "recipe" has an entry titled "Pad thai"
|
||||||
|
Then both entries exist
|
||||||
|
And two entries of a type with an optional unique field both leaving it absent are accepted
|
||||||
|
|
||||||
|
Scenario: Getting an entry
|
||||||
|
Given the entry 7 of type "recipe"
|
||||||
|
When the client sends GET /v1/content-type/recipe/entry/7
|
||||||
|
Then the response status is 200 and the body is the entry
|
||||||
|
When the client sends GET /v1/content-type/dish/entry/7
|
||||||
|
Then the response status is 404 and the body is entry_not_found
|
||||||
|
|
||||||
|
Scenario Outline: Entry routes with a bad id or a missing resource
|
||||||
|
Given a valid jwt cookie
|
||||||
|
When the client sends <method> <path> <body>
|
||||||
|
Then the response status is <status>
|
||||||
|
And the response body is <message>
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| method | path | body | status | message |
|
||||||
|
| GET | /v1/content-type/recipe/entry/abc | | 400 | apperr.IdUint32ErrorMessage |
|
||||||
|
| GET | /v1/content-type/recipe/entry/-1 | | 400 | apperr.IdUint32ErrorMessage |
|
||||||
|
| GET | /v1/content-type/recipe/entry/4294967296 | | 400 | apperr.IdUint32ErrorMessage |
|
||||||
|
| GET | /v1/content-type/recipe/entry/999 | | 404 | entry_not_found |
|
||||||
|
| PUT | /v1/content-type/recipe/entry/999 | and a valid data body | 404 | entry_not_found |
|
||||||
|
| DELETE | /v1/content-type/recipe/entry/999 | | 404 | entry_not_found |
|
||||||
|
| GET | /v1/content-type/nope/entry/1 | | 404 | content_type_not_found |
|
||||||
|
| POST | /v1/content-type/nope/entry | and a valid data body | 404 | content_type_not_found |
|
||||||
|
| GET | /v1/content-type/nope/entry | | 404 | content_type_not_found |
|
||||||
|
|
||||||
|
Scenario: Replacing an entry validates the whole document and keeps provenance
|
||||||
|
Given the entry 7 of type "recipe" created by admin 2, and a valid jwt cookie for owner 1
|
||||||
|
When owner 1 sends PUT /v1/content-type/recipe/entry/7 with {"data": {"title": "Green curry", "difficulty": "medium"}}
|
||||||
|
Then the response status is 200
|
||||||
|
And data is exactly {"title": "Green curry", "difficulty": "medium"} with no default applied
|
||||||
|
And created_by is 2 and updated_by is 1 and updated_at is later than created_at
|
||||||
|
When owner 1 sends PUT with {"data": {"difficulty": "medium"}}
|
||||||
|
Then the response status is 422 with invalid_entry: title: required and the entry is unchanged
|
||||||
|
|
||||||
|
Scenario: Deleting an entry
|
||||||
|
Given the entry 7 of type "recipe"
|
||||||
|
When the client sends DELETE /v1/content-type/recipe/entry/7
|
||||||
|
Then the response status is 204 and the body is empty
|
||||||
|
And GET on entry 7 returns 404 with entry_not_found
|
||||||
|
|
||||||
|
Scenario Outline: Listing entries is paginated and sortable
|
||||||
|
Given 30 entries of type "recipe", and entries of type "dish" that must not appear
|
||||||
|
When the client sends GET /v1/content-type/recipe/entry<query>
|
||||||
|
Then the response status is <status>
|
||||||
|
And <result>
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| query | status | result |
|
||||||
|
| | 200 | items has 25 entries, total 30, page 1, size 25, ordered updated_at desc |
|
||||||
|
| ?page=2 | 200 | items has 5 entries, total 30, page 2, size 25 |
|
||||||
|
| ?size=5&page=2 | 200 | items has 5 entries, page 2, size 5 |
|
||||||
|
| ?sort=id:asc | 200 | items ordered by id ascending |
|
||||||
|
| ?sort=created_at:desc | 200 | items ordered by created_at descending |
|
||||||
|
| ?page=99 | 200 | items is [] and total is 30 |
|
||||||
|
| ?page=0 | 400 | apperr.BodyErrorMessage |
|
||||||
|
| ?size=7 | 400 | apperr.BodyErrorMessage |
|
||||||
|
| ?sort=data:asc | 400 | apperr.BodyErrorMessage |
|
||||||
|
| ?page=abc | 400 | apperr.BodyErrorMessage |
|
||||||
|
|
||||||
|
Scenario: An empty content type lists no entries
|
||||||
|
Given the content type "event" with no entries
|
||||||
|
When the client sends GET /v1/content-type/event/entry
|
||||||
|
Then the body is {"items": [], "total": 0, "page": 1, "size": 25} and items is a JSON array, not null
|
||||||
|
|
||||||
|
Scenario Outline: Entry routes accept any verified user and API keys, and refuse everyone else
|
||||||
|
Given the content type "recipe" exists
|
||||||
|
When <caller> sends POST /v1/content-type/recipe/entry with a valid body
|
||||||
|
Then the response status is <status>
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| caller | status |
|
||||||
|
| an admin cookie | 201 |
|
||||||
|
| an owner cookie | 201 |
|
||||||
|
| an active API key of admin 2 | 201 |
|
||||||
|
| no credentials | 401 |
|
||||||
|
| a cookie for unverified 4 | 403 |
|
||||||
|
| a stale token_version cookie | 401 |
|
||||||
|
|
||||||
|
Scenario: Built-in resources are not reachable through the generic engine
|
||||||
|
Given a valid jwt cookie for admin 2
|
||||||
|
When the client creates a content type with the key "article" and sends GET /v1/content-type/article/entry
|
||||||
|
Then the routes behave as for any custom type and GET /v1/article is unchanged
|
||||||
|
And no article, author, site, media or user is read or written by the engine
|
||||||
|
|
||||||
|
Scenario: Use case: validating an entry against a schema returns domain sentinels
|
||||||
|
Given a fake contenttype.Repository holding "recipe" and a fake entry.Repository
|
||||||
|
When CreateEntry is called with data breaking each rule in the table above
|
||||||
|
Then errors.Is(err, entry.ErrInvalidEntry) is true for each, and the repository received no Create
|
||||||
|
And a duplicate unique value returns an error satisfying errors.Is(err, entry.ErrUniqueViolation)
|
||||||
|
|
||||||
|
Scenario: Use case: schema updates re-validate stored entries
|
||||||
|
Given a fake entry.Repository holding entries and a fake contenttype.Repository
|
||||||
|
When UpdateContentType is called with a schema that an existing entry violates
|
||||||
|
Then it returns contenttype.ErrSchemaIncompatible and the repository Update is not called
|
||||||
|
And a type change returns contenttype.ErrInvalidField
|
||||||
|
And DeleteContentType with entries returns contenttype.ErrHasEntries and nothing is deleted
|
||||||
@@ -0,0 +1,100 @@
|
|||||||
|
# QA procedure: custom content types (backend core)
|
||||||
|
|
||||||
|
Package: `test` (black-box). No live server, no real SQLite file, no real SMTP.
|
||||||
|
|
||||||
|
## Setup shared by every case
|
||||||
|
1. Call `validator.InitValidator()` once per test.
|
||||||
|
2. Add in-memory fakes with unique type names across the package: `mockContentTypeRepo`
|
||||||
|
(implements `contenttype.Repository`, `failNext("Update")` style switch) and `mockEntryRepo` (implements `entry.Repository`, with
|
||||||
|
`CountByContentType`; `FindByFieldValue` compares decoded
|
||||||
|
JSON values in Go; ordering, paging and per-type scoping implemented like the real contract; an
|
||||||
|
`createCalls` counter). Reuse `mockUserRepo`, `stubHasher` and the API key fakes.
|
||||||
|
3. Build the handler stack from a `*api.UseCases` container holding fakes and mount
|
||||||
|
`api.InitBackendRoutes(container, settings)` on a test server (unused use cases stay nil). If a nil
|
||||||
|
use case breaks a constructor, fall back to a fresh `chi.NewRouter()` mirroring the new
|
||||||
|
content type router: `jwtauth.Verifier`, key middleware, `RequireSignedIn`, `jwtauth.Authenticator`,
|
||||||
|
`RequireCurrentToken`, `RequireVerifiedUser`, with `RequireOwnerOrAdmin` on POST/PUT/DELETE
|
||||||
|
`/content-type`. Token: `jwtauth.New("HS256", []byte("test-secret"), nil)`.
|
||||||
|
4. Inject a fake clock (`now func() time.Time`) into the use cases so `updated_at` > `created_at`.
|
||||||
|
5. Seed users: owner 1 "marta", admin 2 "dev" (verified), unverified 4 "quinn". Helpers: `cookieFor(userId,
|
||||||
|
tokenVersion)`, `bearer(raw)`; create the API key through `POST /v1/api-key`.
|
||||||
|
6. Helper `sampleRecipe()` builds the "recipe" request body from the feature's table.
|
||||||
|
|
||||||
|
## Content type create and validation
|
||||||
|
7. Admin 2 `POST /v1/content-type` with the recipe -> `201`; key set is exactly `id`, `key`, `name`, `icon`,
|
||||||
|
`fields`, `created_at`, `updated_at`; each field has exactly `key`, `label`, `type`, `required`,
|
||||||
|
`unique`, `default`, `min`, `max`, `options`; order preserved; `default`/`min`/`max` are JSON `null`
|
||||||
|
and `options` is `[]` when unset.
|
||||||
|
8. Invalid-body table (feature table): each case asserts status, exact body (or contains for
|
||||||
|
validator text), and that `mockContentTypeRepo` is empty. Cover not-json, `{}`, bad key (`Recipe!`,
|
||||||
|
1 char, 41 chars), empty name, 0 fields, 51 fields, bad/duplicate/overlong field keys, unknown type,
|
||||||
|
every min/max/options/unique/default rule violation.
|
||||||
|
9. Duplicate key -> `409` `content_type_key_taken`, one type stored.
|
||||||
|
10. Access table: no credentials `401`, user 4 `403` `apperr.VerificationRequiredErrorMessage`, stale
|
||||||
|
token_version `401`, API key of admin 2 `201`. Failures leave the repository empty.
|
||||||
|
|
||||||
|
## Content type read, update, delete
|
||||||
|
11. List returns an array ordered by name; `GET /{key}` returns the type; unknown or malformed key -> `404`
|
||||||
|
`content_type_not_found`; same for PUT and DELETE.
|
||||||
|
12. Update with no entries: name, order, removal and type change accepted (`200`); body key in the PUT is
|
||||||
|
ignored and the key stays.
|
||||||
|
13. Update with entries (table): type change `422 invalid_field`; new required without default `409
|
||||||
|
schema_incompatible`; new required with default `200`; new optional `200`; remove field `200`; remove
|
||||||
|
an option in use `409`; remove an unused option `200`; lower max below a stored value `409`; label,
|
||||||
|
order, name `200`. On every `409`/`422`, assert the stored schema is byte-identical to before
|
||||||
|
(`failNext` not used, compare the fake's stored type).
|
||||||
|
14. Make a field unique while two stored entries collide -> `409 schema_incompatible`, unchanged.
|
||||||
|
15. Removed field values are not returned on GET, and are absent from the stored document after the next
|
||||||
|
PUT of that entry.
|
||||||
|
16. Delete without entries -> `204` empty body, then `404`. Delete with entries -> `409
|
||||||
|
content_type_has_entries`, type and entries intact.
|
||||||
|
17. Repository failure on Update/Delete -> `500` "Internal server error", state unchanged.
|
||||||
|
|
||||||
|
## Entries
|
||||||
|
18. Create with defaults: response key set exactly `id`, `content_type`, `data`, `created_by`,
|
||||||
|
`updated_by`, `created_at`, `updated_at`; `data` equals `{"title","difficulty","servings":4,
|
||||||
|
"vegetarian":false}`; no `published_on`/`notes` key; `created_by` = `updated_by` = 2.
|
||||||
|
19. Explicit value beats default; explicit `null` is kept and no default is applied to it.
|
||||||
|
20. Invalid-data table (feature table, include 400s: not-json, `{}`, non-object `data`): assert status,
|
||||||
|
exact body, and `createCalls == 0`. Include the date cases `2026-02-30` and a datetime string, a
|
||||||
|
string number `"4"`, and an unknown field `colour`.
|
||||||
|
21. Boundaries: title of exactly 3 and 80 runes (use a multibyte string to pin rune counting), servings 1
|
||||||
|
and 50, notes 500 runes -> `201`; one beyond each -> `422`.
|
||||||
|
22. Unique: second entry with the same title -> `409` body `invalid_entry: title: unique`; PUT on the
|
||||||
|
same entry with its own title -> `200`; same title in another type -> `201`; two entries both
|
||||||
|
omitting an optional unique field -> `201`.
|
||||||
|
23. GET: entry of another type's key -> `404` `entry_not_found`; unknown type -> `404`
|
||||||
|
`content_type_not_found`; ids `abc`, `-1`, `4294967296` -> `400` `apperr.IdUint32ErrorMessage`.
|
||||||
|
24. PUT replaces data wholesale: no defaults re-applied; `created_by` unchanged, `updated_by` = caller,
|
||||||
|
`updated_at` > `created_at`; invalid replacement -> `422` and the stored entry unchanged.
|
||||||
|
25. DELETE -> `204`, empty body, then `404`; unknown id `404 entry_not_found`.
|
||||||
|
26. List: seed 30 recipes and some dishes; default page (25 items, total 30, page 1, size 25,
|
||||||
|
`updated_at:desc`), `?page=2`, `?size=5&page=2`, `?sort=id:asc`, `?sort=created_at:desc`, `?page=99`
|
||||||
|
(`items: []`, total 30). Bad `page=0`, `size=7`, `sort=data:asc`, `page=abc` -> `400`
|
||||||
|
`apperr.BodyErrorMessage`. Empty type -> `items` is `[]` (assert JSON `[]`, not `null`).
|
||||||
|
27. Access table on entry routes: admin, owner, API key -> `201`; none `401`; user 4 `403`; stale `401`.
|
||||||
|
A non-admin verified caller can read and write entries but not content types (only if a
|
||||||
|
non-owner/non-admin role exists in the fake; otherwise skip and note it).
|
||||||
|
28. Isolation: creating a type keyed `article` does not affect `GET /v1/article`; no built-in repository
|
||||||
|
fake is called by any case in this file.
|
||||||
|
|
||||||
|
## Use case level (no HTTP)
|
||||||
|
29. `CreateEntry`/`UpdateEntry` against `mockContentTypeRepo` + `mockEntryRepo`: each rule breach ->
|
||||||
|
`errors.Is(err, entry.ErrInvalidEntry)` and no write; duplicate -> `entry.ErrUniqueViolation`.
|
||||||
|
30. `UpdateContentType`: incompatible stored entry -> `contenttype.ErrSchemaIncompatible` and no `Update`
|
||||||
|
call; type change -> `ErrInvalidField`; `DeleteContentType` with entries ->
|
||||||
|
`ErrHasEntries`; unknown key -> `ErrContentTypeNotFound`; taken key -> `ErrKeyTaken`.
|
||||||
|
31. Schema validator unit table: every row of the "invalid body" table asserted on the domain function
|
||||||
|
directly with `errors.Is(err, contenttype.ErrInvalidField)`.
|
||||||
|
|
||||||
|
## Manual verification (not exercised by the Go tests)
|
||||||
|
- Real SQLite, then MySQL/MariaDB and PostgreSQL via the existing driver tasks: start `task dev:api`,
|
||||||
|
confirm `AutoMigrate` creates the content type and entry tables with the JSON documents in text
|
||||||
|
columns and no table gets created or altered when a new content type is defined.
|
||||||
|
- Create a type, restart the server and confirm types and entries persist; create 1,000 entries and
|
||||||
|
confirm list paging and the unique check stay responsive (the unique check is a portable lookup, not a
|
||||||
|
DB index).
|
||||||
|
- Fire two concurrent POSTs with the same unique value and record the outcome (known limitation: the
|
||||||
|
check is not transactional).
|
||||||
|
- With curl and an API key, create a type and an entry from a non-browser client and confirm a browser
|
||||||
|
origin in `CORS_ALLOWED_ORIGINS` can use PUT and DELETE (preflight allows them).
|
||||||
@@ -0,0 +1,235 @@
|
|||||||
|
Feature: Content types carry an optional icon, built-in types are readable, and verified users can resolve user display names
|
||||||
|
|
||||||
|
As an owner, admin or verified user working in the SPA
|
||||||
|
I want an icon per content type, a read-only view of the built-in types and the display names of entry authors
|
||||||
|
So that the sidebar, the Schema screen and the entry screens can be drawn without leaking account data
|
||||||
|
|
||||||
|
Background:
|
||||||
|
Given the existing content type contract of custom_content_types.feature is unchanged except
|
||||||
|
that a content type response now has exactly the keys id, key, name, icon, fields, created_at,
|
||||||
|
updated_at
|
||||||
|
And a content type icon is null or a string matching ^[a-z][a-z0-9-]{0,39}$ and it is never
|
||||||
|
checked against a list of known icons
|
||||||
|
And internal/domain/contenttype defines the sentinel ErrInvalidIcon and the apperr string is
|
||||||
|
invalid_icon
|
||||||
|
And the icon is stored in a nullable column added by AutoMigrate, so existing rows read as null,
|
||||||
|
and the fields column stays a JSON text column
|
||||||
|
And an empty icon "" is stored as null
|
||||||
|
And a PUT replaces the icon like it replaces the name and the fields, so an absent icon clears it
|
||||||
|
And internal/domain/builtintype defines the static catalogue of the built-in types article,
|
||||||
|
author, site, media and user, in this order, each with a name and a list of fields shaped like
|
||||||
|
a content type field (key, label, type, required, unique, default, min, max, options)
|
||||||
|
And the catalogue uses no repository and no database, and the use cases ListBuiltinTypes and
|
||||||
|
GetBuiltinType depend only on that package
|
||||||
|
And the routes GET /v1/builtin-type and GET /v1/builtin-type/{key} are mounted in a router with
|
||||||
|
jwtauth.Verifier, apiKeyAuth, AuditContext, RequireSignedIn, jwtauth.Authenticator,
|
||||||
|
RequireCurrentToken, RequireVerifiedUser and RequireOwnerOrAdmin
|
||||||
|
And a built-in type response has exactly the keys key, name, fields
|
||||||
|
And the new apperr string is builtin_type_not_found
|
||||||
|
And the route GET /v1/user/lookup is mounted on the existing user router behind the verified
|
||||||
|
user chain with no role requirement
|
||||||
|
And a lookup item has exactly the keys id and display_name
|
||||||
|
And users: owner id 1 "marta" with display name "Marta Alves", admin id 2 "dev" with no
|
||||||
|
display name, verified id 3 "sam" with display name "Sam Roy", unverified id 4 "quinn"
|
||||||
|
And only the roles owner and admin exist, so every verified user passes RequireOwnerOrAdmin
|
||||||
|
And errors are plain text from http.Error
|
||||||
|
|
||||||
|
Scenario: Creating a content type with an icon
|
||||||
|
Given a valid jwt cookie for admin 2
|
||||||
|
When the client sends POST /v1/content-type with the recipe body and "icon": "chef-hat"
|
||||||
|
Then the response status is 201
|
||||||
|
And the body has exactly the keys id, key, name, icon, fields, created_at, updated_at
|
||||||
|
And icon is "chef-hat"
|
||||||
|
And GET /v1/content-type/recipe and GET /v1/content-type both show icon "chef-hat"
|
||||||
|
|
||||||
|
Scenario Outline: A content type without an icon has a null icon
|
||||||
|
Given a valid jwt cookie for admin 2
|
||||||
|
When the client creates "recipe" with <icon>
|
||||||
|
Then the response status is 201 and icon is null in the response, in GET /v1/content-type/recipe and in the list
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| icon |
|
||||||
|
| no icon key |
|
||||||
|
| "icon": null |
|
||||||
|
| "icon": "" |
|
||||||
|
|
||||||
|
Scenario: A content type stored before this slice still works
|
||||||
|
Given the content type "recipe" was stored with no icon value
|
||||||
|
When a verified user sends GET /v1/content-type and GET /v1/content-type/recipe
|
||||||
|
Then the response status is 200 and icon is null and all other keys are unchanged
|
||||||
|
|
||||||
|
Scenario Outline: An invalid icon is refused and stores nothing
|
||||||
|
Given a valid jwt cookie for admin 2
|
||||||
|
When the client sends POST /v1/content-type with a valid body and "icon": <icon>
|
||||||
|
Then the response status is 400
|
||||||
|
And the response body is invalid_icon
|
||||||
|
And no content type exists in the repository
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| icon |
|
||||||
|
| "Chef-Hat" |
|
||||||
|
| "1star" |
|
||||||
|
| "-star" |
|
||||||
|
| "chef hat" |
|
||||||
|
| "chef_hat" |
|
||||||
|
| "<41 characters>" |
|
||||||
|
| 5 |
|
||||||
|
|
||||||
|
Scenario: Boundary icons are accepted
|
||||||
|
Given a valid jwt cookie for admin 2
|
||||||
|
When the client creates types with the icons "a" and a 40 character icon "a" followed by 39 "b"
|
||||||
|
Then each response status is 201
|
||||||
|
|
||||||
|
Scenario Outline: Updating the icon of a content type
|
||||||
|
Given the content type "recipe" exists with the icon "chef-hat" and has an entry
|
||||||
|
When admin 2 sends PUT /v1/content-type/recipe with the same fields and <icon>
|
||||||
|
Then the response status is <status>
|
||||||
|
And <outcome>
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| icon | status | outcome |
|
||||||
|
| "icon": "utensils" | 200 | icon is "utensils" |
|
||||||
|
| no icon key | 200 | icon is null |
|
||||||
|
| "icon": null | 200 | icon is null |
|
||||||
|
| "icon": "Bad Icon" | 400 | the body is invalid_icon and the icon is still "chef-hat" |
|
||||||
|
|
||||||
|
Scenario: The icon does not affect entries
|
||||||
|
Given the content type "recipe" has an entry and admin 2 changes only the icon
|
||||||
|
Then the response status is 200 and the entry data and its updated_at are unchanged
|
||||||
|
|
||||||
|
Scenario: Listing the built-in types
|
||||||
|
Given a valid jwt cookie for owner 1
|
||||||
|
When the client sends GET /v1/builtin-type
|
||||||
|
Then the response status is 200
|
||||||
|
And the body is a JSON array of 5 items with the keys article, author, site, media, user in this order
|
||||||
|
And each item has exactly the keys key, name, fields
|
||||||
|
And the names are "Articles", "Authors", "Sites", "Media" and "Users"
|
||||||
|
And every field has exactly the keys key, label, type, required, unique, default, min, max, options
|
||||||
|
And every field type is one of text, richtext, number, boolean, date, select
|
||||||
|
|
||||||
|
Scenario Outline: The built-in field lists match the real API
|
||||||
|
Given a valid jwt cookie for admin 2
|
||||||
|
When the client sends GET /v1/builtin-type/<key>
|
||||||
|
Then the response status is 200
|
||||||
|
And the field keys, in order, are <fields>
|
||||||
|
And no field key is one of id, created_at, updated_at, password, password_reset_code, verification_code, token_version
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| key | fields |
|
||||||
|
| article | title, body, slug, excerpt, seo_title, seo_description, is_online, canonical_url, noindex |
|
||||||
|
| author | name, slug, bio, website |
|
||||||
|
| site | name, key, base_url, default_robots, locale, is_default, site_name, title_template, default_description |
|
||||||
|
| media | filename, size, width, height, content_type |
|
||||||
|
| user | username, display_name, email, role |
|
||||||
|
|
||||||
|
Scenario Outline: Selected built-in field rules
|
||||||
|
Given a valid jwt cookie for admin 2
|
||||||
|
When the client sends GET /v1/builtin-type/<key>
|
||||||
|
Then the field <field> has type <type>, required <required>, min <min>, max <max> and options <options>
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| key | field | type | required | min | max | options |
|
||||||
|
| article | title | text | true | 3 | 200 | [] |
|
||||||
|
| article | body | richtext | false | null | null | [] |
|
||||||
|
| article | excerpt | text | false | null | 300 | [] |
|
||||||
|
| article | is_online | boolean | false | null | null | [] |
|
||||||
|
| site | default_robots | select | false | null | null | index, noindex |
|
||||||
|
| site | site_name | text | false | null | 100 | [] |
|
||||||
|
| site | title_template | text | false | null | 200 | [] |
|
||||||
|
| site | default_description | text | false | null | 320 | [] |
|
||||||
|
| user | role | select | true | null | null | owner, admin |
|
||||||
|
| user | email | text | true | null | null | [] |
|
||||||
|
|
||||||
|
Scenario: Reading one built-in type does not collide with a custom type of the same key
|
||||||
|
Given the custom content type "builtin" exists, and a custom content type "article" exists
|
||||||
|
And a valid jwt cookie for admin 2
|
||||||
|
When the client sends GET /v1/content-type/builtin and GET /v1/content-type/article
|
||||||
|
Then each response is the custom content type
|
||||||
|
When the client sends GET /v1/builtin-type/article
|
||||||
|
Then the response is the built-in article type
|
||||||
|
And GET /v1/content-type never lists a built-in type
|
||||||
|
|
||||||
|
Scenario Outline: The built-in routes are read-only and restricted
|
||||||
|
Given <caller>
|
||||||
|
When the client sends <method> <path>
|
||||||
|
Then the response status is <status>
|
||||||
|
And the response body is <message>
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| caller | method | path | status | message |
|
||||||
|
| owner 1 cookie | GET | /v1/builtin-type | 200 | |
|
||||||
|
| admin 2 cookie | GET | /v1/builtin-type/user | 200 | |
|
||||||
|
| an active API key of admin 2 | GET | /v1/builtin-type | 200 | |
|
||||||
|
| a cookie for unverified 4 | GET | /v1/builtin-type | 403 | apperr.VerificationRequiredErrorMessage |
|
||||||
|
| no credentials | GET | /v1/builtin-type | 401 | the existing Authenticator response |
|
||||||
|
| a stale token_version cookie | GET | /v1/builtin-type | 401 | the existing Authenticator response |
|
||||||
|
| admin 2 cookie | GET | /v1/builtin-type/nope | 404 | builtin_type_not_found |
|
||||||
|
| admin 2 cookie | GET | /v1/builtin-type/Article | 404 | builtin_type_not_found |
|
||||||
|
| admin 2 cookie | POST | /v1/builtin-type | 405 | empty |
|
||||||
|
| admin 2 cookie | PUT | /v1/builtin-type/article | 405 | empty |
|
||||||
|
| admin 2 cookie | DELETE | /v1/builtin-type/article | 405 | empty |
|
||||||
|
|
||||||
|
Scenario: Reading the built-in types never touches data
|
||||||
|
Given fake repositories for content types, entries, articles, authors, sites, media and users
|
||||||
|
When the client sends GET /v1/builtin-type and GET /v1/builtin-type/site
|
||||||
|
Then no repository method is called
|
||||||
|
|
||||||
|
Scenario: Any verified user resolves display names
|
||||||
|
Given a valid jwt cookie for verified user 3
|
||||||
|
When the client sends GET /v1/user/lookup?ids=1,2,3
|
||||||
|
Then the response status is 200
|
||||||
|
And the body is a JSON array of 3 items ordered by id
|
||||||
|
And each item has exactly the keys id and display_name
|
||||||
|
And the display names are "Marta Alves", "dev" (the username, because the display name is empty) and "Sam Roy"
|
||||||
|
And the body contains no email, role, username or status
|
||||||
|
|
||||||
|
Scenario Outline: Lookup edge cases
|
||||||
|
Given a valid jwt cookie for verified user 3
|
||||||
|
When the client sends GET /v1/user/lookup<query>
|
||||||
|
Then the response status is <status>
|
||||||
|
And the response body is <message>
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| query | status | message |
|
||||||
|
| ?ids=2,2,2 | 200 | an array with one item for id 2 |
|
||||||
|
| ?ids=1,999 | 200 | an array with only id 1 |
|
||||||
|
| ?ids=999 | 200 | [] |
|
||||||
|
| ?ids=4 | 200 | an array with the item for id 4 |
|
||||||
|
| (no query) | 400 | apperr.BodyErrorMessage |
|
||||||
|
| ?ids= | 400 | apperr.BodyErrorMessage |
|
||||||
|
| ?ids=abc | 400 | apperr.BodyErrorMessage |
|
||||||
|
| ?ids=1,-2 | 400 | apperr.BodyErrorMessage |
|
||||||
|
| ?ids=1,4294967296 | 400 | apperr.BodyErrorMessage |
|
||||||
|
| ?ids=1,,2 | 400 | apperr.BodyErrorMessage |
|
||||||
|
| 101 distinct ids | 400 | apperr.BodyErrorMessage |
|
||||||
|
| exactly 100 ids | 200 | an array of the existing users |
|
||||||
|
|
||||||
|
Scenario Outline: Lookup needs a verified signed-in user or an API key
|
||||||
|
Given <caller>
|
||||||
|
When the client sends GET /v1/user/lookup?ids=1
|
||||||
|
Then the response status is <status>
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| caller | status |
|
||||||
|
| a cookie for verified user 3 | 200 |
|
||||||
|
| an active API key of admin 2 | 200 |
|
||||||
|
| no credentials | 401 |
|
||||||
|
| a cookie for unverified 4 | 403 |
|
||||||
|
| a stale token_version cookie | 401 |
|
||||||
|
|
||||||
|
Scenario: Existing user and entry responses are unchanged
|
||||||
|
Given a valid jwt cookie for verified user 3
|
||||||
|
When the client sends GET /v1/user/ and GET /v1/content-type/recipe/entry
|
||||||
|
Then the responses keep their existing shapes, and created_by and updated_by stay numeric ids
|
||||||
|
|
||||||
|
Scenario: Use case: the icon rule returns a domain sentinel
|
||||||
|
Given a fake contenttype.Repository
|
||||||
|
When CreateContentType and UpdateContentType are called with each invalid icon of the table above
|
||||||
|
Then errors.Is(err, contenttype.ErrInvalidIcon) is true and the repository received no Create or Update
|
||||||
|
|
||||||
|
Scenario: Use case: the catalogue and the lookup
|
||||||
|
Given the builtintype package and a fake user.Repository
|
||||||
|
When ListBuiltinTypes and GetBuiltinType("nope") are called
|
||||||
|
Then the list has 5 types and the unknown key returns builtintype.ErrNotFound
|
||||||
|
When LookupUserNames is called with ids 1, 2, 999
|
||||||
|
Then it returns the display name for 1, the username for 2, and nothing for 999
|
||||||
@@ -0,0 +1,91 @@
|
|||||||
|
# QA procedure: custom content types support (icon, built-in read model, user lookup)
|
||||||
|
|
||||||
|
Package: `test` (black-box). No live server, no real SQLite file, no real SMTP.
|
||||||
|
|
||||||
|
## Setup shared by every case
|
||||||
|
1. Call `validator.InitValidator()` once per test.
|
||||||
|
2. Reuse the existing fakes `mockContentTypeRepo`, `mockEntryRepo`, `mockUserRepo`, `stubHasher` and the API key
|
||||||
|
fakes from the custom content types tests. Extend `mockUserRepo` with the batch lookup by ids (unknown ids
|
||||||
|
skipped). Add a counting wrapper (`countingRepos`) that records any call on the article, author, site,
|
||||||
|
media, user, content type and entry fakes, with a unique type name across the package.
|
||||||
|
3. Build the `*api.UseCases` container with fakes and mount `api.InitBackendRoutes(container, settings)` on a
|
||||||
|
test server. If a nil use case breaks a constructor, fall back to a fresh `chi.NewRouter()` mirroring
|
||||||
|
`NewContentTypeRouter`, a new `NewBuiltinTypeRouter` (same chain plus `RequireOwnerOrAdmin`) and the user
|
||||||
|
router, with `jwtauth.New("HS256", []byte("test-secret"), nil)`.
|
||||||
|
4. Inject a fake clock into the use cases.
|
||||||
|
5. Seed users: owner 1 "marta" (display name "Marta Alves"), admin 2 "dev" (empty display name), verified
|
||||||
|
id 3 "sam" ("Sam Roy"), unverified 4 "quinn". Only the roles owner and admin exist, so no verified user is
|
||||||
|
rejected by `RequireOwnerOrAdmin`. Helpers: `cookieFor(userId, tokenVersion)`, `bearer(raw)`; the API key
|
||||||
|
through `POST /v1/api-key`.
|
||||||
|
6. Reuse `sampleRecipe()`; add `withIcon(body, value)` that sets, omits or nulls the icon key.
|
||||||
|
|
||||||
|
## Icon
|
||||||
|
7. Create with `"icon": "chef-hat"` -> 201; key set is exactly `id`, `key`, `name`, `icon`, `fields`, `created_at`,
|
||||||
|
`updated_at`; the icon is also present in `GET /{key}` and in the list. Update the existing pair's
|
||||||
|
"exactly the keys" wording and its QA step 7 accordingly.
|
||||||
|
8. Create with the key absent, `null` and `""` -> 201 and `icon` is JSON `null` in all three reads (assert the
|
||||||
|
raw JSON `null`, not a missing key and not `""`).
|
||||||
|
9. Legacy row: seed `mockContentTypeRepo` with a type that has no icon set; GET list and GET one -> 200, `icon`
|
||||||
|
null, other keys unchanged.
|
||||||
|
10. Invalid icons (`Chef-Hat`, `1star`, `-star`, `chef hat`, `chef_hat`, 41 characters, JSON number `5`) ->
|
||||||
|
400 `invalid_icon`, repository empty. 1 and 40 character icons -> 201.
|
||||||
|
11. PUT on a type that has an entry: new icon -> 200; absent -> 200 and null; `null` -> 200 and null; invalid ->
|
||||||
|
400 `invalid_icon` and the stored icon is unchanged. The stored entry and its `updated_at` are unchanged in
|
||||||
|
every case.
|
||||||
|
12. Use case level: `CreateContentType` / `UpdateContentType` with each invalid icon ->
|
||||||
|
`errors.Is(err, contenttype.ErrInvalidIcon)`, no `Create`/`Update` call on the fake. Domain table test of the
|
||||||
|
icon rule on the function directly.
|
||||||
|
13. Persistence mapper round trip (unit, no GORM): icon nil and non-nil survive the model/domain conversion in
|
||||||
|
both directions. The repository `Update` select list must include the icon (verified in the manual section
|
||||||
|
against the real DB).
|
||||||
|
|
||||||
|
## Built-in types
|
||||||
|
14. Owner `GET /v1/builtin-type` -> 200, array of 5, keys `article`, `author`, `site`, `media`, `user` in order,
|
||||||
|
names `Articles`, `Authors`, `Sites`, `Media`, `Users`; each item has exactly `key`, `name`, `fields`; each
|
||||||
|
field has exactly the nine field keys; every type is one of the six engine types.
|
||||||
|
15. Field-key table (feature table): per type, the ordered field keys; assert none of the forbidden keys
|
||||||
|
(`id`, `created_at`, `updated_at`, `password`, `password_reset_code`, `verification_code`, `token_version`)
|
||||||
|
appears in any type.
|
||||||
|
16. Rules table (feature table): spot-check type, required, min, max and options for the listed fields, with
|
||||||
|
`default`/`min`/`max` as JSON `null` and `options` as `[]` when unset. Rule values come from the request
|
||||||
|
structs; where a rule is not stated there (author bio max, media filename), leave min/max null.
|
||||||
|
17. Cross-check against the real contracts so the catalogue can't drift: for each built-in type, the JSON object
|
||||||
|
keys of the domain struct (via `json.Marshal` of the entity: `article.Article`, `author.Author`, `site.Site`,
|
||||||
|
`image.Image`, `user.User`) must contain every catalogue field key, using the json tags. Fail the test if a
|
||||||
|
catalogue key does not exist in the entity JSON.
|
||||||
|
18. `GET /v1/builtin-type/{key}` for each key -> 200 with the same item as in the list; `nope` and `Article` ->
|
||||||
|
404 `builtin_type_not_found`.
|
||||||
|
19. Collision: seed custom types `builtin` and `article`; `GET /v1/content-type/builtin` and `/article` return the
|
||||||
|
custom types; `GET /v1/content-type` lists only the custom ones; `GET /v1/builtin-type/article` returns the
|
||||||
|
built-in one.
|
||||||
|
20. Access table: owner 200, admin 200, API key of admin 200, user 4 403 `apperr.VerificationRequiredErrorMessage`,
|
||||||
|
none 401, stale 401. POST/PUT/DELETE on `/v1/builtin-type` and `/v1/builtin-type/article` -> 405 for admin.
|
||||||
|
(A verified non-owner non-admin 403 cannot be tested: no such role exists.)
|
||||||
|
21. Isolation: with the counting wrapper, calling the list and `GET /site` leaves every repository call count at
|
||||||
|
zero.
|
||||||
|
22. Use case level: `ListBuiltinTypes` returns 5 types; `GetBuiltinType("nope")` returns `builtintype.ErrNotFound`.
|
||||||
|
|
||||||
|
## User lookup
|
||||||
|
23. As verified user 3, `GET /v1/user/lookup?ids=1,2,3` -> 200; array ordered by id; each item has exactly `id`
|
||||||
|
and `display_name`; names `Marta Alves`, `dev`, `Sam Roy`; raw body contains none of `email`, `role`,
|
||||||
|
`username`, `status`, `password`.
|
||||||
|
24. Edge table (feature table): duplicates collapse, unknown ids are omitted, all-unknown -> `[]` (assert JSON
|
||||||
|
`[]` not `null`), unverified id 4 still resolves, missing/empty/non-numeric/negative/overflow/`1,,2`/101 ids
|
||||||
|
-> 400 `apperr.BodyErrorMessage`, exactly 100 ids -> 200.
|
||||||
|
25. Access table: verified user 3 200, API key of admin 2 200, none 401, user 4 403, stale token_version 401.
|
||||||
|
26. Regression: `GET /v1/user/` and entry responses are unchanged (same keys as before, `created_by`/`updated_by`
|
||||||
|
numeric).
|
||||||
|
27. Use case level: `LookupUserNames` with a fake `user.Repository` returns display name, falls back to the
|
||||||
|
username when it is empty, omits unknown ids, and makes a single batch call on the fake (no per-id lookups).
|
||||||
|
|
||||||
|
## Manual verification (not exercised by the Go tests)
|
||||||
|
- Start `task dev:api` on an existing database that already has content types: confirm AutoMigrate adds the
|
||||||
|
nullable icon column, old types read `icon: null`, and nothing else changes. Repeat on MySQL/MariaDB and
|
||||||
|
PostgreSQL via the existing driver tasks.
|
||||||
|
- Change an icon through PUT against the real SQLite file and reload: confirms the repository `Update` select
|
||||||
|
list includes the icon (the mapper test cannot).
|
||||||
|
- Compare `GET /v1/builtin-type/<key>` field rules with the real `POST`/`PATCH` validation of each resource once
|
||||||
|
(for example create a site with a 101 character `site_name`, expect a 400) to confirm that the stated max
|
||||||
|
values are honest.
|
||||||
|
- Request `GET /v1/user/lookup` in a browser session as a non-admin and confirm no email or role appears in the
|
||||||
|
network response.
|
||||||
@@ -53,12 +53,14 @@ Feature: Password and code hashing go through a domain Hasher interface
|
|||||||
Then the result is the error user.ErrInvalidCredentials
|
Then the result is the error user.ErrInvalidCredentials
|
||||||
And errors.Is(err, user.ErrInvalidCredentials) is true
|
And errors.Is(err, user.ErrInvalidCredentials) is true
|
||||||
|
|
||||||
Scenario: Authenticating an unknown username never calls the hasher
|
Scenario: Authenticating an unknown username spends the same hashing work as a wrong password
|
||||||
Given a user repository with no user "bob"
|
Given a user repository with no user "bob"
|
||||||
When AuthenticateUserUseCase.Authenticate is called with username "bob" and password
|
When AuthenticateUserUseCase.Authenticate is called twice with username "bob" and password
|
||||||
"hunter2example"
|
"hunter2example"
|
||||||
Then the result is the error user.ErrUserNotFound
|
Then each result is the error user.ErrUserNotFound
|
||||||
And the hasher's Compare is never called
|
And the hasher's Compare is called once per attempt, against a decoy hash of a random value
|
||||||
|
that no password can match, so response time does not reveal whether a username exists
|
||||||
|
And the decoy is hashed once and reused for every later unknown username
|
||||||
|
|
||||||
Scenario Outline: Login over HTTP still can't distinguish a bad password from an unknown username
|
Scenario Outline: Login over HTTP still can't distinguish a bad password from an unknown username
|
||||||
Given a user repository containing a user "alice" with stored password "hashed:hunter2example"
|
Given a user repository containing a user "alice" with stored password "hashed:hunter2example"
|
||||||
|
|||||||
@@ -29,9 +29,10 @@ Package: `test` (black-box, alongside the existing `article_test.go` / `user_tes
|
|||||||
assert the returned user matches and `err` is `nil`.
|
assert the returned user matches and `err` is `nil`.
|
||||||
- `Authenticate("alice", "wrongpassword12")` with `fakeHasher.Compare` returning an error
|
- `Authenticate("alice", "wrongpassword12")` with `fakeHasher.Compare` returning an error
|
||||||
→ assert `errors.Is(err, user.ErrInvalidCredentials)` is `true`.
|
→ assert `errors.Is(err, user.ErrInvalidCredentials)` is `true`.
|
||||||
- `Authenticate("bob", "hunter2example")` with no "bob" in the repo → assert
|
- `Authenticate("bob", "hunter2example")` twice with no "bob" in the repo → assert
|
||||||
`errors.Is(err, user.ErrUserNotFound)` is `true` and `fakeHasher`'s `Compare` was never
|
`errors.Is(err, user.ErrUserNotFound)` is `true` each time, that `fakeHasher`'s `Compare`
|
||||||
invoked (record a `compareCalled` flag).
|
ran once per attempt (against the decoy hash), and that `Hash` ran exactly once overall
|
||||||
|
(the decoy is computed lazily and reused).
|
||||||
|
|
||||||
## HTTP checks (real BcryptHasher, in-memory fake repo, mirroring api/router.go)
|
## HTTP checks (real BcryptHasher, in-memory fake repo, mirroring api/router.go)
|
||||||
8. Call `validator.InitValidator()`.
|
8. Call `validator.InitValidator()`.
|
||||||
|
|||||||
@@ -16,7 +16,8 @@ Feature: Login and password-reset requests are rate-limited per client IP
|
|||||||
(github.com/go-chi/chi/v5/middleware) runs first and rewrites r.RemoteAddr from
|
(github.com/go-chi/chi/v5/middleware) runs first and rewrites r.RemoteAddr from
|
||||||
X-Forwarded-For/X-Real-IP when present (matching the nginx reverse proxy setup in
|
X-Forwarded-For/X-Real-IP when present (matching the nginx reverse proxy setup in
|
||||||
docs/deployment.md that already sets X-Forwarded-For), falling back to the raw RemoteAddr
|
docs/deployment.md that already sets X-Forwarded-For), falling back to the raw RemoteAddr
|
||||||
otherwise; RateLimiter keys its counters on r.RemoteAddr
|
otherwise; RateLimiter keys its counters on the host portion of r.RemoteAddr (the source
|
||||||
|
port is ignored, so opening a new connection never yields a fresh counter)
|
||||||
And RateLimiter(maxAttempts int, window time.Duration) func(http.Handler) http.Handler keeps
|
And RateLimiter(maxAttempts int, window time.Duration) func(http.Handler) http.Handler keeps
|
||||||
an in-memory, mutex-guarded fixed-window counter per (route, client IP) pair: the first
|
an in-memory, mutex-guarded fixed-window counter per (route, client IP) pair: the first
|
||||||
request from a client opens a window starting now; each subsequent request from the same
|
request from a client opens a window starting now; each subsequent request from the same
|
||||||
|
|||||||
@@ -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
|
||||||
@@ -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.
|
||||||
@@ -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
|
||||||
@@ -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.
|
||||||
@@ -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
|
||||||
@@ -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.
|
||||||
@@ -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)
|
||||||
|
|||||||
@@ -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.
|
||||||
|
|
||||||
|
|||||||
@@ -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
|
||||||
@@ -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.
|
||||||
@@ -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
|
||||||
|
|
||||||
|
|||||||
@@ -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`.
|
||||||
|
|||||||
@@ -26,8 +26,9 @@ Feature: Pending registration screen
|
|||||||
you'll log in there first. Can't find it? Check your spam folder. If the link has expired,
|
you'll log in there first. Can't find it? Check your spam folder. If the link has expired,
|
||||||
cancel your registration and start again.") is rendered through ResultPanel's default slot
|
cancel your registration and start again.") is rendered through ResultPanel's default slot
|
||||||
as a second paragraph below the description, per components.md's "Slot default for extras"
|
as a second paragraph below the description, per components.md's "Slot default for extras"
|
||||||
And "Log out" calls POST /v1/auth/logout, which per loginHandler.Logout always responds 200 and
|
And "Log out" calls POST /v1/auth/logout, which per loginHandler.Logout clears the jwt cookie
|
||||||
clears the jwt cookie; on its response, PendingPage calls session.clear() and navigates to
|
and responds 200 (500 only when the session cannot be revoked server-side; the cookie is
|
||||||
|
cleared either way); on its response, PendingPage calls session.clear() and navigates to
|
||||||
/login, disabling both actions while the call is in flight
|
/login, disabling both actions while the call is in flight
|
||||||
And "Cancel registration" opens ConfirmDialog (built by this slice; components.md documents it
|
And "Cancel registration" opens ConfirmDialog (built by this slice; components.md documents it
|
||||||
but no file exists yet) via useOverlay().create(ConfirmDialog).open(), with title "Cancel
|
but no file exists yet) via useOverlay().create(ConfirmDialog).open(), with title "Cancel
|
||||||
|
|||||||
@@ -0,0 +1,516 @@
|
|||||||
|
Feature: Create a custom content type in the Schema builder
|
||||||
|
As an owner or admin
|
||||||
|
I want to define a new content type (name, key and ordered fields) on /schema/new
|
||||||
|
So that users can write entries of that type
|
||||||
|
|
||||||
|
Background:
|
||||||
|
Given the SPA calls the API with relative URLs under /v1 and the "jwt" HttpOnly cookie
|
||||||
|
And API errors are plain text
|
||||||
|
And POST /v1/content-type takes {key, name, fields[{key, label, type, required, unique, default, min, max, options}]}
|
||||||
|
And the builder never sends an "icon" key
|
||||||
|
And POST answers 201 with the content type, 400 invalid_content_type_key, 409 content_type_key_taken, 422 invalid_field, 403 or 500
|
||||||
|
And the route /schema/new is declared before /schema/:key, has meta auth "verified" and title "Schema", and renders the builder
|
||||||
|
And a route meta flag, not a path pattern, tells the shell that /schema/new needs the custom list only
|
||||||
|
And only owners and admins can use Schema; the SPA decides from the session role, the API still enforces it
|
||||||
|
And the six field types are text "Text", richtext "Rich text", number "Number", boolean "Yes or no", date "Date" and select "Choice"
|
||||||
|
And the limits are a type name of up to 100 characters, a type key of 2 to 40, 1 to 50 fields, a field key of up to 40 characters and 1 to 50 choices
|
||||||
|
And the layout is: Name and Key with the status chip, Discard and Save on top; the FieldList on the left; the FieldInspector on the right; the ApiPreview at the bottom
|
||||||
|
And below 48rem the FieldList is the page, the FieldInspector is a 92% bottom sheet closed with "Done", the ApiPreview is a bottom sheet, and Discard and Save sit in a bottom bar
|
||||||
|
And every string goes through t() and has a French entry in i18n/messages.ts
|
||||||
|
And a copy tagged "(proposed copy)" is not in the design and is the coder's single point of change
|
||||||
|
|
||||||
|
Scenario: Reaching the builder
|
||||||
|
Given the Schema list is Populated or Empty
|
||||||
|
When the user activates "New content type" (header button, empty-state button or the mobile floating button)
|
||||||
|
Then the router navigates to /schema/new
|
||||||
|
And the builder is shown, not the "Content type not found" page
|
||||||
|
And /schema/events and /schema/unknown still show "Content type not found" for a key that is not built-in
|
||||||
|
|
||||||
|
Scenario: Roles and sessions
|
||||||
|
Given <who> opens /schema/new
|
||||||
|
Then <result>
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| who | result |
|
||||||
|
| a verified owner or admin | the builder |
|
||||||
|
| a verified user who is neither | "You don't have access to Schema" with "Go to Home", URL unchanged |
|
||||||
|
| an unverified user | the redirect to /register/pending |
|
||||||
|
| a signed-out visitor | the redirect to /login |
|
||||||
|
|
||||||
|
Scenario: The builder needs no built-in list
|
||||||
|
Given an owner opens /schema/new as the first page of the session
|
||||||
|
Then GET /v1/content-type is called once for the sidebar
|
||||||
|
And GET /v1/builtin-type is never called
|
||||||
|
And the builder is shown as soon as the session is ready, with no skeleton
|
||||||
|
|
||||||
|
Scenario: New type, desktop (design state 1)
|
||||||
|
Given an owner opens /schema/new on a 1440 px viewport
|
||||||
|
Then the breadcrumb is "Schema" (a link to /schema) then "New content type"
|
||||||
|
And "Name" is an empty text input with the placeholder "For example, Events", marked required, with maxlength 100
|
||||||
|
And "Key" is a read-only mono input with the placeholder "events" and the help "Used in URLs and the API. Lowercase letters, digits and hyphens. It can't change after you save."
|
||||||
|
And the list header reads "Fields" and "1 of 50"
|
||||||
|
And one row is shown with the label "Title" and the key "title" in mono, selected, with the badge "New"
|
||||||
|
And "Add field" is shown under the list
|
||||||
|
And the inspector title is "Field: Title" with the badge "New"
|
||||||
|
And "Label" holds "Title"
|
||||||
|
And "Key" holds "title" with the Auto badge and the help "The name used in the API. Starts with a letter. Lowercase letters, digits and underscores."
|
||||||
|
And the type tiles show Text selected
|
||||||
|
And "Required" is off with "An entry can't be saved with this field empty."
|
||||||
|
And "Unique values" is off
|
||||||
|
And "Default value" is empty with "Used when an entry is created and this field is left out."
|
||||||
|
And "Shortest" and "Longest" are empty with "Counted in characters. Entries show a counter."
|
||||||
|
And "Save" and "Discard" are disabled
|
||||||
|
And no status chip is shown
|
||||||
|
And no "entries use this content type" bar is shown
|
||||||
|
And the API preview bar is collapsed
|
||||||
|
|
||||||
|
Scenario: New type, mobile (design state 1)
|
||||||
|
Given the same page on a 390 px viewport
|
||||||
|
Then the topbar shows an arrow-left and the title "New content type"
|
||||||
|
And Name and Key are stacked above the list, then the rows, then the "API preview" row with a chevron
|
||||||
|
And no inspector is shown until a row is activated
|
||||||
|
And the bottom bar holds Discard and Save
|
||||||
|
|
||||||
|
Scenario Outline: The key follows the name until it is edited
|
||||||
|
Given an empty new type
|
||||||
|
When the user types the name "<name>"
|
||||||
|
Then the Key holds "<key>" with the Auto badge, read-only
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| name | key |
|
||||||
|
| Events | events |
|
||||||
|
| Press mentions | press-mentions |
|
||||||
|
| Café & Bar | cafe-bar |
|
||||||
|
| Job openings! | job-openings |
|
||||||
|
| 2026 Awards | 2026-awards |
|
||||||
|
| !!! | (empty, mode empty) |
|
||||||
|
| a name of 60 letters | the first 40 characters, without a trailing hyphen |
|
||||||
|
|
||||||
|
Scenario: Editing and resetting the key
|
||||||
|
Given the name "Events" and the Auto key "events"
|
||||||
|
When the user activates the pencil
|
||||||
|
Then the Key becomes editable, the Auto badge goes and "Reset to match the name" is shown
|
||||||
|
When the user types the key "agenda" then edits the name to "Events and talks"
|
||||||
|
Then the Key stays "agenda"
|
||||||
|
When the user activates "Reset to match the name"
|
||||||
|
Then the Key is "events-and-talks" with the Auto badge
|
||||||
|
|
||||||
|
Scenario Outline: Type-level rules (design states 6 and 14)
|
||||||
|
Given a new type with a valid field
|
||||||
|
When the user sets <input> to <value> and activates Save
|
||||||
|
Then <message> is shown under <input> with an alert icon
|
||||||
|
And POST /v1/content-type is not called
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| input | value | message |
|
||||||
|
| Name | (empty or spaces) | Give the content type a name. |
|
||||||
|
| Key | e | Use 2 to 40 lowercase letters, digits or hyphens. |
|
||||||
|
| Key | Events | Use 2 to 40 lowercase letters, digits or hyphens. |
|
||||||
|
| Key | my_type | Use 2 to 40 lowercase letters, digits or hyphens. |
|
||||||
|
| Key | -events | Use 2 to 40 lowercase letters, digits or hyphens. |
|
||||||
|
| Key | events--2 | Use 2 to 40 lowercase letters, digits or hyphens. |
|
||||||
|
| Key | new | The key "new" is reserved. Choose a different key. (proposed copy) |
|
||||||
|
|
||||||
|
Scenario Outline: Accepted type keys
|
||||||
|
Given a new type with a valid field and the name "X"
|
||||||
|
When the user types the key "<key>" and activates Save
|
||||||
|
Then POST /v1/content-type is called with that key
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| key |
|
||||||
|
| ab |
|
||||||
|
| press-mentions |
|
||||||
|
| 2026-awards |
|
||||||
|
| 40 lowercase letters |
|
||||||
|
|
||||||
|
Scenario: Type-level errors together (design state 6)
|
||||||
|
Given a new type with no name, the key "e" and no field
|
||||||
|
When the user activates Save
|
||||||
|
Then "Give the content type a name.", "Use 2 to 40 lowercase letters, digits or hyphens." and "A content type needs at least one field." are shown
|
||||||
|
And the empty list shows "No fields yet" with the message in the error colour
|
||||||
|
And the chip reads "3 problems to fix"
|
||||||
|
And Save is disabled until all three are fixed, and Discard stays enabled
|
||||||
|
And the inspector shows "Field settings" and "Add a field, then choose its type and rules here."
|
||||||
|
|
||||||
|
Scenario: When errors are shown
|
||||||
|
Given a new type whose name is empty
|
||||||
|
Then no error is shown while nothing was edited
|
||||||
|
When the user edits an input, an error for that input shows as they type
|
||||||
|
And when the user activates Save, every error of the form shows at once
|
||||||
|
And errors are tied to their input with aria-describedby and aria-invalid
|
||||||
|
And a row with an error shows an alert icon, not only the red border
|
||||||
|
|
||||||
|
Scenario Outline: The status chip
|
||||||
|
Given <situation>
|
||||||
|
Then the chip reads "<chip>"
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| situation | chip |
|
||||||
|
| a pristine new type | (no chip) |
|
||||||
|
| an edit with no error | Unsaved changes |
|
||||||
|
| three inputs in error | 3 problems to fix |
|
||||||
|
| one input in error | 1 problem to fix |
|
||||||
|
| the POST in flight | Saving… |
|
||||||
|
| the POST failed with 500 | Save failed |
|
||||||
|
| navigator.onLine is false | Waiting for connection |
|
||||||
|
|
||||||
|
Scenario Outline: Counting problems
|
||||||
|
Given <errors>
|
||||||
|
Then the chip counts <count>
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| errors | count |
|
||||||
|
| no name, a one-letter key, no field | 3 |
|
||||||
|
| a field with no label, a field with min above max, a choice list with a blank and a duplicate | 3 |
|
||||||
|
| one choice list with a blank row and a duplicate row | 1 |
|
||||||
|
| one field with a bad key | 1 |
|
||||||
|
|
||||||
|
Scenario: Field list rows
|
||||||
|
Given a type with the fields Title, Starts on, Online
|
||||||
|
Then each row shows a grip button labelled "Move <label>", the icon box of its type, the label and the key in mono
|
||||||
|
And an unselected row shows its badges "New", "Required", "Unique" and an alert icon when in error
|
||||||
|
And the selected row is on the sand background and shows Move up, Move down and Remove
|
||||||
|
And a field without a label reads "Untitled field" and a field without a key reads "–"
|
||||||
|
|
||||||
|
Scenario: Adding a field
|
||||||
|
Given the list has 1 field
|
||||||
|
When the user activates "Add field"
|
||||||
|
Then a row is appended, selected, with a Text type and no label, and the label input is focused
|
||||||
|
And the header reads "2 of 50"
|
||||||
|
And at 50 fields "Add field" is disabled and the header reads "50 of 50"
|
||||||
|
|
||||||
|
Scenario Outline: Field key from the label
|
||||||
|
Given a new field is selected
|
||||||
|
When the user types the label "<label>"
|
||||||
|
Then its Key holds "<key>" with the Auto badge
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| label | key |
|
||||||
|
| Title | title |
|
||||||
|
| Starts on | starts_on |
|
||||||
|
| Éléments | elements |
|
||||||
|
| Ends on (date) | ends_on_date |
|
||||||
|
| 2nd room | nd_room |
|
||||||
|
| Title (when "title" exists)| title_2 |
|
||||||
|
| a label of 60 letters | the first 40 characters |
|
||||||
|
|
||||||
|
Scenario Outline: Field key rules (design state 7)
|
||||||
|
Given a new field is selected with the Key in manual mode
|
||||||
|
When the user types the key "<key>"
|
||||||
|
Then <outcome>
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| key | outcome |
|
||||||
|
| Title | "Start with a letter. Use lowercase letters, digits and underscores." under Key |
|
||||||
|
| 1st | the same message |
|
||||||
|
| a-b | the same message |
|
||||||
|
| a b | the same message |
|
||||||
|
| (empty) | the same message |
|
||||||
|
| starts_on | no error |
|
||||||
|
| a | no error |
|
||||||
|
| a_40_characters | no error, and a 41st character cannot be typed |
|
||||||
|
|
||||||
|
Scenario: Duplicate field keys
|
||||||
|
Given two fields whose keys are both "title" in manual mode
|
||||||
|
Then "Another field already uses this key." (proposed copy) is shown under the Key of the second field
|
||||||
|
And the chip counts one problem for that field
|
||||||
|
|
||||||
|
Scenario: A single field key error (design state 7)
|
||||||
|
Given a new field with the key "start-date" and everything else valid
|
||||||
|
Then the Key shows the error with the alert icon and the chip reads "1 problem to fix"
|
||||||
|
And Save is disabled
|
||||||
|
|
||||||
|
Scenario Outline: The inspector follows the type
|
||||||
|
Given a new field of type "<type>"
|
||||||
|
Then the limits are labelled <limits>
|
||||||
|
And "Unique values" is <unique>
|
||||||
|
And the default control is <default>
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| type | limits | unique | default |
|
||||||
|
| text | "Shortest" and "Longest" with the suffix "characters" | available | a text input, placeholder "No default" |
|
||||||
|
| richtext | "Shortest" and "Longest" with the suffix "characters" | disabled with "Not available for rich text." | a textarea, placeholder "No default" |
|
||||||
|
| number | "Lowest value" and "Highest value" | available | a number input, placeholder "No default" |
|
||||||
|
| boolean | none; "Yes or no fields have no limits." | disabled with "Not available for yes or no fields." | the switch "On by default" with help "New entries start with this switch off when the field is left out." |
|
||||||
|
| date | "Earliest date" and "Latest date" | available | a date input, placeholder "No default" |
|
||||||
|
| select | none; "Limits come from the choices below." | available | a select of the choices, placeholder "None" |
|
||||||
|
|
||||||
|
Scenario: Type tiles
|
||||||
|
Given the inspector of a new field
|
||||||
|
Then six radio tiles are shown, each with its icon, name and description
|
||||||
|
| tile | icon | description |
|
||||||
|
| Text | type | Short text, like a title or a name |
|
||||||
|
| Rich text | pilcrow | Long text with formatting, written in Markdown|
|
||||||
|
| Number | hash | Whole or decimal numbers |
|
||||||
|
| Yes or no | toggle-left | An on or off switch |
|
||||||
|
| Date | calendar | A calendar day, without a time |
|
||||||
|
| Choice | list | One option from a list you define |
|
||||||
|
And the selected tile is on the sand background
|
||||||
|
And the help under "Longest" reads "Counted in characters. Entries show a counter." for Text and Rich text, and "Entries outside the range are refused." for Number and Date
|
||||||
|
|
||||||
|
Scenario: Changing the type of a new field
|
||||||
|
Given a Number field with min 1, max 5000, default 20 and unique on
|
||||||
|
When the user picks the tile "Yes or no"
|
||||||
|
Then the label, the key and Required are kept
|
||||||
|
And min, max, default, options and unique are reset
|
||||||
|
When the user picks "Choice"
|
||||||
|
Then the choice list editor is shown with no choice
|
||||||
|
|
||||||
|
Scenario Outline: Field rules
|
||||||
|
Given a new field of type "<type>" with <settings>
|
||||||
|
Then <message> is shown under <where>
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| type | settings | message | where |
|
||||||
|
| text | an empty label or spaces | Give the field a label. | Label |
|
||||||
|
| number | min 6000, max 5000 | Lowest value can't be above the highest value. | the limits |
|
||||||
|
| text | min 10, max 3 | Shortest can't be longer than longest. (proposed copy) | the limits |
|
||||||
|
| date | min 2027-12-31, max 2026-01-01 | Earliest date can't be after the latest date. (proposed copy) | the limits |
|
||||||
|
| text | min 2.5 | Use a whole number, 0 or more. (proposed copy) | the limit |
|
||||||
|
| text | min -1 | Use a whole number, 0 or more. (proposed copy) | the limit |
|
||||||
|
| number | min 1, max 5000, default 0 | The default value is outside the limits. (proposed copy) | Default value |
|
||||||
|
| text | max 3, default "abcd" | The default value is outside the limits. (proposed copy) | Default value |
|
||||||
|
| select | no choice | Add at least one choice. (proposed copy) | the choice list|
|
||||||
|
| select | a blank choice | Choices can't be blank. | that row |
|
||||||
|
| select | "Talk" twice | Two choices are the same. | the second row |
|
||||||
|
| number | min 1, max 5000 | no error | - |
|
||||||
|
| number | min 5, max 5 | no error | - |
|
||||||
|
| text | min 0 | no error | - |
|
||||||
|
|
||||||
|
Scenario: Unique and default
|
||||||
|
Given a Text field with the default "Draft"
|
||||||
|
When the user turns "Unique values" on
|
||||||
|
Then the Default value input is disabled with "A field with unique values can't have a default."
|
||||||
|
And the default is not sent
|
||||||
|
When the user turns "Unique values" off
|
||||||
|
Then the default "Draft" is back
|
||||||
|
|
||||||
|
Scenario: Choice list editor (design state 8)
|
||||||
|
Given a Choice field with the choices Talk, Workshop, Meetup
|
||||||
|
Then "Choices" is shown with the required marker and "3 of 50"
|
||||||
|
And each choice is a row with a grip, a text input, Remove, and the placeholder "Choice"
|
||||||
|
And an input "Add a choice" with the button "Add" is shown
|
||||||
|
And the help reads "Add 1 to 50 choices. Each one needs a different name. Removing a choice that entries use will be refused when you save."
|
||||||
|
When the user types "Panel" in "Add a choice" and activates Add (or presses Enter)
|
||||||
|
Then the choice is appended and the input is emptied and keeps the focus
|
||||||
|
And the Default value select lists the choices
|
||||||
|
When the selected default choice is removed or renamed
|
||||||
|
Then the default is cleared
|
||||||
|
|
||||||
|
Scenario: Choice list limits and errors
|
||||||
|
Given a Choice field with 5 choices, the fourth blank and the fifth equal to the first
|
||||||
|
Then "Choices can't be blank." is shown under the fourth row and "Two choices are the same." under the fifth, each with an alert icon
|
||||||
|
And the field counts as one problem
|
||||||
|
And at 50 choices the Add button is disabled
|
||||||
|
And choices are compared after trimming, case-sensitively
|
||||||
|
|
||||||
|
Scenario: Reordering choices
|
||||||
|
Given a Choice field with 3 choices
|
||||||
|
When the user uses the grip of the second choice
|
||||||
|
Then Move up and Move down work as for fields, with the same live region ("Moving Workshop. Position 2 of 3. ...")
|
||||||
|
|
||||||
|
Scenario: Removing a field
|
||||||
|
Given a list with 3 fields
|
||||||
|
When the user activates Remove on the selected one
|
||||||
|
Then it disappears with no undo row (an undo row only exists for saved fields, slice 4)
|
||||||
|
And the next row is selected, or the previous one at the end, or none if the list is empty
|
||||||
|
And the header counts one less
|
||||||
|
|
||||||
|
Scenario Outline: Moving fields with the buttons
|
||||||
|
Given a list Title, Starts on, Ends on with <selected> selected
|
||||||
|
When the user activates <button>
|
||||||
|
Then the order becomes <order>
|
||||||
|
And the selected row stays selected and keeps the focus on the same button when possible
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| selected | button | order |
|
||||||
|
| Starts on | Move up | Starts on, Title, Ends on |
|
||||||
|
| Starts on | Move down | Title, Ends on, Starts on |
|
||||||
|
|
||||||
|
Scenario Outline: Disabled ends
|
||||||
|
Given a list of 3 fields with <row> selected
|
||||||
|
Then <button> is disabled
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| row | button |
|
||||||
|
| Title | Move up |
|
||||||
|
| Ends on | Move down |
|
||||||
|
|
||||||
|
Scenario: Keyboard reorder (design state 9)
|
||||||
|
Given the list Title, Starts on, Ends on
|
||||||
|
When the user focuses the grip "Move Starts on" and presses Space
|
||||||
|
Then the row is picked up with the primary outline
|
||||||
|
And the polite live region reads "Moving Starts on. Position 2 of 3. Press Up or Down to move, Space to drop, Esc to cancel."
|
||||||
|
When the user presses Up
|
||||||
|
Then the row is first and the live region reads "Moving Starts on. Position 1 of 3. ..."
|
||||||
|
When the user presses Space
|
||||||
|
Then the new order is kept and the live region announces the drop
|
||||||
|
When the user picks it up again, moves it and presses Esc
|
||||||
|
Then the order returns to what it was before the pick-up
|
||||||
|
|
||||||
|
Scenario: No pointer drag in this slice
|
||||||
|
Then rows cannot be dragged with the pointer
|
||||||
|
|
||||||
|
Scenario: Selecting a field on mobile
|
||||||
|
Given a 390 px viewport
|
||||||
|
When the user activates a row
|
||||||
|
Then a bottom sheet titled "Field: <label>" opens with the inspector, Move up, Move down and Remove (proposed placement), and a "Done" button
|
||||||
|
And focus moves to the sheet title
|
||||||
|
When the user activates Done
|
||||||
|
Then the sheet closes and the focus returns to the row
|
||||||
|
|
||||||
|
Scenario: API preview (design state 10)
|
||||||
|
Given the type key "events" and the fields Title, Starts on, Online, Capacity, Category
|
||||||
|
When the user opens "API preview"
|
||||||
|
Then the panel shows "Where entries of this type live" with these five routes
|
||||||
|
| GET | /v1/content-type/events/entry |
|
||||||
|
| POST | /v1/content-type/events/entry |
|
||||||
|
| GET | /v1/content-type/events/entry/{id} |
|
||||||
|
| PUT | /v1/content-type/events/entry/{id} |
|
||||||
|
| DELETE | /v1/content-type/events/entry/{id} |
|
||||||
|
And "A sample entry. Values come from each field's type and default." with the JSON of a sample entry
|
||||||
|
And "Updates as you edit. Fields you add or remove here appear after you save."
|
||||||
|
And the collapsed bar shows "API preview", "GET /v1/content-type/events/entry" in mono and "Copy JSON"
|
||||||
|
And the key falls back to "events" while the Key is empty
|
||||||
|
|
||||||
|
Scenario Outline: Sample values in the preview
|
||||||
|
Given a field "f" of type "<type>" with <settings>
|
||||||
|
Then the sample entry data holds <value> for "f"
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| type | settings | value |
|
||||||
|
| text | no default | "Example text" |
|
||||||
|
| text | default "Draft" | "Draft" |
|
||||||
|
| richtext | no default | "Markdown text" |
|
||||||
|
| number | no default, no min | 0 |
|
||||||
|
| number | min 1 | 1 |
|
||||||
|
| number | min 1, default 20 | 20 |
|
||||||
|
| boolean | no default | false |
|
||||||
|
| boolean | on by default | true |
|
||||||
|
| date | no default | "2026-11-21" |
|
||||||
|
| select | choices Talk, Workshop | "Talk" |
|
||||||
|
| select | default "Workshop" | "Workshop" |
|
||||||
|
| select | no choice yet | null |
|
||||||
|
|
||||||
|
Scenario: The sample entry envelope and live updates
|
||||||
|
Then the sample is {"id": 42, "content_type": <key>, "data": {...}, "created_by": 3, "updated_by": 3, "created_at": "2026-10-15T11:02:00Z", "updated_at": "2026-10-15T11:02:00Z"} indented by 2 spaces
|
||||||
|
And the data keys follow the field order and skip fields without a valid key
|
||||||
|
And it updates on every edit, reorder and removal
|
||||||
|
And it contains no date from the clock
|
||||||
|
|
||||||
|
Scenario: Copy JSON
|
||||||
|
When the user activates "Copy JSON"
|
||||||
|
Then the sample entry JSON is written to the clipboard
|
||||||
|
And the button reads "Copied" for 2 seconds, then "Copy JSON" again
|
||||||
|
And the same happens in the mobile sheet
|
||||||
|
|
||||||
|
Scenario: API preview on mobile
|
||||||
|
Given a 390 px viewport
|
||||||
|
When the user activates the row "API preview"
|
||||||
|
Then a bottom sheet titled "API preview" shows "GET /v1/content-type/events/entry", the JSON and a full-width "Copy JSON" button
|
||||||
|
|
||||||
|
Scenario: Saving a valid type
|
||||||
|
Given the name "Events", the key "events" and these fields
|
||||||
|
| label | key | type | required | unique | default | min | max | options |
|
||||||
|
| Title | title | text | true | true | | | 80 | |
|
||||||
|
| Starts on | starts_on | date | true | false | | 2026-01-01 | 2027-12-31 | |
|
||||||
|
| Online | online | boolean | false | false | on | | | |
|
||||||
|
| Capacity | capacity | number | false | false | 20 | 1 | 5000 | |
|
||||||
|
| Category | category | select | false | false | Talk | | | Talk, Workshop, Meetup |
|
||||||
|
| Description | description | richtext | false | false | | | 5000 | |
|
||||||
|
When the user activates Save
|
||||||
|
Then POST /v1/content-type is called once with the key "events", the name "Events" and the fields in list order
|
||||||
|
And each field carries exactly key, label, type, required, unique, default, min, max, options
|
||||||
|
And unset default, min and max are null, and options are [] for a non-select field
|
||||||
|
And the boolean default is true, an off switch sends null, a date bound is "YYYY-MM-DD", the name is trimmed, choices are trimmed
|
||||||
|
And the body has no "icon" key
|
||||||
|
|
||||||
|
Scenario: Saving (design state 11, create)
|
||||||
|
Given the POST has not answered
|
||||||
|
Then the chip reads "Saving…" with a loader, Save shows a loader and is disabled, Discard is disabled
|
||||||
|
And Name, Key and the inspector are dimmed and not editable
|
||||||
|
And Add field, the grips, the Move and Remove buttons are disabled
|
||||||
|
And a second activation of Save sends no second request
|
||||||
|
|
||||||
|
Scenario: Saved (design state 12, create)
|
||||||
|
Given the POST answers 201 with the content type "events" named "Events" and 6 fields
|
||||||
|
Then a success toast "Content type saved" with "Events now has 6 fields." is shown
|
||||||
|
And the content types store holds "events" in name order when its list was loaded
|
||||||
|
And the sidebar Content group lists "Events"
|
||||||
|
And the router replaces the URL with /schema, where the Events row is listed
|
||||||
|
And no "Leave without saving?" prompt is shown
|
||||||
|
And with one field the toast reads "Events now has 1 field." (proposed copy)
|
||||||
|
|
||||||
|
Scenario: Key already taken (design state 14)
|
||||||
|
Given the name "Events", the key "events" and the fields Title (required) and Starts on (date)
|
||||||
|
When the POST answers 409 with the body "content_type_key_taken"
|
||||||
|
Then under Key: The key "events" is already used by another content type. Choose a different key.
|
||||||
|
And the Key is editable (manual mode), has the error and the focus, and the Auto badge is hidden
|
||||||
|
And the chip reads "1 problem to fix" and Save is disabled
|
||||||
|
And the fields and the name are untouched
|
||||||
|
When the user edits the key
|
||||||
|
Then the error goes and Save is enabled
|
||||||
|
|
||||||
|
Scenario: The server refuses a key or a field
|
||||||
|
Given the POST answers <status> with <body>
|
||||||
|
Then <outcome>
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| status | body | outcome |
|
||||||
|
| 400 | invalid_content_type_key | the key message under Key, as in the rules above |
|
||||||
|
| 422 | invalid_field | the banner "Check the fields marked in the list." (proposed title and placement), edits kept |
|
||||||
|
| 403 | Only ... | the page "You don't have access to Schema" |
|
||||||
|
| 401 | (any) | the existing redirect to /login with the expired reason |
|
||||||
|
|
||||||
|
Scenario Outline: Save failed (design state 13)
|
||||||
|
Given the POST <failure>
|
||||||
|
Then an error alert titled "Couldn't save the content type" shows "Something went wrong on our side. Your changes are still here. Try again in a moment."
|
||||||
|
And it has a "Try again" action and the chip reads "Save failed"
|
||||||
|
And every edit is kept and Save stays enabled
|
||||||
|
When the user activates "Try again"
|
||||||
|
Then the same body is sent again
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| failure |
|
||||||
|
| answers 500 |
|
||||||
|
| fails (network) |
|
||||||
|
|
||||||
|
Scenario: Offline (design state 16)
|
||||||
|
Given the user has edited the form and navigator.onLine becomes false
|
||||||
|
Then the banner "You're offline. Changes will be saved when you reconnect." with a wifi-off icon is shown
|
||||||
|
And the chip reads "Waiting for connection"
|
||||||
|
And Save is disabled and every edit is kept
|
||||||
|
When the connection returns
|
||||||
|
Then the banner goes, Save is enabled again and nothing is sent by itself
|
||||||
|
|
||||||
|
Scenario: Discard
|
||||||
|
Given the user has edited the form
|
||||||
|
When the user activates Discard
|
||||||
|
Then Name and Key are empty, the list holds the starter field Title, errors and the chip are cleared
|
||||||
|
And nothing is sent and the URL stays /schema/new
|
||||||
|
And Discard and Save are disabled again
|
||||||
|
|
||||||
|
Scenario Outline: Leaving with unsaved edits
|
||||||
|
Given <state>
|
||||||
|
When the user leaves through the breadcrumb, the mobile arrow, the sidebar or the browser back
|
||||||
|
Then <result>
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| state | result |
|
||||||
|
| a pristine form | the router navigates with no prompt |
|
||||||
|
| an edited name, key or field | the dialog "Leave without saving?" with "Keep editing" and "Discard changes" is shown |
|
||||||
|
| after Save answered 201 | the router navigates with no prompt |
|
||||||
|
|
||||||
|
Scenario: Keep editing or discard on leave
|
||||||
|
Given the leave dialog is open
|
||||||
|
When the user chooses "Keep editing" (or dismisses the dialog)
|
||||||
|
Then the user stays on /schema/new with every edit
|
||||||
|
When the user chooses "Discard changes"
|
||||||
|
Then the router navigates away
|
||||||
|
|
||||||
|
Scenario: Accessibility of the builder
|
||||||
|
Then every control has a visible label
|
||||||
|
And the type tiles are a radio group
|
||||||
|
And the field list is one tab stop and arrow keys move between rows
|
||||||
|
And controls are 44 px high on mobile
|
||||||
|
And focus is a 2 px ring in the primary colour
|
||||||
@@ -0,0 +1,82 @@
|
|||||||
|
# QA: Schema builder, create flow (SPA slice 3)
|
||||||
|
|
||||||
|
Runner: Vitest + Vue Test Utils (`task test:web`). No Go test: the POST /v1/content-type contract is already covered by features/custom_content_types.qa.md and nothing changes in the backend.
|
||||||
|
Same pattern as features/schema_builtin_view.qa.md: mock `/v1` through the api composable (extend `views/__tests__/schemaTestKit.ts` with a POST handler and a configurable responder), mount with the real router and a resolved session whose role varies, use `components/__tests__/viewport.ts` for desktop (1440) and mobile (390), fake timers for the 2 s "Copied" and any delay. Never freeze the system date. Tests that touch the clipboard stub `navigator.clipboard.writeText`. Online/offline is driven by dispatching the window `offline` and `online` events.
|
||||||
|
|
||||||
|
## Automated
|
||||||
|
|
||||||
|
Fixtures: the three custom types and five built-in types of schemaTestKit; the "Events" form of the feature (6 fields) as the full-save case; a 201 response for it with id 4 and updated_at; the plain-text bodies `content_type_key_taken`, `invalid_content_type_key`, `invalid_field`.
|
||||||
|
|
||||||
|
Pure logic (suggested files lib/__tests__/schemaBuilder*.spec.ts; each rule table is an it.each over the feature's Examples):
|
||||||
|
1. Type key derivation: the 7 name rows; empty result keeps the key empty.
|
||||||
|
2. Field key derivation: the 7 label rows, including the `_2` suffix against an existing key and the 40-character cut.
|
||||||
|
3. Type validation: name, key (the 7 rejected rows, the 4 accepted rows including 40 characters), fields count 0 / 1 / 50 / 51, reserved key "new".
|
||||||
|
4. Field validation: label, key (8 rows), duplicate keys, limits ordering per type, whole non-negative limits for text, default against limits and length, choice rules (blank, duplicate after trim, none, 50 max), unique disabled for richtext and boolean, default dropped when unique. Assert each message string.
|
||||||
|
5. Problem counting: the 4 rows of the feature (per field and per type-level input, never per message).
|
||||||
|
6. Payload builder: the 6-field table gives the exact JSON, with null for unset values, [] options, boolean off to null, trimmed name and choices, ISO date bounds, no "icon", no unique default.
|
||||||
|
7. Sample entry: the 12 value rows, the envelope with fixed ids and timestamps, key fallback "events", field order, skipped invalid keys, 2-space indentation.
|
||||||
|
8. Type change reset (Number to Yes or no to Choice).
|
||||||
|
|
||||||
|
Store (extend stores/__tests__/contentTypes.spec.ts):
|
||||||
|
9. add(type) inserts by name order when status is "ready", does nothing when "idle" (the next load returns it), does not touch built-in items, and does not trigger a request.
|
||||||
|
|
||||||
|
Composable and API (extend composables/__tests__/useContentTypes.spec.ts):
|
||||||
|
10. createContentType posts JSON to /v1/content-type and returns the type; ApiError carries status and plain-text body for 400, 409, 422, 403, 500; NetworkError passes through.
|
||||||
|
|
||||||
|
Builder view (new views/__tests__/SchemaBuilderView.spec.ts and component specs for FieldList, FieldInspector, ChoiceList, ApiPreview), one test per feature scenario:
|
||||||
|
11. Reaching the builder from the list button, the empty-state button and the mobile floating button; /schema/events and /schema/unknown still show "Content type not found".
|
||||||
|
12. Roles: owner, admin, a role that is neither (403 page, no field shown), unverified and signed-out redirects (extend routerGuard.spec). Route registered before /schema/:key with the right meta, and GET /v1/builtin-type never called on /schema/new (assert the calls list).
|
||||||
|
13. State 1 desktop: breadcrumb, Name and Key copy, "1 of 50", starter row, inspector copy, Save and Discard disabled, no chip, collapsed API bar, no "entries use" bar.
|
||||||
|
14. State 1 mobile: topbar arrow-left and title, stacked Name and Key, "API preview" row, bottom bar, no inspector.
|
||||||
|
15. Auto key and manual key: pencil, Auto badge, reset, key stays after a name edit.
|
||||||
|
16. Type-level errors (it.each of the 7 rows) and state 6 together: the three messages, "No fields yet", "3 problems to fix", Save disabled then enabled after fixes, Discard enabled.
|
||||||
|
17. When errors appear: none on a pristine form; per input while typing; all on Save; aria-describedby and aria-invalid wiring; alert icon on a row in error.
|
||||||
|
18. Chip table (7 rows).
|
||||||
|
19. Field list: row content, badges, selected row buttons, "Untitled field" and "–".
|
||||||
|
20. Add field: appended, selected, label focused, counter, disabled at 50.
|
||||||
|
21. Inspector per type (it.each over 6 types): labels, unique state with its message, default control, help texts, tiles with icons and descriptions; type change reset.
|
||||||
|
22. Field rules (it.each over the Examples), unique and default interaction, key rules (state 7) and duplicate key.
|
||||||
|
23. Choice list: add by button and Enter with focus kept, remove, reorder, default cleared on remove or rename, blank and duplicate flags, 50 cap, counter.
|
||||||
|
24. Removing a field: selection moves, no undo row, empty list state.
|
||||||
|
25. Move buttons and disabled ends (it.each); keyboard reorder: Space, Up, Down, Space and Esc, live region text at each step, order restored on Esc. Assert no drag handler on rows.
|
||||||
|
26. Mobile sheets: row opens the field sheet with Done, focus to the title and back; API sheet with Copy JSON.
|
||||||
|
27. API preview: routes, texts, sample JSON live update, key fallback, collapsed bar, Copy JSON writes the exact JSON and shows "Copied" for 2 s (fake timers).
|
||||||
|
28. Save: the exact POST body, one request on double activation, the Saving state (dimmed, disabled controls, loader).
|
||||||
|
29. Success: toast copy including the singular, store.add, sidebar item, router.replace('/schema'), no leave prompt, the list shows the new row without a second GET /v1/content-type.
|
||||||
|
30. Key taken: 409 message, key editable with focus and no Auto badge, "1 problem to fix", Save disabled, enabled again after an edit.
|
||||||
|
31. Server refusals: 400 invalid_content_type_key, 422 invalid_field banner, 403 page, 401 redirect.
|
||||||
|
32. Save failed: 500 and network, banner copy, edits kept, "Try again" resends the same body.
|
||||||
|
33. Offline: banner copy, chip, Save disabled, edits kept, recovery without any request.
|
||||||
|
34. Discard resets to the blank form and sends nothing.
|
||||||
|
35. Leave guard: pristine, edited, after save; Keep editing, dismiss and Discard changes.
|
||||||
|
|
||||||
|
Existing tests to update:
|
||||||
|
36. features/schema_builtin_view.qa.md item 11 and SchemaTypeView.spec: remove /schema/new from the "Unknown key" it.each (it is now the builder).
|
||||||
|
37. French: every new string has a French entry (the existing i18n completeness spec must pass).
|
||||||
|
|
||||||
|
## Visual (task visual:check -- schema)
|
||||||
|
|
||||||
|
Run `task visual:check -- schema`; every capture within 10 % at desktop and mobile, light and dark. Nothing in the covered states is clock-sensitive. Mock GET /v1/auth/me (owner "Marta Alves") and GET /v1/content-type (the 3 custom types) with the sidebar mock of the existing Schema states, plus every other /v1 call the page makes. The shell and sidebar are the board's `AppFrame`; if the board marks the sidebar differently from the SPA, report it, do not fix it silently.
|
||||||
|
|
||||||
|
Setups to add in `web/visual/states.ts` (screen `schema`):
|
||||||
|
|
||||||
|
| Board state | Setup | Sample data (from the frame) |
|
||||||
|
|---|---|---|
|
||||||
|
| New type | open /schema/new, no steps | empty name and key (placeholders "For example, Events" and "events"), starter field Title/title, Text, optional |
|
||||||
|
| Type-level errors | open /schema/new; steps: edit the key and type "e", Remove the starter field, activate Save | empty name, key "e", no fields, chip "3 problems to fix" |
|
||||||
|
| Key already taken | open /schema/new; mock POST /v1/content-type as 409 with the body `content_type_key_taken`; steps: type the name "Events", turn Required on for Title, Add field with the label "Starts on" and the Date tile (key starts_on), select the first row, activate Save | name "Events", key "events", fields Title (required) and Starts on (date), the key error, chip "1 problem to fix" |
|
||||||
|
|
||||||
|
Known visual differences to report, never hide: the missing `...` button (D15), the absent chip in the pristine state (Q2), and the Key help copy (Q1) if the board text is kept.
|
||||||
|
|
||||||
|
`skip: 'pending'` (drawn on the Events edit screen, which exists in slice 4): Editing an existing type, Locked key: tooltip, Unsaved changes, Field errors, Choice list editor, Keyboard reorder, API preview open, Saving, Saved, Save failed, Schema incompatible, Offline. Field key error (state 7) has no board frame: Vitest only. If check.ts demands an entry for it, add a pending skip, and report it.
|
||||||
|
|
||||||
|
The "Review and delete" group is slice 4/5: every state stays pending.
|
||||||
|
|
||||||
|
## Manual
|
||||||
|
|
||||||
|
- Keyboard: Tab order is Name, Key (pencil), Save, Discard, field list (one stop, arrows move between rows), inspector top to bottom, API preview. Screen reader (NVDA or VoiceOver): the live region reads each reorder step; the tile group announces its selected tile; errors are read with their input.
|
||||||
|
- Focus ring on every control; hover and motion on rows, tiles, sheets and the Copy JSON button; sheet open and close focus return on a real phone.
|
||||||
|
- Clipboard: Copy JSON pastes the exact sample entry in a real browser (permission prompt behaviour).
|
||||||
|
- Real backend: as owner, then admin, create a type with all six field types including a Choice default and a unique Title. Check the type in `GET /v1/content-type`, in the sidebar Content group, and in the Schema list. Create the same key again for a real 409. Send an invalid body through curl to compare the 400 and 422 texts with the mapped messages.
|
||||||
|
- Real offline: switch the browser offline, edit, reconnect, press Save.
|
||||||
|
- Reload or close the tab with unsaved edits (not handled by the leave guard): note the browser behaviour.
|
||||||
@@ -0,0 +1,157 @@
|
|||||||
|
Feature: Delete a custom content type from the Schema builder
|
||||||
|
As an owner or admin
|
||||||
|
I want to delete a custom type that has no entries
|
||||||
|
So that unused types leave the schema, the API and the sidebar
|
||||||
|
|
||||||
|
Background:
|
||||||
|
Given the SPA calls the API with relative URLs under /v1 and the "jwt" HttpOnly cookie
|
||||||
|
And API errors are plain text
|
||||||
|
And the edit builder, its store, entry count, leave guard, chip and banners of features/schema_builder_edit.feature are reused unchanged unless a scenario below says otherwise
|
||||||
|
And DELETE /v1/content-type/{key} answers 204 with no body
|
||||||
|
And DELETE answers 404 content_type_not_found, 409 content_type_has_entries, 403 or 500
|
||||||
|
And the number of entries is the "total" already loaded from GET /v1/content-type/{key}/entry?page=1&size=5; no other request is made to open a dialog
|
||||||
|
And the dialogs are DeleteTypeDialog (UModal + UAlert, color "error" on the destructive action; a bottom sheet on mobile) from docs/design/screens/schema.md group "3 Review and delete", states 5 to 7
|
||||||
|
And every string goes through t() and has a French entry in i18n/messages.ts
|
||||||
|
And a copy tagged "(proposed copy)" is not in the design and is the coder's single point of change
|
||||||
|
|
||||||
|
Scenario: The overflow menu (proposed placement, see open question 1)
|
||||||
|
Given an owner opens /schema/recipes
|
||||||
|
Then the top bar holds an icon button "More actions" (proposed copy) with the ellipsis icon, after Discard and Save on desktop and as the topbar action on mobile
|
||||||
|
When the user activates it
|
||||||
|
Then a menu opens with one item "Delete content type" with a trash-2 icon in the error colour
|
||||||
|
And Esc or a click outside closes it and returns focus to the button
|
||||||
|
|
||||||
|
Scenario Outline: Where the menu is available
|
||||||
|
Given <page>
|
||||||
|
Then <result>
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| page | result |
|
||||||
|
| /schema/new | no overflow menu |
|
||||||
|
| /schema/articles (built-in, read-only) | no overflow menu and no delete |
|
||||||
|
| /schema/events (edit) | the overflow menu |
|
||||||
|
|
||||||
|
Scenario Outline: The menu is disabled while another action runs
|
||||||
|
Given /schema/recipes and <state>
|
||||||
|
Then the "More actions" button is disabled
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| state |
|
||||||
|
| the PUT is in flight (Saving, Applying) |
|
||||||
|
| a delete is in flight |
|
||||||
|
|
||||||
|
Scenario: Blocked, the type has entries (design group 3, state 5)
|
||||||
|
Given /schema/events has 37 entries
|
||||||
|
When the user chooses "Delete content type"
|
||||||
|
Then no request is sent
|
||||||
|
And the dialog "You can't delete Events yet" opens with "A content type can only be deleted when it has no entries."
|
||||||
|
And a warning alert reads "Events has 37 entries" with "Delete all of its entries first, then delete the content type."
|
||||||
|
And the actions are "Close" and "View entries"; there is no delete button
|
||||||
|
And the count is grouped like the info bar ("1,200 entries") and a single entry reads "Recipes has 1 entry" (proposed copy)
|
||||||
|
|
||||||
|
Scenario: View entries
|
||||||
|
Given the blocked dialog or the fallback dialog is open
|
||||||
|
When the user activates "View entries"
|
||||||
|
Then the dialog closes and the router navigates to /content/events (see open question 4)
|
||||||
|
|
||||||
|
Scenario: Close the blocked dialog
|
||||||
|
Given the blocked dialog is open
|
||||||
|
When the user chooses "Close", the close icon or presses Esc
|
||||||
|
Then the dialog closes, the page and every edit are unchanged and focus returns to the menu button
|
||||||
|
|
||||||
|
Scenario: Confirm, the type has no entries (design group 3, state 6)
|
||||||
|
Given /schema/recipes has 0 entries
|
||||||
|
When the user chooses "Delete content type"
|
||||||
|
Then no request is sent
|
||||||
|
And the dialog "Delete Recipes?" opens with "Recipes has no entries. Its fields and its API routes will be deleted. This can't be undone."
|
||||||
|
And the body reads "Key: " then "recipes" in mono
|
||||||
|
And the actions are "Cancel" and "Delete content type" (error colour)
|
||||||
|
And Cancel, the close icon and Esc close it with nothing sent and focus returned to the menu button
|
||||||
|
|
||||||
|
Scenario: Deleting (proposed, see open question 3)
|
||||||
|
Given the confirm dialog is open
|
||||||
|
When the user activates "Delete content type"
|
||||||
|
Then DELETE /v1/content-type/recipes is sent once
|
||||||
|
And the button reads "Deleting…" with a loader, Cancel is disabled
|
||||||
|
And Esc, the close icon and a click on the overlay do not dismiss the dialog
|
||||||
|
And a second activation sends nothing
|
||||||
|
|
||||||
|
Scenario: Deleted
|
||||||
|
Given DELETE answers 204
|
||||||
|
Then the dialog closes
|
||||||
|
And the content types store drops "recipes" (store.drop) with no GET /v1/content-type
|
||||||
|
And the router navigates to /schema with no "Leave without saving?" prompt
|
||||||
|
And a success toast "Content type deleted" with "Recipes was deleted." (proposed copy) is shown
|
||||||
|
And the Schema list no longer shows Recipes and the sidebar Content group no longer lists it
|
||||||
|
And no request to GET /v1/content-type/recipes/... is made afterwards
|
||||||
|
|
||||||
|
Scenario: Back or reload after a delete
|
||||||
|
Given Recipes was deleted
|
||||||
|
When the user opens /schema/recipes
|
||||||
|
Then the page "Content type not found" with "It may have been deleted, or the address may be mistyped." is shown
|
||||||
|
|
||||||
|
Scenario: Server fallback, entries appeared (design group 3, state 7)
|
||||||
|
Given the page loaded Recipes with 0 entries
|
||||||
|
When the user confirms and DELETE answers 409 content_type_has_entries
|
||||||
|
Then the dialog stays open with the title "Delete Recipes?" and the error alert "Recipes now has entries" with "Someone added an entry after this page loaded, so nothing was deleted. Delete the entries first, then try again."
|
||||||
|
And the actions are "Close" and "View entries"; there is no delete button
|
||||||
|
And the store still holds Recipes and the user stays on /schema/recipes
|
||||||
|
And "Close" closes the dialog; the loaded count is not refreshed, so choosing "Delete content type" again opens the confirm dialog (see open question 2)
|
||||||
|
|
||||||
|
Scenario Outline: Other answers of DELETE
|
||||||
|
Given the confirm dialog is open and DELETE <outcome>
|
||||||
|
Then <result>
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| outcome | result |
|
||||||
|
| answers 404 content_type_not_found | the dialog closes, the store drops the type and the page "Content type not found" is shown (proposed, see open question 5) |
|
||||||
|
| answers 403 "Only ..." | the dialog closes and the page "You don't have access to Schema" is shown |
|
||||||
|
| answers 401 | the existing redirect to /login with the expired reason |
|
||||||
|
| answers 500 or fails (network) | the dialog stays open with the error alert "Couldn't delete the content type" (proposed copy) and "Something went wrong on our side. Nothing was changed. Try again in a moment."; "Cancel" and "Delete content type" are enabled again and the store is untouched |
|
||||||
|
|
||||||
|
Scenario: Retry after a failure
|
||||||
|
Given the dialog shows the 500 alert
|
||||||
|
When the user activates "Delete content type"
|
||||||
|
Then the same DELETE is sent again and the alert clears while it is in flight
|
||||||
|
|
||||||
|
Scenario: Offline
|
||||||
|
Given the page is offline (the existing offline banner is shown)
|
||||||
|
When the confirm dialog is open
|
||||||
|
Then "Delete content type" is disabled and nothing is sent
|
||||||
|
And when the connection returns it is enabled again and nothing is sent by itself
|
||||||
|
|
||||||
|
Scenario Outline: Unsaved edits and the delete (the leave guard)
|
||||||
|
Given /schema/<key> with unsaved edits (chip "Unsaved changes")
|
||||||
|
When the user chooses "Delete content type"
|
||||||
|
Then the dialog is the one of the saved type's count, its copy never mentions the edits
|
||||||
|
And opening it does not discard, validate or save the edits
|
||||||
|
And <after>
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| key | after |
|
||||||
|
| recipes | on Cancel, Close, 409 and 500, the edits, the chip and the undo rows are exactly as they were |
|
||||||
|
| recipes | on 204 the router leaves with no "Leave without saving?" prompt and the edits are discarded with the page |
|
||||||
|
| events | the blocked dialog is shown for the saved count (37), and Close keeps every edit |
|
||||||
|
|
||||||
|
Scenario: Delete after a refused save
|
||||||
|
Given the banner "Nothing was changed" is shown for Recipes
|
||||||
|
When the user deletes the type with no entries
|
||||||
|
Then the delete flow is the same and the banner goes with the page
|
||||||
|
|
||||||
|
Scenario: Session and role
|
||||||
|
Given a user who is neither owner nor admin opens /schema/recipes
|
||||||
|
Then the page "You don't have access to Schema" is shown and no menu exists
|
||||||
|
And the API still answers 403 to DELETE for that user
|
||||||
|
|
||||||
|
Scenario: Accessibility of the delete flow
|
||||||
|
Then the menu button has an accessible name and the menu is keyboard operable
|
||||||
|
And dialogs trap focus, open with focus on the title and return it to "More actions" on close
|
||||||
|
And while Deleting, focus stays on the dialog title
|
||||||
|
And the destructive button is never the default focus (focus starts on Cancel or Close)
|
||||||
|
And controls are 44 px high on mobile and focus is a 2 px ring in the primary colour
|
||||||
|
|
||||||
|
Scenario: Key error on a new field in the edit builder (design state 7, visual only)
|
||||||
|
Given /schema/events and a field added with the label "Second date", type Date and the key "2nd-date"
|
||||||
|
Then the board shows 8 fields, that row selected with the badge "New", the Key "2nd-date" with "Start with a letter. Use lowercase letters, digits and underscores." and the alert icon, and the chip "1 problem to fix"
|
||||||
|
And Save is disabled
|
||||||
|
And behaviour is as in schema_builder_edit.feature "A single field key error on a new field"
|
||||||
@@ -0,0 +1,42 @@
|
|||||||
|
# QA: Schema builder, delete (SPA slice 5)
|
||||||
|
|
||||||
|
Runner: Vitest + Vue Test Utils (`task test:web`). No Go test: DELETE /v1/content-type/{key} is already covered by features/custom_content_types.qa.md and the backend does not change.
|
||||||
|
Same kit as features/schema_builder_edit.qa.md (`views/__tests__/schemaTestKit.ts`: add a DELETE handler per status, plain-text bodies content_type_has_entries and content_type_not_found; Events with total 37, Recipes with 4 fields and total 0). Never freeze the system date.
|
||||||
|
|
||||||
|
## Automated
|
||||||
|
|
||||||
|
1. Composable (useContentTypes.spec): `deleteContentType(key)` sends DELETE to /v1/content-type/{key}, resolves on 204 with no body parsing, ApiError carries status and plain text for 404, 409, 403, 500; NetworkError passes through.
|
||||||
|
2. Store: `remove(key)` drops the custom type, keeps order of the rest, never touches built-ins, makes no request, does nothing for an unknown key. reset() unchanged.
|
||||||
|
3. Menu: shown in edit mode only (not /schema/new, not built-in view, not for a non-owner/admin); one item "Delete content type"; Esc closes and returns focus; disabled while Saving, Applying and Deleting.
|
||||||
|
4. Blocked (total 37): no request; copy, warning alert, "Close" and "View entries", no delete button; singular and 1,200 grouping (proposed copy); Close/Esc/close icon keep edits; View entries navigates to /content/events.
|
||||||
|
5. Confirm (total 0): no request; copy, "Key: recipes" in mono; Cancel/Esc/close icon send nothing; focus starts on Cancel.
|
||||||
|
6. Deleting: one DELETE, "Deleting…" with loader, Cancel disabled, Esc/overlay/close icon do not dismiss, second activation sends nothing, focus on the title.
|
||||||
|
7. Deleted: 204 closes the dialog, store.drop called, navigates to /schema with no leave prompt even with unsaved edits, toast copy, list and sidebar Content group no longer show the type, no GET /v1/content-type afterwards; reopening /schema/recipes shows "Content type not found".
|
||||||
|
8. Fallback 409: dialog keeps title "Delete Recipes?", error alert copy, "Close" and "View entries", no delete button, store untouched, user stays on the page, edits kept.
|
||||||
|
9. Other answers (it.each): 404 (dialog closes, store drops, not-found page), 403 (access page), 401 (redirect to /login with expired reason), 500 and network (alert copy in the dialog, store untouched, retry sends the same DELETE and clears the alert).
|
||||||
|
10. Offline: Delete disabled with the dialog open, enabled on reconnect, nothing sent by itself.
|
||||||
|
11. Unsaved edits: dialog uses the saved count; opening, Cancel, Close and failures leave edits, chip and undo rows unchanged; 204 leaves with no prompt; blocked dialog for Events keeps edits.
|
||||||
|
12. Accessibility: focus return to "More actions", destructive button not default focus, menu keyboard use.
|
||||||
|
13. Structural refactor (SchemaTypeView.vue, six flags simplified): no new behaviour. Every existing SchemaTypeView/SchemaBuilder spec, schema_builtin_view, create and edit specs pass unchanged with no edit to their assertions; if one needs a change, stop and report. The resolver outcomes (built-in, custom edit, create, not found, forbidden, loading, error) are covered by one it.each over the former flag combinations.
|
||||||
|
14. French: every new string has an entry (i18n completeness spec passes).
|
||||||
|
|
||||||
|
## Visual (task visual:check -- schema)
|
||||||
|
|
||||||
|
Every capture within 10 %, desktop and mobile, light and dark. Register nothing new in `extraSources` (group "3 Review and delete" is already registered).
|
||||||
|
|
||||||
|
| Board state | Setup in web/visual/states.ts | Board sample data |
|
||||||
|
|---|---|---|
|
||||||
|
| Delete type: blocked | path /schema/events, steps: open "More actions", choose "Delete content type" | "You can't delete Events yet", "Events has 37 entries" |
|
||||||
|
| Delete type: confirm | path /schema/recipes (Recipes 4 fields, entry total 0), same steps | "Delete Recipes?", "Key: recipes" |
|
||||||
|
| Delete type: server fallback (409) | path /schema/recipes, DELETE mocked 409 content_type_has_entries, steps: open menu, choose item, "Delete content type" | "Recipes now has entries" |
|
||||||
|
| Field key error | replace `skip: 'pending'`; path /schema/events (the board draws it in the edit builder, not /schema/new); steps: Add field, label "Second date", type Date, set key "2nd-date" | 8 fields, row selected, chip "1 problem to fix" |
|
||||||
|
|
||||||
|
Board caveat (report, never hide): in the three delete frames the page behind the dialog is the Events builder while the dialog says Recipes (the frame reuses one builder). The overlay is compared as drawn (see open question 6). The desktop overflow menu itself is not drawn on any board: it is not visually checked.
|
||||||
|
|
||||||
|
## Manual
|
||||||
|
|
||||||
|
- Real backend, owner and admin: create a type with entries and try to delete it (dialog blocked, no request). Delete the entries, delete the type (204), check the sidebar and the list, reload /schema/<key>.
|
||||||
|
- Race: open Recipes, add an entry elsewhere, confirm the delete and check the real 409 fallback.
|
||||||
|
- Delete a type while another tab shows it, then act in the other tab (404 page).
|
||||||
|
- Keyboard: Tab to "More actions", open with Enter, dialogs trap focus and return it. Screen reader announces the dialog titles and the error alert.
|
||||||
|
- Real offline: open the confirm dialog, go offline, reconnect.
|
||||||
@@ -0,0 +1,450 @@
|
|||||||
|
Feature: Edit a custom content type in the Schema builder
|
||||||
|
As an owner or admin
|
||||||
|
I want to change the name and fields of a saved custom type
|
||||||
|
So that the type follows the content it holds
|
||||||
|
|
||||||
|
Background:
|
||||||
|
Given the SPA calls the API with relative URLs under /v1 and the "jwt" HttpOnly cookie
|
||||||
|
And API errors are plain text
|
||||||
|
And the builder, FieldList, FieldInspector, ChoiceList, ApiPreview, status chip and leave guard of features/schema_builder_create.feature are reused unchanged unless a scenario below says otherwise
|
||||||
|
And PUT /v1/content-type/{key} takes {name, icon, fields[{key, label, type, required, unique, default, min, max, options}]} and answers 200 with the content type
|
||||||
|
And PUT answers 400 (name or icon), 404 content_type_not_found, 409 schema_incompatible, 422 invalid_field, 403 or 500
|
||||||
|
And the number of entries comes from GET /v1/content-type/{key}/entry?page=1&size=5, field "total"
|
||||||
|
And the route /schema/:key keeps meta auth "verified" and title "Schema"
|
||||||
|
And the content types store is the source of the loaded type; no GET /v1/content-type/{key} is made
|
||||||
|
And only owners and admins can use Schema; the SPA decides from the session role, the API still enforces it
|
||||||
|
And every string goes through t() and has a French entry in i18n/messages.ts
|
||||||
|
And a copy tagged "(proposed copy)" is not in the design and is the coder's single point of change
|
||||||
|
|
||||||
|
Scenario Outline: Resolving the key of /schema/:key
|
||||||
|
Given the custom list holds events, recipes, press-mentions and the built-in list holds articles, authors, sites, media, users
|
||||||
|
When an owner opens /schema/<key>
|
||||||
|
Then <result>
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| key | result |
|
||||||
|
| events | the builder in edit mode |
|
||||||
|
| articles | the read-only built-in view, unchanged from schema_builtin_view.feature |
|
||||||
|
| unknown | "Content type not found" |
|
||||||
|
| new | the create builder, unchanged |
|
||||||
|
|
||||||
|
Scenario: Reaching the editor from the list
|
||||||
|
Given the Schema list is Populated
|
||||||
|
Then each custom row is a link to /schema/<key> on the table and on the mobile cards
|
||||||
|
And built-in rows still link to /schema/<key>
|
||||||
|
When the user activates the row "Events"
|
||||||
|
Then the router navigates to /schema/events and the builder opens in edit mode
|
||||||
|
|
||||||
|
Scenario: Loading, the session store and the entry count
|
||||||
|
Given an owner opens /schema/events as the first page of the session
|
||||||
|
Then GET /v1/content-type is called once and GET /v1/builtin-type once (the resolver needs both)
|
||||||
|
And GET /v1/content-type/events/entry?page=1&size=5 is called once
|
||||||
|
And the Schema skeleton is shown until the type, the built-in list and the count are known
|
||||||
|
And no GET /v1/content-type/events is made
|
||||||
|
|
||||||
|
Scenario Outline: The count or the list cannot be loaded
|
||||||
|
Given <failure>
|
||||||
|
Then the page shows the error "Couldn't load content type" (proposed copy) with the line "<line>" and a "Try again" action
|
||||||
|
And no builder, no Save is shown
|
||||||
|
When the user activates "Try again"
|
||||||
|
Then the failed request is sent again and the builder opens when it succeeds
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| failure | line |
|
||||||
|
| the entry count answers 500 or fails (network) | GET /v1/content-type/events/entry failed. Check your connection and try again. (proposed copy) |
|
||||||
|
|
||||||
|
Scenario: The entry count answers 404
|
||||||
|
Given the entry count answers 404 content_type_not_found
|
||||||
|
Then the page shows "Content type not found"
|
||||||
|
|
||||||
|
Scenario Outline: Roles and sessions in edit mode
|
||||||
|
Given <who> opens /schema/events
|
||||||
|
Then <result>
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| who | result |
|
||||||
|
| a verified owner or admin | the builder in edit mode |
|
||||||
|
| a verified user who is neither | "You don't have access to Schema" with "Go to Home", URL unchanged |
|
||||||
|
| an unverified user | the redirect to /register/pending |
|
||||||
|
| a signed-out visitor | the redirect to /login |
|
||||||
|
|
||||||
|
Scenario: Session-owned store
|
||||||
|
Given an owner has loaded the custom and built-in lists
|
||||||
|
When the user signs out
|
||||||
|
Then the content types store is reset
|
||||||
|
And the next signed-in user's first Schema page loads both lists again
|
||||||
|
And an in-progress edit is not carried to another session or to a second visit of /schema/events
|
||||||
|
|
||||||
|
Scenario: Editing an existing type, desktop (design state 2)
|
||||||
|
Given /schema/events is Events with 7 saved fields and 37 entries, on a 1440 px viewport
|
||||||
|
Then the breadcrumb is "Schema" (a link) then "Events"
|
||||||
|
And "Name" holds "Events" and is editable
|
||||||
|
And "Key" holds "events" in mono, read-only, with a lock icon, no pencil, no Auto badge and no "Reset to match the name"
|
||||||
|
And the chip reads "Saved"
|
||||||
|
And the info bar reads "37 entries use this content type. Changes are checked against them when you save." with an info icon, under the type bar and above the list
|
||||||
|
And the list header reads "Fields" and "7 of 50" with the 7 rows in saved order, none carrying a badge "New" or "Changed"
|
||||||
|
And "Add field" is shown under the list
|
||||||
|
And the first row is selected and the inspector title is "Field: Title" with no "New" badge
|
||||||
|
And "Save" and "Discard" are disabled
|
||||||
|
And the API preview bar is collapsed
|
||||||
|
|
||||||
|
Scenario: Editing an existing type, mobile (design state 2)
|
||||||
|
Given the same page on a 390 px viewport
|
||||||
|
Then the topbar shows an arrow-left, the title "Events"
|
||||||
|
And Name and Key are stacked, then the info bar, then the rows, then the "API preview" row
|
||||||
|
And no inspector is shown until a row is activated
|
||||||
|
And the bottom bar holds the chip "Saved", Discard and Save
|
||||||
|
|
||||||
|
Scenario Outline: The info bar follows the count
|
||||||
|
Given the entry count answers <total>
|
||||||
|
Then <bar>
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| total | bar |
|
||||||
|
| 0 | no info bar is shown |
|
||||||
|
| 1 | "1 entry uses this content type. Changes are checked against it when you save." (proposed copy) |
|
||||||
|
| 37 | "37 entries use this content type. Changes are checked against them when you save." |
|
||||||
|
| 1200 | "1,200 entries use this content type. Changes are checked against them when you save." |
|
||||||
|
|
||||||
|
Scenario: The locked type key (design state 3)
|
||||||
|
Given /schema/events
|
||||||
|
When the user hovers or focuses the locked key
|
||||||
|
Then a tooltip reads "The key is used in URLs and the API, so it can't change after the type is created."
|
||||||
|
And the tooltip closes on blur, mouse out and Esc
|
||||||
|
And the key input cannot be typed in and no key error can appear
|
||||||
|
|
||||||
|
Scenario: Saved fields are locked
|
||||||
|
Given the saved field Starts on (date) is selected
|
||||||
|
Then "Key" holds "starts_on" with a lock icon, no Auto badge, read-only, with the help "Used in the API, so it can't change."
|
||||||
|
And "Type" shows "Can't change after saving" with a lock icon
|
||||||
|
And the six tiles are shown, the date tile selected and the other five at reduced emphasis and not selectable
|
||||||
|
And label, Required, Unique values, Default value, limits and choices stay editable
|
||||||
|
|
||||||
|
Scenario: Fields added since the last save are not locked
|
||||||
|
Given the user activates "Add field" on /schema/events
|
||||||
|
Then the new row is selected with the badge "New", an Auto key, six selectable tiles and no lock
|
||||||
|
And the key and type behave as in the create builder
|
||||||
|
And a label typed for it derives its key without colliding with any saved key
|
||||||
|
|
||||||
|
Scenario Outline: What marks a saved field as changed
|
||||||
|
Given the saved field <field> is selected
|
||||||
|
When the user <edit>
|
||||||
|
Then its row and its inspector title show the badge "Changed"
|
||||||
|
When the user restores the original value
|
||||||
|
Then the badge goes
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| field | edit |
|
||||||
|
| Capacity | sets Highest value to 2000 |
|
||||||
|
| Title | renames the label to "Name of event" |
|
||||||
|
| Starts on| turns Required off |
|
||||||
|
| Category | adds the choice "Panel" |
|
||||||
|
| Online | turns the default on |
|
||||||
|
|
||||||
|
Scenario: Reordering is not a change of a field (proposed)
|
||||||
|
Given the saved fields in saved order
|
||||||
|
When the user moves Ends on above Starts on
|
||||||
|
Then no row shows "Changed"
|
||||||
|
And the chip reads "Unsaved changes" and Save is enabled
|
||||||
|
|
||||||
|
Scenario: Unsaved changes (design state 4)
|
||||||
|
Given Events with 37 entries
|
||||||
|
When the user sets Capacity's Highest value to 2000, adds Speaker (Text) and Room (Choice, required, default "Main hall", choices "Main hall" and "Studio"), and removes Description
|
||||||
|
Then the chip reads "Unsaved changes" and Save and Discard are enabled
|
||||||
|
And Capacity shows "Changed", Speaker and Room show "New"
|
||||||
|
And an undo row after the list reads "Description will be removed" with the action "Undo", with a minus icon and a dashed border
|
||||||
|
And the header reads "8 of 50"
|
||||||
|
And the info bar stays
|
||||||
|
|
||||||
|
Scenario: Removing a saved field and undoing it
|
||||||
|
Given Events with the saved field Description at position 7
|
||||||
|
When the user activates Remove on Description
|
||||||
|
Then it leaves the list and an undo row "Description will be removed" appears
|
||||||
|
And the next row (or the previous one at the end) is selected
|
||||||
|
When the user activates "Undo"
|
||||||
|
Then Description returns at position 7 with its original values and no badge
|
||||||
|
And the undo row goes, and with no other edit the chip returns to "Saved" and Save is disabled
|
||||||
|
|
||||||
|
Scenario: Several removals
|
||||||
|
Given the user removed Description and Ends on
|
||||||
|
Then two undo rows are shown, one per field, in the order of the removals (proposed)
|
||||||
|
And each Undo restores its own field at its original position
|
||||||
|
|
||||||
|
Scenario: A removed key stays reserved (proposed)
|
||||||
|
Given the user removed the saved field Description
|
||||||
|
When the user adds a field labelled "Description"
|
||||||
|
Then its Auto key is "description_2"
|
||||||
|
And "Undo" on the removed field still restores "description" without a duplicate key
|
||||||
|
|
||||||
|
Scenario: Undo at the limit of 50 fields (proposed)
|
||||||
|
Given 50 fields are in the list and one saved field is in an undo row
|
||||||
|
Then "Undo" is disabled until a field is removed
|
||||||
|
|
||||||
|
Scenario: Removing every field
|
||||||
|
Given the user removed all saved fields
|
||||||
|
Then the list shows "No fields yet" with "A content type needs at least one field." in the error colour
|
||||||
|
And undo rows are shown for the removed fields
|
||||||
|
And the chip counts one problem and Save is disabled
|
||||||
|
|
||||||
|
Scenario: Name edit only
|
||||||
|
Given Events
|
||||||
|
When the user changes the name to "Events and talks"
|
||||||
|
Then the Key stays "events"
|
||||||
|
And the chip reads "Unsaved changes"
|
||||||
|
And the sidebar and the list keep "Events" until the PUT answers
|
||||||
|
|
||||||
|
Scenario Outline: Type-level rules in edit mode
|
||||||
|
Given Events
|
||||||
|
When the user sets Name to <value>
|
||||||
|
Then <message> is shown under Name with an alert icon
|
||||||
|
And Save is disabled and no request is sent
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| value | message |
|
||||||
|
| (empty or spaces) | Give the content type a name. |
|
||||||
|
|
||||||
|
Scenario: Field errors (design state 5)
|
||||||
|
Given Events
|
||||||
|
When the user empties the label of Ends on, sets Capacity's Lowest value to 6000, and gives Category the choices Talk, Workshop, a blank and Talk
|
||||||
|
Then the chip reads "3 problems to fix" and Save is disabled
|
||||||
|
And the three rows are outlined with an alert icon
|
||||||
|
And the messages "Give the field a label.", "Lowest value can't be above the highest value.", "Choices can't be blank." and "Two choices are the same." are shown under their inputs
|
||||||
|
And errors follow the timing and the counting rules of the create builder
|
||||||
|
|
||||||
|
Scenario: A single field key error on a new field (design state 7)
|
||||||
|
Given Events and a field added since the last save with the key "start-date"
|
||||||
|
Then the Key shows "Start with a letter. Use lowercase letters, digits and underscores." with the alert icon and the chip reads "1 problem to fix"
|
||||||
|
And a saved field never shows a key error
|
||||||
|
|
||||||
|
Scenario: The choice list of a saved Choice field (design state 8)
|
||||||
|
Given the saved field Category with the choices Talk, Workshop, Meetup is selected
|
||||||
|
Then every control of the create builder's choice list works, including add, remove, reorder and the 50 cap
|
||||||
|
And the help keeps "Removing a choice that entries use will be refused when you save."
|
||||||
|
And the default select lists the choices and is cleared when its choice is removed or renamed
|
||||||
|
|
||||||
|
Scenario: Keyboard reorder in edit mode (design state 9)
|
||||||
|
Given Events with 7 saved fields and Ends on at position 3
|
||||||
|
When the user focuses the grip "Move Ends on", presses Space then Up
|
||||||
|
Then the polite live region reads "Moving Ends on. Position 2 of 7. Press Up or Down to move, Space to drop, Esc to cancel."
|
||||||
|
And Esc restores the order and Space drops it
|
||||||
|
|
||||||
|
Scenario: API preview in edit mode (design state 10)
|
||||||
|
Given Events
|
||||||
|
When the user opens "API preview"
|
||||||
|
Then the routes use the locked key "events"
|
||||||
|
And the sample entry follows the current fields, so added fields appear and removed ones disappear as the user edits
|
||||||
|
And the note "Updates as you edit. Fields you add or remove here appear after you save." is shown
|
||||||
|
And Copy JSON, the "Copied" label and the mobile sheet behave as in the create builder
|
||||||
|
|
||||||
|
Scenario: Saving a type that has no entries
|
||||||
|
Given Recipes with 4 saved fields and 0 entries
|
||||||
|
When the user changes the label of Servings and activates Save
|
||||||
|
Then PUT /v1/content-type/recipes is called once with no review dialog
|
||||||
|
And the body has exactly name, icon and fields
|
||||||
|
|
||||||
|
Scenario: The PUT body
|
||||||
|
Given Events with the loaded icon "calendar" (or null)
|
||||||
|
When the user saves
|
||||||
|
Then the body is {name, icon, fields} with name trimmed
|
||||||
|
And "icon" equals the loaded icon, so an edit never changes it (proposed, see open question)
|
||||||
|
And no "key" is sent in the body
|
||||||
|
And the fields are in list order, undo-row fields are not sent, and each field carries exactly key, label, type, required, unique, default, min, max, options
|
||||||
|
And unset default, min and max are null, options are [] for a non-select field, a date bound is "YYYY-MM-DD", the boolean default is true or null
|
||||||
|
And the key and type of every saved field equal the loaded ones
|
||||||
|
|
||||||
|
Scenario: Saving (design state 11, no entries)
|
||||||
|
Given the PUT has not answered
|
||||||
|
Then the chip reads "Saving…" with a loader, Save shows a loader and is disabled, Discard is disabled
|
||||||
|
And Name, the inspector, Add field, grips, Move, Remove and Undo are dimmed and disabled
|
||||||
|
And a second activation of Save sends no second request
|
||||||
|
|
||||||
|
Scenario: Saved (design state 12)
|
||||||
|
Given the PUT answers 200 with Events and 8 fields
|
||||||
|
Then a success toast "Content type saved" with "Events now has 8 fields." is shown
|
||||||
|
And the user stays on /schema/events
|
||||||
|
And every badge "New" and "Changed" and every undo row clear
|
||||||
|
And the added fields become saved fields: their key and type are now locked
|
||||||
|
And the chip reads "Saved at" followed by the time (HH:MM) of the response's updated_at, Save and Discard are disabled
|
||||||
|
And the content types store holds the answered type in place, so the list, the sidebar Content group and the field count show the new name and count with no second GET /v1/content-type
|
||||||
|
And with one field the toast reads "Events now has 1 field." (proposed copy)
|
||||||
|
And no "Leave without saving?" prompt is shown afterwards
|
||||||
|
|
||||||
|
Scenario: Edit after saving
|
||||||
|
Given the form was just saved
|
||||||
|
When the user edits the name
|
||||||
|
Then the chip reads "Unsaved changes" again
|
||||||
|
And Discard returns to the last saved state, not to the state at page load
|
||||||
|
|
||||||
|
Scenario: Discard
|
||||||
|
Given the user edited the name, a field and removed a field
|
||||||
|
When the user activates Discard
|
||||||
|
Then the form returns to the loaded type, with the first row selected, no badge, no undo row, no error and the chip "Saved"
|
||||||
|
And nothing is sent and the URL stays /schema/events
|
||||||
|
|
||||||
|
Scenario Outline: Leaving with unsaved edits
|
||||||
|
Given <state>
|
||||||
|
When the user leaves through the breadcrumb, the mobile arrow, the sidebar or the browser back
|
||||||
|
Then <result>
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| state | result |
|
||||||
|
| no edit | the router navigates with no prompt |
|
||||||
|
| an edit, even one only in an undo row | the dialog "Leave without saving?" with "Keep editing" and "Discard changes" |
|
||||||
|
| after Save answered 200 | the router navigates with no prompt |
|
||||||
|
| after Discard | the router navigates with no prompt |
|
||||||
|
|
||||||
|
Scenario: Save on a type with entries opens the review (design group 3, state 1)
|
||||||
|
Given Events with 37 entries, the edits of the "Unsaved changes" scenario and no error
|
||||||
|
When the user activates Save
|
||||||
|
Then no PUT is sent yet
|
||||||
|
And the dialog "Review changes to Events" with "Apply them to save the content type." opens (a bottom sheet on mobile)
|
||||||
|
And the summary reads "Add 2 fields, change 1, remove 1" and "Events has 37 entries. Each one is checked against the new fields when you apply."
|
||||||
|
And the changes are listed in this order: additions, changes, removals, each in list order
|
||||||
|
And the footer note reads "Flagged changes can be refused if existing entries don't fit. If that happens, nothing is changed."
|
||||||
|
And "Back to editing" and "Apply changes" are shown
|
||||||
|
|
||||||
|
Scenario Outline: Review rows
|
||||||
|
Given Events with entries and the edit <edit>
|
||||||
|
Then the review shows the row "<title>" with the text "<text>" and <flag>
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| edit | title | text | flag |
|
||||||
|
| adds Speaker, Text, optional | Add Speaker | Text, optional. | no flag |
|
||||||
|
| adds Room, Choice, required, default "Main hall" | Add Room | Choice, required, default "Main hall". Existing entries get the default, so they still fit. | no flag |
|
||||||
|
| adds Seats, Number, required, no default | Add Seats | Number, required. Existing entries have no value for it. (proposed copy) | "Entries may not fit" |
|
||||||
|
| sets Capacity's Highest value from 5000 to 2000 | Change Capacity | Highest value goes from 5000 to 2000. | "Entries may not fit" |
|
||||||
|
| raises Capacity's Lowest value from 1 to 10 (proposed copy) | Change Capacity | Lowest value goes from 1 to 10. | "Entries may not fit" |
|
||||||
|
| sets a first Longest on Title (80) where none was set (proposed copy) | Change Title | Longest is now 80. | "Entries may not fit" |
|
||||||
|
| turns Required on for Ends on (proposed copy) | Change Ends on | Now required. | "Entries may not fit" |
|
||||||
|
| turns Unique values on for Category (proposed copy) | Change Category | Values must now be unique. | "Entries may not fit" |
|
||||||
|
| removes the choice Meetup from Category (proposed copy) | Change Category | Choice removed: "Meetup". | "Entries may not fit" |
|
||||||
|
| loosens Capacity's Highest value from 5000 to 8000 (proposed copy) | Change Capacity | Highest value goes from 5000 to 8000. | no flag |
|
||||||
|
| renames the label of Title to "Name" (proposed copy) | Change Title | Label goes from "Title" to "Name". | no flag |
|
||||||
|
| adds the choice "Panel" to Category (proposed copy) | Change Category | Choice added: "Panel". | no flag |
|
||||||
|
| removes Description | Remove Description | Entries stop returning its values. | "Removes data" |
|
||||||
|
|
||||||
|
Scenario Outline: The summary line
|
||||||
|
Given Events with entries and <changes>
|
||||||
|
Then the summary reads "<summary>"
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| changes | summary |
|
||||||
|
| 2 added, 1 changed, 1 removed | Add 2 fields, change 1, remove 1 |
|
||||||
|
| 1 added | Add 1 field |
|
||||||
|
| 1 changed, 2 removed | Change 1, remove 2 |
|
||||||
|
| 1 changed | Change 1 |
|
||||||
|
|
||||||
|
Scenario Outline: When the review opens
|
||||||
|
Given Events with 37 entries
|
||||||
|
When the user makes <edit> and activates Save
|
||||||
|
Then <result>
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| edit | result |
|
||||||
|
| only a name change or only a reorder | the PUT is sent at once, with no review (proposed) |
|
||||||
|
| a field added, changed or removed | the review opens |
|
||||||
|
| a name change and a changed field | the review opens and lists only the field change (proposed) |
|
||||||
|
|
||||||
|
Scenario: Back to editing from the review
|
||||||
|
Given the review is open
|
||||||
|
When the user chooses "Back to editing" (or presses Esc or the close icon)
|
||||||
|
Then the dialog closes, no PUT is sent and every edit is kept
|
||||||
|
|
||||||
|
Scenario: Applying (group 3, state 2)
|
||||||
|
Given the review is open
|
||||||
|
When the user activates "Apply changes"
|
||||||
|
Then PUT /v1/content-type/events is sent once
|
||||||
|
And the confirm button reads "Applying…" with a loader and the dialog's other actions are disabled
|
||||||
|
And Esc, the close icon and a click on the overlay do not dismiss the dialog
|
||||||
|
And a second activation sends nothing
|
||||||
|
|
||||||
|
Scenario: Applied
|
||||||
|
Given the PUT answers 200
|
||||||
|
Then the dialog closes, the toast, the cleared badges, the locks and the chip "Saved at" are as in "Saved (design state 12)"
|
||||||
|
And the info bar and the count are unchanged
|
||||||
|
|
||||||
|
Scenario: Refused (design state 15 and group 3, state 3)
|
||||||
|
Given the user applied the edits "Capacity's Highest value goes from 5000 to 2000" plus "Description removed"
|
||||||
|
When the PUT answers 409 with the body "schema_incompatible"
|
||||||
|
Then the review is replaced by the dialog "Nothing was changed" with "RenewCMS refused the changes because some entries don't fit the new fields. It doesn't say which entries."
|
||||||
|
And an error alert reads "Your content type is as it was" with "No field was added, changed or removed."
|
||||||
|
And the section "The change that can cause this in your edit" lists only the flagged changes, here Change Capacity with "Highest value goes from 5000 to 2000. An entry may have a higher value." and the badge "Possible cause"
|
||||||
|
And Removes-data rows are not listed as a cause
|
||||||
|
And the explanation reads "This kind of change is refused when an entry is over the new limit, a new required field has no default, a field becomes unique while entries share a value, or a removed choice is still in use."
|
||||||
|
And "Discard changes" and "Back to editing" are shown
|
||||||
|
And no entry, id or value is ever named
|
||||||
|
And every edit is still in the form and the store still holds the type as loaded
|
||||||
|
|
||||||
|
Scenario: Refused with no flagged change (proposed)
|
||||||
|
Given the 409 comes back for edits that have no flagged change
|
||||||
|
Then the dialog shows "Nothing was changed", the "Your content type is as it was" alert and the explanation
|
||||||
|
And the section "The change that can cause this in your edit" is omitted
|
||||||
|
|
||||||
|
Scenario: Back to editing after a refusal (design state 15)
|
||||||
|
Given the refusal dialog is open
|
||||||
|
When the user chooses "Back to editing"
|
||||||
|
Then the dialog closes and the page shows the error alert "Nothing was changed" with "Some entries don't fit the new fields, so the whole change was refused. RenewCMS can't tell which entries. The changes that can cause this are marked." and the action "Review changes"
|
||||||
|
And the rows of the flagged changes show the badge "Possible cause" next to "Changed" or "New"
|
||||||
|
And the chip reads "Unsaved changes" and Save stays enabled
|
||||||
|
When the user activates "Review changes"
|
||||||
|
Then the review dialog (group 3, state 1) opens again, with the same rows
|
||||||
|
|
||||||
|
Scenario: Discard changes after a refusal
|
||||||
|
Given the refusal dialog is open
|
||||||
|
When the user chooses "Discard changes"
|
||||||
|
Then the dialog closes and the form returns to the loaded type, with no banner, no badge and the chip "Saved"
|
||||||
|
|
||||||
|
Scenario: The refusal markers clear
|
||||||
|
Given the banner "Nothing was changed" is shown
|
||||||
|
When a PUT succeeds, or the user activates Discard
|
||||||
|
Then the banner and every "Possible cause" badge go
|
||||||
|
And when the user undoes or reverts a flagged change, that row loses its "Possible cause" badge
|
||||||
|
|
||||||
|
Scenario Outline: Other answers of the PUT
|
||||||
|
Given the PUT answers <status> with <body>
|
||||||
|
Then <outcome>
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| status | body | outcome |
|
||||||
|
| 422 | invalid_field | the review dialog closes and the banner "Check the fields marked in the list." (proposed copy) is shown, edits kept |
|
||||||
|
| 400 | Bad request body | the review closes and "Give the content type a name." is shown under Name, edits kept (proposed copy) |
|
||||||
|
| 404 | content_type_not_found | the page "Content type not found" and the store drops the type (proposed copy) |
|
||||||
|
| 403 | Only ... | the page "You don't have access to Schema" |
|
||||||
|
| 401 | (any) | the existing redirect to /login with the expired reason |
|
||||||
|
|
||||||
|
Scenario Outline: Save failed (design state 13)
|
||||||
|
Given the PUT <failure>
|
||||||
|
Then the review dialog (if open) closes
|
||||||
|
And an error alert titled "Couldn't save the content type" shows "Something went wrong on our side. Your changes are still here. Try again in a moment."
|
||||||
|
And it has a "Try again" action and the chip reads "Save failed"
|
||||||
|
And every edit is kept and Save stays enabled
|
||||||
|
When the user activates "Try again"
|
||||||
|
Then the same body is sent again, through the review again when the type has entries
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| failure |
|
||||||
|
| answers 500 |
|
||||||
|
| fails (network) |
|
||||||
|
|
||||||
|
Scenario: Offline (design state 16)
|
||||||
|
Given the user edited Events and navigator.onLine becomes false
|
||||||
|
Then the banner "You're offline. Changes will be saved when you reconnect." with a wifi-off icon is shown
|
||||||
|
And the chip reads "Waiting for connection", Save is disabled and every edit is kept
|
||||||
|
When the connection returns
|
||||||
|
Then the banner goes, Save is enabled again and nothing is sent by itself
|
||||||
|
|
||||||
|
Scenario: Offline while the review is open
|
||||||
|
Given the review dialog is open and navigator.onLine becomes false
|
||||||
|
Then "Apply changes" is disabled and the edits are kept
|
||||||
|
|
||||||
|
Scenario: Mobile field sheet in edit mode
|
||||||
|
Given a 390 px viewport
|
||||||
|
When the user activates the row Capacity
|
||||||
|
Then the sheet "Field: Capacity" opens with the inspector, the locked key, Move up, Move down, Remove and "Done"
|
||||||
|
And Remove inside the sheet closes the sheet and shows the undo row
|
||||||
|
|
||||||
|
Scenario: Accessibility of the edit mode
|
||||||
|
Then the lock icons have a text alternative or are tied to the field's help text
|
||||||
|
And dialogs trap focus, return it to the opener on close, and the Applying dialog keeps focus on its title
|
||||||
|
And the undo row's "Undo" is a button reachable by keyboard
|
||||||
|
And controls are 44 px high on mobile and focus is a 2 px ring in the primary colour
|
||||||
@@ -0,0 +1,103 @@
|
|||||||
|
# QA: Schema builder, edit (SPA slice 4; delete is slice 5)
|
||||||
|
|
||||||
|
Runner: Vitest + Vue Test Utils (`task test:web`). No Go test: PUT /v1/content-type/{key} and the entry list are already covered by features/custom_content_types.qa.md and nothing changes in the backend.
|
||||||
|
Same pattern as features/schema_builder_create.qa.md: mock `/v1` through the api composable (extend `views/__tests__/schemaTestKit.ts` with PUT and the entry count handlers, and a full "Events" type with the board's 7 saved fields), mount with the real router and a resolved session whose role varies, `components/__tests__/viewport.ts` for 1440 and 390, fake timers where a delay exists. Never freeze the system date. "Saved at HH:MM" is asserted with /^Saved at \d{2}:\d{2}$/ only.
|
||||||
|
|
||||||
|
## Automated
|
||||||
|
|
||||||
|
Fixtures: Events (id 1, 7 saved fields as drawn on the board: Title text required unique max 80, Starts on date required, Ends on date, Online boolean default false, Capacity number min 1 max 5000, Category select Talk/Workshop/Meetup, Description richtext) with icon "calendar"; Recipes (4 saved fields, 0 entries); the entry-count body {items:[],total:37,page:1,size:1}; plain-text bodies schema_incompatible, content_type_has_entries, content_type_not_found, invalid_field.
|
||||||
|
|
||||||
|
Pure logic (lib/__tests__, it.each over the feature's Examples):
|
||||||
|
1. Form from a ContentType: API field to BuilderField (number default to string, boolean default to defaultOn, options, ISO dates), saved flag, locked keyMode, and the round trip: loaded form to payload equals the loaded fields (no spurious diff).
|
||||||
|
2. Change detection per saved field: Changed on and off by restoring the value; reorder-only is not a field change; New for added fields.
|
||||||
|
3. Diff for the review: adds, changes, removes in that order, the summary line (singular, zero parts omitted), the row texts of the "Review rows" table, the flags ("Entries may not fit", "Removes data", none), and the flagged-only list used by the refusal. Name-only or reorder-only means no review.
|
||||||
|
4. Payload for PUT: {name, icon, fields}, no key, icon equal to the loaded one (null stays null), undo-row fields excluded, saved key and type unchanged.
|
||||||
|
5. Field key derivation against saved keys and keys in undo rows (`description_2`).
|
||||||
|
6. Undo bookkeeping: positions, several removals, limit of 50.
|
||||||
|
7. Info-bar copy for 0, 1, 37 and 1200 entries.
|
||||||
|
|
||||||
|
Store (stores/__tests__/contentTypes.spec.ts):
|
||||||
|
8. replace(type) swaps by key and keeps order by name when the name changed, does nothing when "idle", never touches built-in items, no request. reset() clears both slices (signed-out case).
|
||||||
|
|
||||||
|
Composable and API (composables/__tests__/useContentTypes.spec.ts):
|
||||||
|
9. updateContentType PUTs JSON to /v1/content-type/{key} and returns the type. countEntries reads `total` from the size=5 request. ApiError carries status and plain-text body for 400, 404, 409, 422, 403, 500. NetworkError passes through.
|
||||||
|
|
||||||
|
Resolver and routing:
|
||||||
|
10. Key resolver (built-in, custom, none, loading) for events, articles, unknown, new. /schema/new is still the create builder, GET /v1/builtin-type result is awaited for /schema/:key. Custom rows of SchemaTable and the mobile cards are links to /schema/<key>.
|
||||||
|
11. Roles: owner, admin, neither (403 page), unverified and signed-out redirects (extend routerGuard.spec) on /schema/events.
|
||||||
|
12. Session reset: sign-out resets the store and discards any edit state; a second visit starts from the store, not from an old draft.
|
||||||
|
|
||||||
|
Builder view in edit mode (new views/__tests__/SchemaBuilderEdit*.spec.ts), one test per scenario:
|
||||||
|
13. Loading: calls list (assert once each), skeleton until type, list and count are known, no GET /v1/content-type/events.
|
||||||
|
14. Count or list failure: error copy, Try again re-sends, builder shown after success. Count 404 gives "Content type not found".
|
||||||
|
15. State 2 desktop and mobile: breadcrumb, Name editable, locked Key without pencil/Auto/Reset, chip "Saved", info bar, "7 of 50", no badges, first row selected, Save and Discard disabled, collapsed API bar. Mobile topbar, stack order, bottom bar.
|
||||||
|
16. Info bar for 0, 1, 37, 1200.
|
||||||
|
17. Locked key tooltip on hover and on focus, closes on blur and Esc, input not editable.
|
||||||
|
18. Saved fields locked: key lock and help, "Can't change after saving", tiles not selectable, other controls editable. New fields unlocked.
|
||||||
|
19. Changed badge table (5 rows) and revert; reorder-only is no Changed badge but dirty.
|
||||||
|
20. State 4 end to end: badges, undo row text and action, header count, chip.
|
||||||
|
21. Remove and Undo: position restored, no residue, chip back to "Saved". Several removals, reserved key, Undo disabled at 50, empty list error.
|
||||||
|
22. Name-only edit keeps the key; empty name error and disabled Save.
|
||||||
|
23. Field errors (state 5) and single field key error on a new field; a saved field never shows a key error.
|
||||||
|
24. Choice list on a saved Choice field (state 8) and keyboard reorder (state 9) with the live-region texts.
|
||||||
|
25. API preview in edit mode (state 10): locked key in the routes, live sample, note text.
|
||||||
|
26. PUT without entries: one request, no dialog, exact body (icon preserved, no key), Saving state (state 11) with dimmed/disabled controls and no second request on double activation.
|
||||||
|
27. Saved (state 12): toast copy incl. singular, stays on the page, badges and undo rows cleared, newly saved fields now locked, chip /^Saved at \d{2}:\d{2}$/, store.replace, list/sidebar/count updated with no extra GET, no leave prompt, edit after save and Discard back to last saved.
|
||||||
|
28. Discard: back to the loaded form, nothing sent.
|
||||||
|
29. Leave guard (5 rows) with Keep editing, dismiss and Discard changes.
|
||||||
|
30. Review (group 3, state 1): opens only for adds/changes/removes with total > 0; no PUT yet; summary, rows (the table), order, footer note, Back to editing, Esc, mobile sheet.
|
||||||
|
31. Applying (state 2): one PUT, loader, non-dismissable (Esc, overlay, close icon), second activation ignored.
|
||||||
|
32. Applied: dialog closes, same results as item 27.
|
||||||
|
33. Refused: 409 schema_incompatible: refusal dialog copy, only flagged changes listed with "Possible cause", no entry named, store untouched, edits kept. Without flagged change: section omitted. Back to editing: banner "Nothing was changed", "Review changes" reopens the review, row markers. Discard changes resets. Markers clear on success, Discard or revert.
|
||||||
|
34. Other PUT answers: 422 banner, 400 name message, 404 not-found page and store drop, 403 page, 401 redirect.
|
||||||
|
35. Save failed (state 13): 500 and network, review closes, banner and chip, edits kept, Try again resends the same body through the review again.
|
||||||
|
36. Offline (state 16) and offline with the review open.
|
||||||
|
37. Mobile field sheet in edit mode.
|
||||||
|
40. Accessibility: focus return from dialogs, Applying focus on its title, Undo reachable by keyboard.
|
||||||
|
|
||||||
|
Existing tests to update:
|
||||||
|
41. features/schema_builtin_view.qa.md and SchemaTypeView.spec: "Content type not found" for a key that is neither built-in nor custom; events is now the editor. features/schema_list_and_content_nav.qa.md and SchemaView.spec: custom rows are links.
|
||||||
|
42. features/schema_builder_create.qa.md item 29/31: nothing changes for create; assert that the create builder still never sends "icon" (regression guard next to the edit icon test).
|
||||||
|
43. French: every new string has a French entry (the i18n completeness spec must pass).
|
||||||
|
|
||||||
|
## Visual (task visual:check -- schema)
|
||||||
|
|
||||||
|
Run `task visual:check -- schema`. Every capture within 10 %, desktop and mobile, light and dark. Mock GET /v1/auth/me (owner "Marta Alves"), GET /v1/builtin-type, and GET /v1/content-type with the 3 custom types. Replace the placeholder Events fields of `schemaCustomTypes` in `web/visual/states.ts` with the board's full 7 fields (EV), keep 7 as the list's field count, and add Recipes with the board's 4 fields (RC). Mock GET /v1/content-type/events/entry as total 37 and /recipes/entry as total 0. Register the group "3 Review and delete" in `extraSources` of `web/visual/check.ts`.
|
||||||
|
|
||||||
|
Setups to replace `skip: 'pending'` in `web/visual/states.ts` (screen `schema`, steps are Playwright actions on the SPA):
|
||||||
|
|
||||||
|
| Board state | Setup (path /schema/events unless noted) | Board sample data |
|
||||||
|
|---|---|---|
|
||||||
|
| Editing an existing type | no steps | Events, 7 saved fields, Title selected, info bar "37 entries use this content type…", chip "Saved", locked key |
|
||||||
|
| Locked key: tooltip | select the row "Starts on", hover (focus on mobile) the locked key | tooltip text, Starts on selected |
|
||||||
|
| Unsaved changes | steps: Capacity Highest value 2000, Add field "Speaker", Add field "Room" with Choice, Required, choices Main hall and Studio, default Main hall, remove Description, select Capacity | rows New and Changed, undo row "Description will be removed", chip "Unsaved changes" |
|
||||||
|
| Field errors | steps: empty the label of Ends on, Capacity Lowest value 6000, Category choices Talk, Workshop, blank, Talk, select Capacity | chip "3 problems to fix" and the four messages |
|
||||||
|
| Choice list editor | steps: Category choices Talk, Workshop, Meetup, blank, Talk, select Category | "5 of 50", chip "1 problem to fix" |
|
||||||
|
| Keyboard reorder | steps: focus the grip "Move Ends on", press Space, press Up | live region "Moving Ends on. Position 2 of 7. …", Ends on picked up |
|
||||||
|
| API preview open | steps: open "API preview" (sheet on mobile) | key events, board's sample JSON |
|
||||||
|
| Saved | `skip: 'clock-sensitive'` | the chip says "Saved at 11:02" |
|
||||||
|
| Save failed | PUT mocked 500; same edits as Unsaved changes; steps: Save, Apply changes | banner "Couldn't save the content type", chip "Save failed" |
|
||||||
|
| Schema incompatible | PUT mocked 409 schema_incompatible; same edits; steps: Save, Apply changes, Back to editing | banner "Nothing was changed" with "Review changes", "Possible cause" on Capacity |
|
||||||
|
| Offline | same edits; steps: go offline | offline banner, chip "Waiting for connection" |
|
||||||
|
| Saving | see open question 6 | |
|
||||||
|
| Review before saving | same edits; steps: Save | dialog copy and the 4 rows of group 3 state 1 |
|
||||||
|
| Applying | PUT mocked to hang; steps: Save, Apply changes | "Applying…" |
|
||||||
|
| Refused (schema_incompatible) | PUT mocked 409; steps: Save, Apply changes | refusal dialog with Change Capacity |
|
||||||
|
|
||||||
|
Not checked: "Review with counts and diff" (scope Later, not built; leave it out of `extraSources`). "Field key error" has no board frame: keep it as a documented `skip: 'pending'` with that reason and cover it in Vitest only. Do not hide it.
|
||||||
|
Known visual differences to report, never hide: the Key help copy (Q1) on /schema/new.
|
||||||
|
|
||||||
|
## Manual
|
||||||
|
|
||||||
|
- Real backend, as owner and admin:
|
||||||
|
- Create Events with all six field types and some entries.
|
||||||
|
- Open it from the list. Edit the name and a label. Confirm the review does not open for a name-only edit and does for a field edit.
|
||||||
|
- Lower Capacity's Highest value below an existing entry's value. Confirm the real 409 `schema_incompatible`, the refusal dialog and that nothing changed (reload).
|
||||||
|
- Add a required field with no default (409). Add one with a default (200 and existing entries get it).
|
||||||
|
- Turn Unique on over duplicate values (409). Remove a Choice option that entries use (409). Remove a field and check entries no longer return it.
|
||||||
|
- Create a type through curl with an `icon`, edit it in the SPA, and check the icon is still returned by GET.
|
||||||
|
- Check that `GET /v1/content-type/{key}/entry?page=1&size=5` is accepted as the count request.
|
||||||
|
- Keyboard: Tab order is Name, locked Key (tooltip on focus), Save, Discard, the field list (one stop, arrows move between rows), the inspector, Undo, API preview. Dialogs trap focus and return it to the trigger. Screen reader: the lock states are announced, the live region reads each reorder step, errors are read with their input.
|
||||||
|
- Hover and motion on the lock tooltip, the undo row and the dialogs. Sheet open and close focus return on a real phone.
|
||||||
|
- Real offline: edit, go offline with the review open, reconnect, press Apply.
|
||||||
|
- Reload or close the tab with unsaved edits (not handled by the leave guard): note the browser behaviour.
|
||||||
@@ -0,0 +1,170 @@
|
|||||||
|
Feature: Read-only view of a built-in content type
|
||||||
|
As an owner or admin
|
||||||
|
I want to open a built-in type from the Schema list and read its fields
|
||||||
|
So that I can see the rules RenewCMS applies without being able to change them
|
||||||
|
|
||||||
|
Background:
|
||||||
|
Given the SPA calls the API with relative URLs under /v1 and the "jwt" HttpOnly cookie
|
||||||
|
And GET /v1/builtin-type returns [{key, name, fields}] for owners and admins only
|
||||||
|
And each field is {key, label, type, required, unique, default, min, max, options}
|
||||||
|
And API errors are plain text
|
||||||
|
And the route /schema/:key has meta auth "verified" and title "Schema"
|
||||||
|
And the contentTypes store already exposes builtinItems, builtinStatus and load({builtin: true})
|
||||||
|
And the view takes its data from builtinItems, matched on the route key, and never calls GET /v1/builtin-type/{key}
|
||||||
|
And only owners and admins can use Schema; the SPA decides from the session role, the API still enforces it
|
||||||
|
And a session whose role is neither owner nor admin is a test double for the forbidden states
|
||||||
|
And the built-in types are articles ("Articles"), authors, sites, media and users with 5, 5, 8, 6 and 6 fields in the sample data
|
||||||
|
|
||||||
|
Scenario: A built-in row of the Schema list is a link
|
||||||
|
Given the Schema list is Populated
|
||||||
|
When the user looks at the five built-in rows
|
||||||
|
Then each row is a single link to /schema/<its key> whose accessible name is the type name
|
||||||
|
And the row keeps its lock icon, name, "Built-in" badge, key, field count and a chevron-right at the end
|
||||||
|
And on desktop its "Last updated" cell reads "Managed by RenewCMS"
|
||||||
|
And below 640 px the card of a built-in type shows "<key> · <n> fields" with no "Updated" text and a chevron-right
|
||||||
|
And custom rows are not links and show no chevron
|
||||||
|
|
||||||
|
Scenario: Opening a built-in type from the list
|
||||||
|
Given the Schema list is Populated
|
||||||
|
When the user activates the "Articles" row
|
||||||
|
Then the router navigates to /schema/articles
|
||||||
|
And GET /v1/builtin-type is not called a second time
|
||||||
|
|
||||||
|
Scenario: Read-only view of a built-in type (design state 6, desktop)
|
||||||
|
Given an owner or admin is signed in
|
||||||
|
And GET /v1/builtin-type returns the type "articles" named "Articles" with the fields
|
||||||
|
| label | key | type | required | unique | min | max | default |
|
||||||
|
| Title | title | text | true | false | | 200 | |
|
||||||
|
| Slug | slug | text | true | true | | | |
|
||||||
|
| Body | body | richtext | false | false | | 10000 | |
|
||||||
|
| Online | online | boolean | false | false | | | false |
|
||||||
|
| Published on | published_on | date | false | false | | | |
|
||||||
|
When they open /schema/articles
|
||||||
|
Then the breadcrumb is "Schema" (a link to /schema) then "Articles"
|
||||||
|
And the h1 "Articles" is shown with a lock icon and a "Built-in" badge
|
||||||
|
And an info alert titled "Managed by RenewCMS" says "Articles is a built-in type. You can read its fields here, but you can't edit it, delete it or add fields."
|
||||||
|
And a table has the columns "Label", "Key", "Type", "Rules"
|
||||||
|
And the rows are, in this order
|
||||||
|
| Label | Key | Type | Rules |
|
||||||
|
| Title | title | Text | Required · up to 200 characters |
|
||||||
|
| Slug | slug | Text | Required · unique |
|
||||||
|
| Body | body | Rich text | Up to 10,000 characters |
|
||||||
|
| Online | online | Yes or no | Off by default |
|
||||||
|
| Published on | published_on | Date | – |
|
||||||
|
And each row starts with the icon of its type
|
||||||
|
And the note "Entries of built-in types are managed from their own screens, like Articles and Authors." is shown under the table
|
||||||
|
And there is no "New content type", edit, delete, add field, save or discard action
|
||||||
|
And the keys are shown in the mono style
|
||||||
|
And GET /v1/content-type and GET /v1/builtin-type are each called once
|
||||||
|
|
||||||
|
Scenario: Read-only view of a built-in type on mobile
|
||||||
|
Given the same data and a 390 px wide viewport
|
||||||
|
When they open /schema/articles
|
||||||
|
Then the topbar shows an arrow-left and the title "Articles"
|
||||||
|
And the fields are cards in order, each with the icon box of its type, the label, and the key in mono followed by " · " and the rules
|
||||||
|
And the Type column is not shown
|
||||||
|
And the "Built-in" badge, the alert and the note are shown
|
||||||
|
|
||||||
|
Scenario Outline: Field types show their label and icon
|
||||||
|
Given a built-in field of type "<type>"
|
||||||
|
Then the Type cell reads "<label>" with the icon <icon>
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| type | label | icon |
|
||||||
|
| text | Text | type |
|
||||||
|
| richtext | Rich text | pilcrow |
|
||||||
|
| number | Number | hash |
|
||||||
|
| boolean | Yes or no | toggle-left |
|
||||||
|
| date | Date | calendar |
|
||||||
|
| select | Choice | list |
|
||||||
|
|
||||||
|
Scenario Outline: The Rules cell is derived from the field
|
||||||
|
Given a field of type "<type>" with <settings>
|
||||||
|
Then the Rules cell reads "<rules>"
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| type | settings | rules |
|
||||||
|
| text | required, max 200 | Required · up to 200 characters |
|
||||||
|
| text | required, unique | Required · unique |
|
||||||
|
| richtext | max 10000 | Up to 10,000 characters |
|
||||||
|
| boolean | default false | Off by default |
|
||||||
|
| boolean | default true | On by default |
|
||||||
|
| date | nothing | – |
|
||||||
|
| text | min 3, max 80 (proposed copy) | 3 to 80 characters |
|
||||||
|
| text | min 3 (proposed copy) | At least 3 characters |
|
||||||
|
| number | min 1, max 5000 (proposed copy) | Between 1 and 5000 |
|
||||||
|
| number | min 1 (proposed copy) | At least 1 |
|
||||||
|
| number | max 5000 (proposed copy) | At most 5000 |
|
||||||
|
| select | 3 options (proposed copy) | 3 choices |
|
||||||
|
| text | default "Draft" (proposed copy) | Default: Draft |
|
||||||
|
|
||||||
|
Scenario: Back to the list
|
||||||
|
Given the read-only view is shown
|
||||||
|
When the user activates the "Schema" breadcrumb, or the arrow-left on mobile
|
||||||
|
Then the router navigates to /schema
|
||||||
|
|
||||||
|
Scenario: Deep link and reload load what the view needs
|
||||||
|
Given the user opens /schema/articles as the first page of the session
|
||||||
|
Then the session is resolved, then GET /v1/builtin-type is called once
|
||||||
|
And the view shows the read-only view when it answers 200
|
||||||
|
|
||||||
|
Scenario: Loading
|
||||||
|
Given GET /v1/builtin-type has not answered
|
||||||
|
When an owner opens /schema/articles
|
||||||
|
Then nothing is shown in the content area during the first 150 ms
|
||||||
|
And after 150 ms skeleton rows are shown
|
||||||
|
And the not-found page and the 403 page are not shown
|
||||||
|
|
||||||
|
Scenario Outline: Unknown key
|
||||||
|
Given GET /v1/builtin-type returns the five built-in types
|
||||||
|
When an owner opens <path>
|
||||||
|
Then the page "Content type not found" is shown with "It may have been deleted, or the address may be mistyped."
|
||||||
|
And the URL stays <path> and nothing redirects
|
||||||
|
And no field table is shown
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| path | why |
|
||||||
|
| /schema/unknown | a mistyped key |
|
||||||
|
| /schema/events | a custom type; its builder is a later slice |
|
||||||
|
|
||||||
|
Scenario Outline: Error
|
||||||
|
Given GET /v1/builtin-type <failure>
|
||||||
|
When an owner opens /schema/articles
|
||||||
|
Then an alert shows "Couldn't load content types"
|
||||||
|
And it shows "GET /v1/builtin-type failed. Check your connection and try again."
|
||||||
|
And a "Try again" action is shown
|
||||||
|
And no table is shown
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| failure |
|
||||||
|
| answers 500 |
|
||||||
|
| fails (network) |
|
||||||
|
|
||||||
|
Scenario: Retry recovers
|
||||||
|
Given the view is in the Error state
|
||||||
|
When the user activates "Try again"
|
||||||
|
Then GET /v1/builtin-type is called again
|
||||||
|
And when it answers 200 the read-only view replaces the alert
|
||||||
|
|
||||||
|
Scenario: Forbidden for a user who is not owner or admin
|
||||||
|
Given a verified user whose role is neither owner nor admin is signed in
|
||||||
|
When they open /schema/articles
|
||||||
|
Then the URL stays /schema/articles and nothing redirects
|
||||||
|
And the page shows "You don't have access to Schema"
|
||||||
|
And it shows "Only owners and admins can change content types. You can still add and edit entries from the Content menu."
|
||||||
|
And a "Go to Home" action navigates to /home
|
||||||
|
And GET /v1/builtin-type is never called
|
||||||
|
|
||||||
|
Scenario: The API answers 403
|
||||||
|
Given the session says owner or admin but GET /v1/builtin-type answers 403
|
||||||
|
When they open /schema/articles
|
||||||
|
Then the same "You don't have access to Schema" page is shown
|
||||||
|
|
||||||
|
Scenario: An unverified or signed-out user keeps the existing redirects
|
||||||
|
Given the user is not verified or not signed in
|
||||||
|
When they open /schema/articles
|
||||||
|
Then they are redirected to /register/pending or /login as for any other "verified" route
|
||||||
|
|
||||||
|
Scenario: The list and the view share one load
|
||||||
|
Given the user opens /schema, then /schema/articles, then goes back
|
||||||
|
Then GET /v1/builtin-type and GET /v1/content-type are each called once in the session
|
||||||
@@ -0,0 +1,42 @@
|
|||||||
|
# QA: Read-only view of a built-in type (SPA slice 2)
|
||||||
|
|
||||||
|
Runner: Vitest + Vue Test Utils (`task test:web`). No Go test: there is no backend change.
|
||||||
|
Same pattern as features/schema_list_and_content_nav.qa.md: mock `/v1` through the existing api composable, mount with a test router (routes /schema, /schema/:key) and a resolved session whose role varies. The forbidden cases use a session with an unknown role.
|
||||||
|
|
||||||
|
## Automated
|
||||||
|
|
||||||
|
Fixtures: the five built-in types with the board's sample data; "articles" has the 5 fields of the board (Title, Slug, Body, Online, Published on), the others only need a `fields` array of the right length (5, 5, 8, 6, 6). Three custom types as in slice 1.
|
||||||
|
|
||||||
|
SchemaTable / list (extend SchemaView.spec and the SchemaTable spec):
|
||||||
|
1. Built-in rows are single links (`a` with href /schema/<key>), accessible name = type name, chevron present, "Managed by RenewCMS" in the desktop Last updated cell, no "Updated" text on the mobile card (use `components/__tests__/viewport.ts`).
|
||||||
|
2. Custom rows are not links and have no chevron. Replaces the slice-1 test "rows are not links".
|
||||||
|
3. Activating the "Articles" row navigates to /schema/articles; no second GET /v1/builtin-type.
|
||||||
|
|
||||||
|
Read-only view (new SchemaBuiltinView.spec), one test per state:
|
||||||
|
4. Read-only: owner and admin. Assert the breadcrumb, h1 with lock and "Built-in", alert title and text, columns, the five rows (label, key, type label, rules) in order, the note, and the absence of any new/edit/delete/add/save/discard button. Both /v1 calls made once.
|
||||||
|
5. Mobile: arrow-left + title, cards with key and rules, no Type column.
|
||||||
|
6. Type labels and icons (it.each over the 6 types).
|
||||||
|
7. Rules derivation (it.each over the Examples table of the feature, incl. 10,000 separator, the en dash for empty, and capitalisation of the first part). Cases tagged "proposed copy" are separate it.each rows so a design change touches them only.
|
||||||
|
8. Back: the breadcrumb and the mobile arrow push /schema.
|
||||||
|
9. Deep link: a store in its initial state loads the builtin list once on mount.
|
||||||
|
10. Loading: unresolved promise, fake timers. Nothing at 149 ms, skeleton at 150 ms, no not-found or 403 page. A fast response never shows the skeleton.
|
||||||
|
11. Unknown key: it.each over /schema/unknown, /schema/events. Assert the "Content type not found" page copy, URL unchanged, no table.
|
||||||
|
12. Error: 500 and network failure. Assert the alert copy ("GET /v1/builtin-type failed. ..."), "Try again", no table. Retry then returns 200 and the view replaces the alert (second call made).
|
||||||
|
13. Forbidden: unknown role gives the 403 page copy, "Go to Home" navigates to /home, URL stays /schema/articles, builtin-type never called. Plus a case where builtin-type answers 403 for an owner.
|
||||||
|
14. Shared load: navigating /schema -> /schema/articles -> back calls each list endpoint once.
|
||||||
|
|
||||||
|
Router and guard:
|
||||||
|
15. `/schema/:key` is registered with auth "verified" and title "Schema". Unverified and signed-out users get the existing redirects (extend routerGuard.spec). /schema (exact) is unchanged.
|
||||||
|
|
||||||
|
## Visual (task visual:check -- schema)
|
||||||
|
|
||||||
|
Run `task visual:check -- schema`; every capture within 10 % at desktop and mobile, light and dark. Nothing is clock-sensitive.
|
||||||
|
- Replace `skip: 'pending'` of state 6 in `web/visual/states.ts` with a real setup: open /schema/articles. Mock GET /v1/session, GET /v1/content-type (the 3 custom types), GET /v1/builtin-type with the five types. "articles" must carry the board's 5 fields: Title (text, required, max 200), Slug (text, required, unique), Body (richtext, max 10000), Online (boolean, default false), Published on (date, none). Field counts 5, 5, 8, 6, 6. Keys in the mock follow the board's sample text ("articles" etc.), since the view resolves the key from data. Use the sidebar mock of states 1-5 and mock every other /v1 call the screen makes.
|
||||||
|
- States 1 to 5 must still pass after the list-row change (chevron on built-in rows, "Managed by RenewCMS" in Last updated). If the board and the slice-1 rendering differ on custom rows' chevron, report it, do not fix it silently.
|
||||||
|
- Loading, Error, Unknown key and Forbidden-on-detail have no board frame: Vitest only, not in the visual check.
|
||||||
|
|
||||||
|
## Manual
|
||||||
|
|
||||||
|
- Keyboard: Tab order list rows (each row one stop), Enter on a focused built-in row opens it; visible focus ring; the breadcrumb and back arrow are reachable.
|
||||||
|
- Hover on a built-in row, and focus/hover motion.
|
||||||
|
- Real backend: log in as owner and as admin, open each of the five built-in rows, compare the rendered Rules with the actual fields returned by GET /v1/builtin-type (the board's rules are illustrative), and confirm a plain user gets the 403 page on /schema/article.
|
||||||
@@ -0,0 +1,194 @@
|
|||||||
|
Feature: Schema list and content navigation in the back-office
|
||||||
|
As an owner or admin
|
||||||
|
I want to see the custom and built-in content types on a Schema screen
|
||||||
|
And as any verified user I want a Content menu with one link per custom type
|
||||||
|
So that I can reach the content types I manage and write entries for
|
||||||
|
|
||||||
|
Background:
|
||||||
|
Given the SPA calls the API with relative URLs under /v1 and the "jwt" HttpOnly cookie
|
||||||
|
And GET /v1/content-type returns a JSON array of {id, key, name, icon, fields, created_at, updated_at}
|
||||||
|
And GET /v1/builtin-type returns a JSON array of {key, name, fields}, for owners and admins only
|
||||||
|
And API errors are plain text
|
||||||
|
And the session store exposes the role of the signed-in user, and only owner and admin exist today
|
||||||
|
And a session whose role is neither owner nor admin (absent or unknown) is a test double for the forbidden states
|
||||||
|
And the Schema screen is the route /schema with meta auth "verified", title "Schema"
|
||||||
|
And only owners and admins can use Schema; the SPA decides from the session role, the API still enforces it
|
||||||
|
And the typed API client exposes listContentTypes() and listBuiltinTypes()
|
||||||
|
And a content types store loads them once per session and exposes loading, error and items
|
||||||
|
And this slice does not add the Vitest runner, it already exists (task test:web)
|
||||||
|
|
||||||
|
Scenario Outline: The Schema entry is shown to owners and admins only
|
||||||
|
Given a verified user with role "<role>" is signed in
|
||||||
|
When the back-office shell renders
|
||||||
|
Then the sidebar <schema_entry> a "Schema" entry linking to /schema, with the "shapes" icon, placed after "Users"
|
||||||
|
And no existing nav item changed
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| role | schema_entry |
|
||||||
|
| owner | shows |
|
||||||
|
| admin | shows |
|
||||||
|
| unknown | does not show |
|
||||||
|
|
||||||
|
Scenario: The Content group lists one link per custom type
|
||||||
|
Given a verified user is signed in
|
||||||
|
And GET /v1/content-type returns the types "events" (Events), "recipes" (Recipes) and "press-mentions" (Press mentions)
|
||||||
|
When the back-office shell renders
|
||||||
|
Then the sidebar shows a "Content" group under the main items
|
||||||
|
And the group contains three links, in the API order, to /content/events, /content/recipes and /content/press-mentions
|
||||||
|
And each row shows the type name
|
||||||
|
And the row of the type matching the current route /content/:key is marked as the current page
|
||||||
|
|
||||||
|
Scenario Outline: Each type shows its icon, or the default icon
|
||||||
|
Given a custom type "recipes" with icon <icon>
|
||||||
|
When the sidebar renders
|
||||||
|
Then the row for "recipes" shows <shown>
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| icon | shown |
|
||||||
|
| "chef-hat" | the icon i-lucide-chef-hat (in bundle) |
|
||||||
|
| null | the default icon "files" |
|
||||||
|
| "not-bundled" | the default icon "files" |
|
||||||
|
|
||||||
|
Scenario: A long type name is truncated in one line and keeps its full name available
|
||||||
|
Given a custom type named "Frequently asked questions and answers"
|
||||||
|
When the sidebar renders on desktop
|
||||||
|
Then the label is cut with an ellipsis on one line and does not widen the sidebar
|
||||||
|
And the full name is available in a tooltip and as the link's accessible name
|
||||||
|
|
||||||
|
Scenario: With more than 5 types the desktop group shows 5 and the selected one
|
||||||
|
Given 14 custom types and the current route is /content/<selected>
|
||||||
|
When the sidebar renders on desktop
|
||||||
|
Then the group shows the first 5 types, plus the selected type if it is not among them
|
||||||
|
And a "Show all 14" action follows
|
||||||
|
When the user activates "Show all 14"
|
||||||
|
Then all 14 types are listed
|
||||||
|
|
||||||
|
Scenario: With 5 types or fewer there is no "Show all"
|
||||||
|
Given 5 custom types
|
||||||
|
When the sidebar renders
|
||||||
|
Then all 5 are listed and no "Show all" action appears
|
||||||
|
|
||||||
|
Scenario: On mobile the group is one collapsed row in the drawer
|
||||||
|
Given 14 custom types and a 390 px wide viewport
|
||||||
|
When the user opens the drawer
|
||||||
|
Then the Content group shows one collapsed row "All content types" with the count 14
|
||||||
|
When the user expands it
|
||||||
|
Then the 14 types are listed with rows 44 px high
|
||||||
|
|
||||||
|
Scenario: No custom type hides the group
|
||||||
|
Given GET /v1/content-type returns []
|
||||||
|
When the shell renders
|
||||||
|
Then there is no Content group and no empty placeholder in the sidebar
|
||||||
|
|
||||||
|
Scenario Outline: A failing content type request does not break the shell
|
||||||
|
Given GET /v1/content-type <failure>
|
||||||
|
When the shell renders
|
||||||
|
Then the Content group is not shown
|
||||||
|
And the rest of the sidebar and the page render normally
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| failure |
|
||||||
|
| answers 500 |
|
||||||
|
| fails (network) |
|
||||||
|
|
||||||
|
Scenario: The Content group is loaded once for the whole session
|
||||||
|
Given the user navigates between several back-office screens
|
||||||
|
Then GET /v1/content-type is called once and the list is shared by the sidebar and the Schema list
|
||||||
|
|
||||||
|
Scenario: Populated list
|
||||||
|
Given an owner or admin is signed in
|
||||||
|
And GET /v1/content-type returns three types
|
||||||
|
And GET /v1/builtin-type returns articles, authors, sites, media and users
|
||||||
|
When they open /schema
|
||||||
|
Then the page shows the title "Schema" and the text "Content types and the fields they are made of."
|
||||||
|
And a "New content type" action is enabled
|
||||||
|
And a table has the columns "Name", "Key", "Fields", "Last updated"
|
||||||
|
And each custom row shows name, key, the number of fields and the updated date as an absolute date, using the board's sample data
|
||||||
|
And after the custom rows come the five built-in rows, each with a lock icon and a "Built-in" badge
|
||||||
|
And a built-in row shows its field count from the length of fields and "Managed by RenewCMS" as Last updated on desktop (no Updated text on mobile)
|
||||||
|
And the text "Built-in types are managed by RenewCMS. You can read their fields, but not change them." is shown
|
||||||
|
And the summary "3 content types · 5 built-in" is shown
|
||||||
|
And below 640 px the table is a list of cards with the same content
|
||||||
|
|
||||||
|
Scenario: Loading
|
||||||
|
Given GET /v1/content-type has not answered
|
||||||
|
When an owner opens /schema
|
||||||
|
Then no skeleton is shown during the first 150 ms
|
||||||
|
And after 150 ms skeleton rows are shown
|
||||||
|
And "New content type" is disabled
|
||||||
|
And the 403 page and the empty state are not shown
|
||||||
|
|
||||||
|
Scenario: Empty, no custom type yet
|
||||||
|
Given GET /v1/content-type returns []
|
||||||
|
When an owner opens /schema
|
||||||
|
Then the empty state "No content types yet" is shown with the text "Create a content type to manage your own kind of content, like events or recipes. The built-in types stay as they are."
|
||||||
|
And a "New content type" action is shown and enabled
|
||||||
|
And the five built-in types are still listed below
|
||||||
|
|
||||||
|
Scenario Outline: Error
|
||||||
|
Given GET /v1/content-type <failure>
|
||||||
|
When an owner opens /schema
|
||||||
|
Then an alert shows "Couldn't load content types"
|
||||||
|
And it shows "GET /v1/content-type failed. Check your connection and try again."
|
||||||
|
And a "Try again" action is shown
|
||||||
|
And no table is shown
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| failure |
|
||||||
|
| answers 500 |
|
||||||
|
| fails (network) |
|
||||||
|
|
||||||
|
Scenario: Retry recovers
|
||||||
|
Given the list is in the Error state
|
||||||
|
When the user activates "Try again"
|
||||||
|
Then the skeleton rows show after 150 ms and GET /v1/content-type is called again
|
||||||
|
And when it answers 200 the Populated state replaces the alert
|
||||||
|
|
||||||
|
Scenario: Forbidden for a user who is not owner or admin
|
||||||
|
Given a verified user whose role is neither owner nor admin is signed in
|
||||||
|
When they open /schema directly
|
||||||
|
Then the URL stays /schema and nothing redirects
|
||||||
|
And the page shows "You don't have access to Schema"
|
||||||
|
And it shows "Only owners and admins can change content types. You can still add and edit entries from the Content menu."
|
||||||
|
And a "Go to Home" action navigates to /home
|
||||||
|
And GET /v1/builtin-type is never called
|
||||||
|
|
||||||
|
Scenario: The API answers 403 for the list
|
||||||
|
Given the session says owner or admin but GET /v1/builtin-type answers 403
|
||||||
|
When they open /schema
|
||||||
|
Then the same "You don't have access to Schema" page is shown
|
||||||
|
|
||||||
|
Scenario: Built-in types fail to load while custom types load
|
||||||
|
Given GET /v1/content-type answers 200 and GET /v1/builtin-type answers 500
|
||||||
|
When an owner opens /schema
|
||||||
|
Then the Error state is shown
|
||||||
|
|
||||||
|
Scenario: An unverified or signed-out user keeps the existing redirects
|
||||||
|
Given the user is not verified or not signed in
|
||||||
|
When they open /schema
|
||||||
|
Then they are redirected to /register/pending or /login as for any other "verified" route
|
||||||
|
|
||||||
|
Scenario: New content type
|
||||||
|
Given the list is Populated or Empty
|
||||||
|
When an owner activates "New content type"
|
||||||
|
Then the router navigates to /schema/new (the builder is a later slice)
|
||||||
|
|
||||||
|
Scenario: Custom rows are not links in this slice
|
||||||
|
Given the list is Populated
|
||||||
|
Then custom rows do not navigate (the editor is a later slice)
|
||||||
|
And built-in rows are links, see schema_builtin_view.feature
|
||||||
|
|
||||||
|
Scenario Outline: The typed client maps responses
|
||||||
|
When the client calls <call>
|
||||||
|
And the API answers <answer>
|
||||||
|
Then it <result>
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| call | answer | result |
|
||||||
|
| listContentTypes | 200 with icon null | returns the types, icon typed string or null |
|
||||||
|
| listContentTypes | 200 [] | returns an empty array |
|
||||||
|
| listContentTypes | 500 plain text | rejects with an error carrying status 500 |
|
||||||
|
| listContentTypes | network failure | rejects with a network error |
|
||||||
|
| listBuiltinTypes | 200 | returns {key, name, fields} items |
|
||||||
|
| listBuiltinTypes | 403 plain text | rejects with an error carrying status 403 |
|
||||||
|
| listBuiltinTypes | 500 plain text | rejects with an error carrying status 500 |
|
||||||
@@ -0,0 +1,48 @@
|
|||||||
|
# QA: Schema list and content navigation (SPA slice 1)
|
||||||
|
|
||||||
|
Runner: Vitest + Vue Test Utils (already installed, `task test:web`). No Go test: there is no backend change.
|
||||||
|
Mock `/v1` through the existing api composable pattern used by the other view specs. Mount the shell (DashboardShell) with a test router and a resolved session whose role varies. Only owner and admin exist, so the forbidden cases use a session with an unknown role.
|
||||||
|
|
||||||
|
## Automated
|
||||||
|
|
||||||
|
Fixtures: three custom types (events, recipes, press-mentions) with the board's sample data for names, field counts and dates, at least one with icon "chef-hat" and one with icon null; five built-in types (articles, authors, sites, media, users) with fields arrays.
|
||||||
|
|
||||||
|
Schema list, one test per design state (screens/schema.md section 1):
|
||||||
|
1. Populated: both calls 200, role owner and role admin. Assert the title, subtitle, columns, custom rows before built-in rows, lock + "Built-in" badge on 5 rows, the built-in note, the summary "3 content types · 5 built-in", enabled "New content type". Assert the card layout below 640 px.
|
||||||
|
2. Loading: unresolved promise with fake timers. No skeleton at 149 ms, skeleton at 150 ms, "New content type" disabled. A fast response (under 150 ms) never shows skeletons.
|
||||||
|
3. Empty: content-type returns []. Assert the empty state copy, action, and the 5 built-in rows still listed.
|
||||||
|
4. Error: 500 and network failure. Assert the alert copy, the "Try again" action, no table. Then retry returns 200 and the Populated state replaces the alert (the second call is made).
|
||||||
|
5. Forbidden: unknown role. Assert the 403 page copy, "Go to Home" navigates to /home, URL stays /schema, `GET /v1/builtin-type` never called. Add a case where builtin-type answers 403 for an owner.
|
||||||
|
6. builtin-type 500 with content-type 200: Error state.
|
||||||
|
7. "New content type" pushes /schema/new.
|
||||||
|
|
||||||
|
Sidebar:
|
||||||
|
8. Schema entry visibility for owner, admin and unknown role; position after Users.
|
||||||
|
9. Content group: three links with the right hrefs, current row marked, hidden on empty, hidden on 500 and on network failure, no second request across route changes.
|
||||||
|
10. Icons: "chef-hat" in the bundle renders it, null and an unbundled name render the default "files" icon.
|
||||||
|
11. Truncation: label has the truncate classes, full name in tooltip and accessible name.
|
||||||
|
12. More than 5 types: 14 types and a selected type beyond the fifth. Assert 5 + the selected row + "Show all 14"; after activating it all 14 show. With 5 types, no "Show all".
|
||||||
|
13. Mobile (viewport helper in `components/__tests__/viewport.ts`): drawer shows one collapsed row "All content types" with count 14, expands to 14 rows.
|
||||||
|
|
||||||
|
Router and guard:
|
||||||
|
14. `/schema` is registered with auth "verified" and title "Schema"; unverified and signed-out users get the existing redirects (extend routerGuard.spec).
|
||||||
|
|
||||||
|
Client and store:
|
||||||
|
15. Typed client calls (the Examples table in the feature) incl. icon string|null typing, 403, 500, network failure.
|
||||||
|
16. Store loads once, shares state between the sidebar and the Schema list, retry reloads.
|
||||||
|
|
||||||
|
## Visual (task visual:check -- schema)
|
||||||
|
|
||||||
|
Run `task visual:check -- schema`, every capture within 10 % at desktop and mobile, light and dark. States to set up in `web/visual/states.ts`, reusing the board's sample data (names, keys, field counts, dates, counts "3 content types · 5 built-in" taken from SchemaFrame.dc.html):
|
||||||
|
- 1 Populated, 2 Loading, 3 Empty, 4 Error, 5 Forbidden (403).
|
||||||
|
- State 6 (built-in read-only view) is covered by schema_builtin_view.qa.md.
|
||||||
|
- None of these is clock-sensitive; if the Last updated cell turns out to be relative on the board, mark it `skip: 'clock-sensitive'`.
|
||||||
|
- Mock every `/v1` call the screen makes, including the sidebar's GET /v1/content-type.
|
||||||
|
- The sidebar group and drawer frames belong to the later `content` group.
|
||||||
|
|
||||||
|
## Manual
|
||||||
|
|
||||||
|
- Keyboard: tab order through sidebar, "Show all", table and "New content type"; visible focus rings.
|
||||||
|
- Tooltip on a truncated name on hover and on focus.
|
||||||
|
- Hover and motion of the drawer expand/collapse row.
|
||||||
|
- With a real backend: log in as owner and admin and confirm the sidebar and /schema; create a type with icon "chef-hat" via the API and see it appear.
|
||||||
@@ -0,0 +1,190 @@
|
|||||||
|
Feature: Sessions, uploads and stored personal data are hardened against forgery, replay and over-retention
|
||||||
|
|
||||||
|
As the operator of a RenewCMS instance
|
||||||
|
I want cross-site writes refused, logged-out sessions dead, weak secrets rejected, mail encrypted,
|
||||||
|
photo metadata removed and stale personal data deleted on a schedule
|
||||||
|
So that the instance meets the security-of-processing and storage-limitation duties of the GDPR
|
||||||
|
(art. 5(1)(c), 5(1)(e), 25 and 32) without the operator having to configure anything
|
||||||
|
|
||||||
|
Background:
|
||||||
|
Given api.InitRoutes wraps every route in middleware.CrossOriginProtection(settings.PublicURL),
|
||||||
|
built on the standard library's http.CrossOriginProtection, after CORS and before any router
|
||||||
|
And the jwt cookie is set and cleared with HttpOnly, SameSite=Lax, Path "/" and, in
|
||||||
|
production, Secure
|
||||||
|
|
||||||
|
Rule: Cross-site writes are refused
|
||||||
|
|
||||||
|
Scenario Outline: An unsafe cross-origin browser request is refused before any handler runs
|
||||||
|
Given a request <method> /v1/user/invite carrying the jwt cookie and the headers <headers>
|
||||||
|
Then the response is 403 with the body "Cross-origin requests are not allowed."
|
||||||
|
And the handler never runs
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| method | headers |
|
||||||
|
| POST | Sec-Fetch-Site: cross-site, Origin: https://evil.example |
|
||||||
|
| POST | Sec-Fetch-Site: same-site, Origin: https://blog.example.com |
|
||||||
|
| DELETE | Sec-Fetch-Site: cross-site, Origin: https://evil.example |
|
||||||
|
| POST | Origin: https://evil.example (an older browser, no Sec-Fetch-Site) |
|
||||||
|
|
||||||
|
Scenario Outline: Requests that cannot be forged are let through
|
||||||
|
Given a request <request>
|
||||||
|
Then the handler runs
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| request |
|
||||||
|
| POST with Sec-Fetch-Site: same-origin |
|
||||||
|
| POST with Sec-Fetch-Site: none |
|
||||||
|
| POST with neither Sec-Fetch-Site nor Origin (a non-browser client) |
|
||||||
|
| GET, HEAD or OPTIONS from any origin |
|
||||||
|
| POST from another origin carrying an Authorization header (an API key or bearer jwt) |
|
||||||
|
| POST whose Origin is the origin of PUBLIC_URL while a proxy rewrote Host |
|
||||||
|
|
||||||
|
Scenario: A PUBLIC_URL that cannot be parsed still leaves the protection on
|
||||||
|
Given PUBLIC_URL is not a URL
|
||||||
|
When a cross-site POST arrives
|
||||||
|
Then it is refused with 403
|
||||||
|
|
||||||
|
Rule: Logging out kills the session server-side
|
||||||
|
|
||||||
|
Scenario: Every session token carries a unique id and an expiry
|
||||||
|
When authtoken.Encode issues a token without "jti" or "exp"
|
||||||
|
Then it adds a random "jti" (crypto/rand.Text) and "exp" 24 hours after "iat"
|
||||||
|
And authtoken.Decode refuses a token without "exp" and a token whose "jti" is not a string
|
||||||
|
with ErrInvalid
|
||||||
|
|
||||||
|
Scenario: The token presented at logout is refused afterwards, other sessions are not
|
||||||
|
Given alice logged in twice, getting tokens A and B
|
||||||
|
When she sends POST /v1/auth/logout with token A
|
||||||
|
Then the response is 200 and clears the cookie
|
||||||
|
And a session.Revocation for A's jti, expiring at A's exp, is stored in revoked_sessions
|
||||||
|
And GET /v1/auth/me with token A answers 401 and with token B answers 200
|
||||||
|
|
||||||
|
Scenario: Logout without a valid session stores nothing
|
||||||
|
When POST /v1/auth/logout arrives without a cookie, or with an expired or revoked one
|
||||||
|
Then the response is 200, the cookie is cleared and nothing is stored
|
||||||
|
|
||||||
|
Scenario: A revocation that cannot be stored is reported
|
||||||
|
Given the revoked_sessions store refuses writes
|
||||||
|
When alice logs out
|
||||||
|
Then the response is 500 and the cookie is still cleared
|
||||||
|
|
||||||
|
Scenario: A token whose revocation cannot be checked is refused
|
||||||
|
Given the revoked_sessions store cannot be read
|
||||||
|
Then any request authenticated by a jwt is treated as unauthenticated
|
||||||
|
|
||||||
|
Rule: Only a current session sees drafts
|
||||||
|
|
||||||
|
Scenario: A verified user's stale token reads like an anonymous visitor
|
||||||
|
Given alice is verified and her token_version is 1
|
||||||
|
When GET /v1/article/ arrives with a token carrying token_version 0
|
||||||
|
Then only online articles are listed
|
||||||
|
|
||||||
|
Rule: Passwords fit bcrypt
|
||||||
|
|
||||||
|
Scenario Outline: A password over 72 bytes is refused with 400
|
||||||
|
When <request> carries a password of 73 bytes, or of 37 two-byte characters
|
||||||
|
Then the response is 400 with the body "The password must be 72 bytes or fewer."
|
||||||
|
And nothing is created or changed
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| request |
|
||||||
|
| POST /v1/auth/register |
|
||||||
|
| POST /v1/auth/password-reset/confirm (valid code) |
|
||||||
|
| POST /v1/auth/invite/accept (valid code) |
|
||||||
|
|
||||||
|
Scenario: A wrong reset code still wins over a long password
|
||||||
|
When POST /v1/auth/password-reset/confirm carries a wrong code and a 73-byte password
|
||||||
|
Then the response is 403 as for any wrong code
|
||||||
|
|
||||||
|
Rule: The server refuses to start with a guessable signing secret
|
||||||
|
|
||||||
|
Scenario Outline: A weak JWT_SECRET stops startup
|
||||||
|
Given JWT_SECRET is <value>
|
||||||
|
Then config.NewSettingsFromEnv fails with config.ErrWeakJWTSecret
|
||||||
|
And the message says to generate one with `openssl rand -hex 32`
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| value |
|
||||||
|
| empty |
|
||||||
|
| shorter than 32 bytes |
|
||||||
|
| "change-me-to-a-long-random-string" |
|
||||||
|
| "replace-with-output-of-openssl-rand-hex-32" |
|
||||||
|
|
||||||
|
Rule: Mail is never sent in clear text over the network by default
|
||||||
|
|
||||||
|
Scenario: A non-loopback SMTP server without STARTTLS is refused
|
||||||
|
Given SMTP_PORT is not 465, SMTP_HOST is not localhost, 127.0.0.1 or ::1, and the server does
|
||||||
|
not offer STARTTLS
|
||||||
|
When a mail is sent
|
||||||
|
Then delivery fails before MAIL FROM with an error naming SMTP_ALLOW_INSECURE
|
||||||
|
|
||||||
|
Scenario: The operator can opt out for a trusted relay
|
||||||
|
Given SMTP_ALLOW_INSECURE is "true"
|
||||||
|
When a mail is sent to such a server without credentials
|
||||||
|
Then it is delivered in clear text
|
||||||
|
And credentials are still never sent in clear text
|
||||||
|
|
||||||
|
Rule: Uploaded photos lose their metadata
|
||||||
|
|
||||||
|
Scenario Outline: Metadata is removed before the bytes are stored, hashed or measured for size
|
||||||
|
When a <format> image is uploaded
|
||||||
|
Then the stored bytes no longer contain <removed>
|
||||||
|
And they still contain <kept>
|
||||||
|
And the image's size and sha256 describe the stored bytes, and its pixels are unchanged
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| format | removed | kept |
|
||||||
|
| JPEG | EXIF, XMP, IPTC (APP13), comments, MPF and other APPn segments, trailing images | JFIF, ICC profile, Adobe |
|
||||||
|
| PNG | eXIf, tEXt, zTXt, iTXt, tIME and data after IEND | every other chunk |
|
||||||
|
| WebP | EXIF and XMP chunks (their VP8X flags cleared) and data after the RIFF size | every other chunk |
|
||||||
|
|
||||||
|
Scenario: A rotated photo keeps only its orientation
|
||||||
|
Given an uploaded JPEG, PNG or WebP whose EXIF orientation is 2 to 8
|
||||||
|
Then the stored file carries a minimal EXIF block holding only that orientation (after SOI or
|
||||||
|
JFIF for JPEG, after IHDR for PNG, at the end with the EXIF flag set for WebP)
|
||||||
|
|
||||||
|
Scenario: An image whose container cannot be walked is refused
|
||||||
|
When a JPEG, PNG or WebP with a truncated header, a chunk longer than the file or no IEND
|
||||||
|
(PNG) is uploaded
|
||||||
|
Then the upload fails with image.ErrImageUnreadable and nothing is stored
|
||||||
|
And a JPEG cut off inside its scan data is kept as it is
|
||||||
|
|
||||||
|
Scenario: SVG is stored as uploaded
|
||||||
|
When an SVG is uploaded
|
||||||
|
Then its bytes are stored unchanged
|
||||||
|
|
||||||
|
Rule: Stale personal data is deleted on a schedule
|
||||||
|
|
||||||
|
Scenario: The retention job runs hourly and logs only when it removed something
|
||||||
|
Given scheduler.NewSystemRetentionRunner runs useCases.EnforceRetentionUseCase a minute after
|
||||||
|
startup and then every hour
|
||||||
|
When a run removes something
|
||||||
|
Then the log reads "scheduler: personal data retention completed: revoked_sessions=<n>
|
||||||
|
unverified_users=<n> invites=<n>"
|
||||||
|
And a run that removes nothing logs nothing, and a failed run logs "... failed: <error>"
|
||||||
|
|
||||||
|
Scenario Outline: What is removed
|
||||||
|
Given <record>
|
||||||
|
Then the retention job <outcome>
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| record | outcome |
|
||||||
|
| a revoked session whose exp has passed | deletes it |
|
||||||
|
| an unverified account whose verification code expired more than 7 days ago | deletes it |
|
||||||
|
| an unverified account without a code expiry created more than 7 days ago | deletes it |
|
||||||
|
| an invite that expired more than 30 days ago | deletes it |
|
||||||
|
| an invite accepted more than 30 days ago | deletes it |
|
||||||
|
| a verified account, a pending invite or an account still inside its 7 days | keeps it |
|
||||||
|
|
||||||
|
Scenario: A failure stops the run and keeps the counts of what was done
|
||||||
|
Given deleting a user fails
|
||||||
|
Then the run returns the error with the sessions already purged counted and touches no invite
|
||||||
|
|
||||||
|
Rule: The back office loads nothing from third parties
|
||||||
|
|
||||||
|
Scenario: Fonts are bundled
|
||||||
|
Given the SPA's fonts (IBM Plex Sans, IBM Plex Mono, Source Serif 4) live in
|
||||||
|
web/src/assets/fonts with their OFL licences
|
||||||
|
Then the Content-Security-Policy allows "font-src 'self'" and "style-src 'self'
|
||||||
|
'unsafe-inline'" with no Google Fonts host
|
||||||
|
And loading the back office sends no request to fonts.googleapis.com or fonts.gstatic.com
|
||||||
@@ -0,0 +1,84 @@
|
|||||||
|
# QA: security and privacy hardening
|
||||||
|
|
||||||
|
Everything below runs in `task test` (package `test`, `-tags nofrontend`) unless marked manual.
|
||||||
|
|
||||||
|
## Cross-origin protection and cookie flags
|
||||||
|
|
||||||
|
1. `test/cross_origin_protection_http_test.go`: wrap a counting handler in
|
||||||
|
`middleware.CrossOriginProtection("https://cms.example.com")`.
|
||||||
|
- Refused with 403 and `apperr.CrossOriginErrorMessage`, handler not reached: a cross-site POST, a
|
||||||
|
same-site POST from `https://blog.example.com`, a cross-site DELETE, and a POST with only
|
||||||
|
`Origin: https://evil.example`.
|
||||||
|
- Allowed: same-origin POST, `Sec-Fetch-Site: none`, no headers, cross-site GET and OPTIONS, a
|
||||||
|
cross-site POST with `Authorization: Bearer rcms_key`, and a POST whose `Origin` is the public
|
||||||
|
URL while `Host` is `127.0.0.1:8080`.
|
||||||
|
- With `PUBLIC_URL` `::not a url`, a cross-site POST is still 403.
|
||||||
|
2. `test/session_revocation_http_test.go` drives `api.InitRoutes`: the login cookie is HttpOnly,
|
||||||
|
Secure and `SameSite=Lax`, and a cross-site `POST /v1/auth/logout` is 403 and revokes nothing.
|
||||||
|
|
||||||
|
## Session revocation
|
||||||
|
|
||||||
|
3. `test/authtoken_test.go` (`TestAuthTokenRevocation`, `TestAuthTokenDecodeRejections`): distinct
|
||||||
|
`jti` per token; explicit `jti` kept; a revoked token gives `ErrRevoked` and is stored until its
|
||||||
|
`exp`; other tokens stay valid; store read failure gives `ErrInvalid`; store write failure is
|
||||||
|
returned by `Revoke`; no `jti` is a no-op; no `exp` refuses; tokens without `exp` or with a
|
||||||
|
non-string `jti` are refused by `Decode`.
|
||||||
|
4. `TestSessionRevocationUseCase`: an already-expired session is not stored; an empty or 65-byte id
|
||||||
|
is `session.ErrInvalidSessionID`; 64 bytes is accepted.
|
||||||
|
5. `TestRevokedSessionRepository` on a migrated SQLite file: revoking twice is harmless,
|
||||||
|
`DeleteExpired(now)` removes rows whose `expires_at <= now` and reports the count.
|
||||||
|
6. `TestLogoutRevokesTheSession` through `api.InitRoutes`: two logins, logout with the first, `/me`
|
||||||
|
with it is 401 and with the second is 200; logout without a cookie is 200 and stores nothing;
|
||||||
|
a failing write gives 500 with the cookie cleared; a failing read makes `/me` 401.
|
||||||
|
7. `test/verified_account_required_http_test.go`: a verified user whose `token_version` moved on
|
||||||
|
only sees online articles.
|
||||||
|
|
||||||
|
## Passwords
|
||||||
|
|
||||||
|
8. `test/password_length_limit_test.go`: 72 bytes accepted, 73 bytes and 37 × "é" refused by
|
||||||
|
`user.ValidatePassword`; register, reset (valid code) and invite accept answer 400 with
|
||||||
|
`apperr.PasswordTooLongErrorMessage` and change nothing; a wrong reset code still answers 403.
|
||||||
|
9. `test/hasher_test.go`: an unknown username compares against a decoy hash once per attempt and
|
||||||
|
hashes the decoy once.
|
||||||
|
|
||||||
|
## Configuration and mail
|
||||||
|
|
||||||
|
10. `test/runtime_settings_from_env_test.go`: empty, short, 31-byte and both example
|
||||||
|
`JWT_SECRET` values fail with `config.ErrWeakJWTSecret` and mention `openssl rand -hex 32`;
|
||||||
|
32 bytes passes. `SMTP_ALLOW_INSECURE` reads `""`/`false` as false, `true`/`TRUE` as true, and
|
||||||
|
`maybe` fails naming the variable.
|
||||||
|
11. `test/smtp_mailer_test.go` against the fake server on `127.0.0.2`: no STARTTLS and no opt-out
|
||||||
|
fails before `MAIL FROM` naming `SMTP_ALLOW_INSECURE`; with the opt-out the message is
|
||||||
|
delivered in clear text; with the opt-out and credentials, nothing is sent.
|
||||||
|
|
||||||
|
## Upload metadata
|
||||||
|
|
||||||
|
12. `test/image_metadata_stripping_test.go` builds JPEG, PNG and WebP files carrying a GPS-like
|
||||||
|
marker in EXIF, XMP, IPTC, comments, text chunks, MPF and trailing data. Assert the marker is
|
||||||
|
gone, ICC is kept, pixels decode identically, the orientation-only EXIF appears only when the
|
||||||
|
orientation is not 1 and sits in the documented place, WebP flags and RIFF size are correct,
|
||||||
|
a plain WebP and an SVG come back unchanged, and each malformed container is
|
||||||
|
`ErrImageUnreadable`.
|
||||||
|
13. `TestUploadStoresTheStrippedImage`: the stored bytes carry no marker and `Size`/`SHA256` match
|
||||||
|
them. `TestUploadRefusesAnImageWhoseContainerIsBroken`: nothing is stored.
|
||||||
|
|
||||||
|
## Retention
|
||||||
|
|
||||||
|
14. `test/personal_data_retention_test.go`: the user and invite rules at their boundaries; one run
|
||||||
|
over a seeded world removes exactly one expired revocation, one abandoned account and two
|
||||||
|
invites; a second run removes nothing; a session store failure touches nothing else; a user
|
||||||
|
or invite deletion failure returns the partial counts; the runner logs counts only when
|
||||||
|
something was removed and logs failures.
|
||||||
|
|
||||||
|
## Fonts
|
||||||
|
|
||||||
|
15. `test/security_headers_test.go`: the CSP contains `font-src 'self';` and no Google host.
|
||||||
|
16. Manual: `task build:web`, open the back office with the network panel; no request leaves for
|
||||||
|
`fonts.googleapis.com` or `fonts.gstatic.com`, and `task visual:check -- log-in` passes.
|
||||||
|
|
||||||
|
## Manual verification
|
||||||
|
|
||||||
|
- Behind the real reverse proxy, log in, copy the `jwt` cookie, log out, then replay the cookie
|
||||||
|
with `curl`: `/v1/auth/me` answers 401.
|
||||||
|
- With an SMTP relay that lacks STARTTLS on a non-loopback host, sending fails until
|
||||||
|
`SMTP_ALLOW_INSECURE=true` is set.
|
||||||
@@ -10,7 +10,7 @@ Feature: The rate limiter keys on the real connection address, trusting a forwar
|
|||||||
Background:
|
Background:
|
||||||
Given POST /v1/auth/login and POST /v1/auth/password-reset are each wrapped, inside
|
Given POST /v1/auth/login and POST /v1/auth/password-reset are each wrapped, inside
|
||||||
NewAuthRouter, by a middleware that runs before RateLimiter (api/middleware/rateLimit.go),
|
NewAuthRouter, by a middleware that runs before RateLimiter (api/middleware/rateLimit.go),
|
||||||
which keys its counters on r.RemoteAddr
|
which keys its counters on the host portion of r.RemoteAddr, never on its source port
|
||||||
And this slice replaces chimiddleware.RealIP on those two route groups with
|
And this slice replaces chimiddleware.RealIP on those two route groups with
|
||||||
TrustedProxyRealIP(trustedProxies []string) func(http.Handler) http.Handler
|
TrustedProxyRealIP(trustedProxies []string) func(http.Handler) http.Handler
|
||||||
(api/middleware/trustedProxyRealIP.go)
|
(api/middleware/trustedProxyRealIP.go)
|
||||||
@@ -96,3 +96,23 @@ Feature: The rate limiter keys on the real connection address, trusting a forwar
|
|||||||
X-Real-IP header
|
X-Real-IP header
|
||||||
Then the first response is not rejected by rate limiting and the second is 429 — both are
|
Then the first response is not rejected by rate limiting and the second is 429 — both are
|
||||||
counted against "10.0.0.1" itself
|
counted against "10.0.0.1" itself
|
||||||
|
|
||||||
|
Scenario: New connections from the same address share one counter
|
||||||
|
Given TRUSTED_PROXIES is "" and AUTH_RATE_LIMIT_MAX_ATTEMPTS is 1
|
||||||
|
When a request arrives with connection address "203.0.113.7:40000"
|
||||||
|
And a second request arrives with connection address "203.0.113.7:40001"
|
||||||
|
Then the first response is not rejected by rate limiting and the second is 429, because the
|
||||||
|
counter is keyed on "203.0.113.7" and the source port is ignored
|
||||||
|
|
||||||
|
Scenario: A forwarded client keeps one counter across the proxy's connections
|
||||||
|
Given TRUSTED_PROXIES is "10.0.0.1" and AUTH_RATE_LIMIT_MAX_ATTEMPTS is 1
|
||||||
|
When a request arrives with connection address "10.0.0.1:51000" and header
|
||||||
|
X-Real-IP: "198.51.100.9"
|
||||||
|
And a second request arrives with connection address "10.0.0.1:51001" and the same header
|
||||||
|
Then the first response is not rejected by rate limiting and the second is 429
|
||||||
|
|
||||||
|
Scenario: Expired counters do not accumulate
|
||||||
|
Given requests from many distinct addresses
|
||||||
|
When a full window has passed since a counter started
|
||||||
|
Then the next request evicts every counter whose window has ended, so memory stays bounded by
|
||||||
|
the addresses seen within one window
|
||||||
@@ -56,6 +56,14 @@ setup (`mockUserRepo`, `stubHasher`, `mockMailRepo`, the full `useCases` set, `a
|
|||||||
no forwarding header at all. Assert not `429`. Send a second, identical request. Assert `429` —
|
no forwarding header at all. Assert not `429`. Send a second, identical request. Assert `429` —
|
||||||
a trusted proxy with nothing to forward falls back to its own address as the key.
|
a trusted proxy with nothing to forward falls back to its own address as the key.
|
||||||
|
|
||||||
|
14. `trustedProxies = nil`, limit 5. Send 100 requests from `203.0.113.7` on ports `40000`–`40099`.
|
||||||
|
Assert exactly 95 are `429` — the source port never yields a fresh counter
|
||||||
|
(`test/rate_limit_connection_key_http_test.go`).
|
||||||
|
15. Same for IPv6: `[2001:db8::1]:50000` then `[2001:db8::1]:50001` with limit 1 → `200` then `429`.
|
||||||
|
16. `trustedProxies = ["10.0.0.1"]`, limit 1. `10.0.0.1:51000` and `10.0.0.1:51001`, both with
|
||||||
|
`X-Real-IP: 198.51.100.9` → `200` then `429`.
|
||||||
|
17. Limit 1, window 20 ms: `200`, `429`, wait 30 ms, `200` — an expired counter starts over.
|
||||||
|
|
||||||
## Manual verification (not exercised by the Go test)
|
## Manual verification (not exercised by the Go test)
|
||||||
|
|
||||||
- Real behaviour behind the documented nginx and Caddy reverse proxies (`docs/deployment.md`) —
|
- Real behaviour behind the documented nginx and Caddy reverse proxies (`docs/deployment.md`) —
|
||||||
|
|||||||
@@ -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
|
||||||
)
|
)
|
||||||
@@ -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=
|
||||||
|
|||||||
@@ -0,0 +1,141 @@
|
|||||||
|
package builtintype
|
||||||
|
|
||||||
|
import (
|
||||||
|
"RenewCMS/internal/domain/article"
|
||||||
|
"RenewCMS/internal/domain/contenttype"
|
||||||
|
"RenewCMS/internal/domain/user"
|
||||||
|
"errors"
|
||||||
|
)
|
||||||
|
|
||||||
|
var ErrNotFound = errors.New("built-in type not found")
|
||||||
|
|
||||||
|
const (
|
||||||
|
KeyArticle = "article"
|
||||||
|
KeyAuthor = "author"
|
||||||
|
KeySite = "site"
|
||||||
|
KeyMedia = "media"
|
||||||
|
KeyUser = "user"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Type struct {
|
||||||
|
Key string `json:"key"`
|
||||||
|
Name string `json:"name"`
|
||||||
|
Fields []contenttype.Field `json:"fields"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func Catalogue() []Type {
|
||||||
|
return []Type{
|
||||||
|
{Key: KeyArticle, Name: "Articles", Fields: articleFields()},
|
||||||
|
{Key: KeyAuthor, Name: "Authors", Fields: authorFields()},
|
||||||
|
{Key: KeySite, Name: "Sites", Fields: siteFields()},
|
||||||
|
{Key: KeyMedia, Name: "Media", Fields: mediaFields()},
|
||||||
|
{Key: KeyUser, Name: "Users", Fields: userFields()},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func Find(key string) (Type, error) {
|
||||||
|
for _, candidate := range Catalogue() {
|
||||||
|
if candidate.Key == key {
|
||||||
|
return candidate, nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return Type{}, ErrNotFound
|
||||||
|
}
|
||||||
|
|
||||||
|
func field(key string, label string, fieldType contenttype.FieldType) contenttype.Field {
|
||||||
|
return contenttype.Field{Key: key, Label: label, Type: fieldType, Options: []string{}}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (b builder) required() builder {
|
||||||
|
b.Required = true
|
||||||
|
return b
|
||||||
|
}
|
||||||
|
|
||||||
|
func (b builder) min(bound int) builder {
|
||||||
|
b.Min = bound
|
||||||
|
return b
|
||||||
|
}
|
||||||
|
|
||||||
|
func (b builder) max(bound int) builder {
|
||||||
|
b.Max = bound
|
||||||
|
return b
|
||||||
|
}
|
||||||
|
|
||||||
|
func (b builder) options(options ...string) builder {
|
||||||
|
b.Options = options
|
||||||
|
return b
|
||||||
|
}
|
||||||
|
|
||||||
|
type builder contenttype.Field
|
||||||
|
|
||||||
|
func text(key string, label string) builder {
|
||||||
|
return builder(field(key, label, contenttype.TypeText))
|
||||||
|
}
|
||||||
|
|
||||||
|
func of(key string, label string, fieldType contenttype.FieldType) builder {
|
||||||
|
return builder(field(key, label, fieldType))
|
||||||
|
}
|
||||||
|
|
||||||
|
func build(builders ...builder) []contenttype.Field {
|
||||||
|
fields := make([]contenttype.Field, 0, len(builders))
|
||||||
|
for _, b := range builders {
|
||||||
|
fields = append(fields, contenttype.Field(b))
|
||||||
|
}
|
||||||
|
return fields
|
||||||
|
}
|
||||||
|
|
||||||
|
func articleFields() []contenttype.Field {
|
||||||
|
return build(
|
||||||
|
text("title", "Title").required().min(article.MinTitleRunes).max(article.MaxTitleRunes),
|
||||||
|
of("body", "Body", contenttype.TypeRichText),
|
||||||
|
text("slug", "Slug"),
|
||||||
|
text("excerpt", "Excerpt").max(300),
|
||||||
|
text("seo_title", "SEO title").max(120),
|
||||||
|
text("seo_description", "SEO description").max(320),
|
||||||
|
of("is_online", "Online", contenttype.TypeBoolean),
|
||||||
|
text("canonical_url", "Canonical URL").max(article.MaxCanonicalURLRunes),
|
||||||
|
of("noindex", "No index", contenttype.TypeBoolean),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
func authorFields() []contenttype.Field {
|
||||||
|
return build(
|
||||||
|
text("name", "Name").required(),
|
||||||
|
text("slug", "Slug"),
|
||||||
|
text("bio", "Bio"),
|
||||||
|
text("website", "Website"),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
func siteFields() []contenttype.Field {
|
||||||
|
return build(
|
||||||
|
text("name", "Name").required(),
|
||||||
|
text("key", "Key").required(),
|
||||||
|
text("base_url", "Base URL").required(),
|
||||||
|
of("default_robots", "Default robots", contenttype.TypeSelect).options("index", "noindex"),
|
||||||
|
text("locale", "Locale"),
|
||||||
|
of("is_default", "Default site", contenttype.TypeBoolean),
|
||||||
|
text("site_name", "Site name").max(100),
|
||||||
|
text("title_template", "Title template").max(200),
|
||||||
|
text("default_description", "Default description").max(320),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
func mediaFields() []contenttype.Field {
|
||||||
|
return build(
|
||||||
|
text("filename", "Filename"),
|
||||||
|
of("size", "Size", contenttype.TypeNumber),
|
||||||
|
of("width", "Width", contenttype.TypeNumber),
|
||||||
|
of("height", "Height", contenttype.TypeNumber),
|
||||||
|
text("content_type", "Content type"),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
func userFields() []contenttype.Field {
|
||||||
|
return build(
|
||||||
|
text("username", "Username").required(),
|
||||||
|
text("display_name", "Display name"),
|
||||||
|
text("email", "Email").required(),
|
||||||
|
of("role", "Role", contenttype.TypeSelect).required().options(string(user.RoleOwner), string(user.RoleAdmin)),
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -0,0 +1,67 @@
|
|||||||
|
package contenttype
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
ErrContentTypeNotFound = errors.New("content type not found")
|
||||||
|
ErrKeyTaken = errors.New("a content type with that key already exists")
|
||||||
|
ErrInvalidName = errors.New("invalid content type name")
|
||||||
|
ErrInvalidKey = errors.New("invalid content type key")
|
||||||
|
ErrInvalidIcon = errors.New("invalid content type icon")
|
||||||
|
ErrInvalidField = errors.New("invalid field")
|
||||||
|
ErrHasEntries = errors.New("the content type still has entries")
|
||||||
|
ErrSchemaIncompatible = errors.New("the schema is incompatible with the stored entries")
|
||||||
|
)
|
||||||
|
|
||||||
|
type FieldType string
|
||||||
|
|
||||||
|
const (
|
||||||
|
TypeText FieldType = "text"
|
||||||
|
TypeRichText FieldType = "richtext"
|
||||||
|
TypeNumber FieldType = "number"
|
||||||
|
TypeBoolean FieldType = "boolean"
|
||||||
|
TypeDate FieldType = "date"
|
||||||
|
TypeSelect FieldType = "select"
|
||||||
|
TypeMedia FieldType = "media"
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
RuleType = "type"
|
||||||
|
RuleMin = "min"
|
||||||
|
RuleMax = "max"
|
||||||
|
RuleOptions = "options"
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
MinKeyRunes = 2
|
||||||
|
MaxKeyRunes = 40
|
||||||
|
MaxNameRunes = 100
|
||||||
|
MinFields = 1
|
||||||
|
MaxFields = 50
|
||||||
|
DateLayout = "2006-01-02"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Field struct {
|
||||||
|
Key string `json:"key"`
|
||||||
|
Label string `json:"label"`
|
||||||
|
Type FieldType `json:"type"`
|
||||||
|
Required bool `json:"required"`
|
||||||
|
Unique bool `json:"unique"`
|
||||||
|
Default any `json:"default"`
|
||||||
|
Min any `json:"min"`
|
||||||
|
Max any `json:"max"`
|
||||||
|
Options []string `json:"options"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type ContentType struct {
|
||||||
|
ID uint32 `json:"id"`
|
||||||
|
Key string `json:"key"`
|
||||||
|
Name string `json:"name"`
|
||||||
|
Icon *string `json:"icon"`
|
||||||
|
Fields []Field `json:"fields"`
|
||||||
|
CreatedAt time.Time `json:"created_at"`
|
||||||
|
UpdatedAt time.Time `json:"updated_at"`
|
||||||
|
}
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
package contenttype
|
||||||
|
|
||||||
|
type Repository interface {
|
||||||
|
Create(contentType ContentType) (ContentType, error)
|
||||||
|
GetByKey(key string) (ContentType, error)
|
||||||
|
List() ([]ContentType, error)
|
||||||
|
Update(contentType ContentType) (ContentType, error)
|
||||||
|
Delete(id uint32) error
|
||||||
|
}
|
||||||
Loaded 100 of 554 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user