Compare commits

..
57 Commits
Author SHA1 Message Date
fsylvain 2c8f39273c release: v2.6.2-beta English and French interface 2026-10-03 02:08:52 +02:00
fsylvain 721311a643 feat(SPA): i18n internationzalization, english and french 2026-10-03 01:53:49 +02:00
fsylvain 7f1e8e572d docs: deployement guide with new ui update settings 2026-10-02 17:11:04 +02:00
fsylvain 02a0a36dc3 release: v2.6.0-beta signed updates and browser restart 2026-10-02 16:56:04 +02:00
fsylvain 5a430c08f4 chore: ai fest 2026-10-02 16:44:04 +02:00
fsylvain 54e8fd5fed feat: restart to apply update, privileged helper, rollback 2026-10-01 21:36:40 +02:00
fsylvain 70460e4170 feat: update button (download, verify, stage) 2026-10-01 18:13:45 +02:00
fsylvain 834493a4f5 feat: signed releases, release feed, notification (read-only) 2026-10-01 15:01:53 +02:00
fsylvain a49eec909c chore: groundwork for update from settings page 2026-10-01 06:04:02 +02:00
fsylvain e10a5e57e2 docs: release notes for v2.5.0-beta 2026-10-01 05:32:13 +02:00
fsylvain ff0854f331 fix: deleted image wrongfully caching 2026-10-01 05:27:25 +02:00
fsylvain b3793d5dbb feat: media picker and image removal 2026-10-01 05:04:58 +02:00
fsylvain 008b0dfbb9 feat: media page T1 2026-10-01 01:36:35 +02:00
fsylvain 67d456baf6 feat(SPA): media page T0 2026-09-30 19:45:47 +02:00
fsylvain 0d99544579 feat(API): media library 2026-09-30 18:35:28 +02:00
fsylvain 95ae043d3e chore: groundwork for media library feature 2026-09-30 17:48:15 +02:00
fsylvain e0fa433ff9 docs: release notes format and patch notes for v2.0.0-beta to v2.4.0-beta 2026-09-30 03:11:37 +02:00
fsylvain 142325730d feat: users row actions "Cancel invite" on Pending rows and "Renew invite" on Expired rows 2026-09-30 02:48:49 +02:00
fsylvain 1ece778caf feat: UsersTable and UserCardList get Email, Display name (dash when empty), Role (new RoleBadge), Invite status and Created 2026-09-30 02:00:46 +02:00
fsylvain 153fd8719a feat: invite management API: DELETE /v1/user/invite/:id (204, cancels a pending invite) and POST /v1/user/invite/:id/renew (200, new code, expires_at = now+3d, created_at = now, resends the invitation email, old link dead) 2026-09-30 01:36:43 +02:00
fsylvain 461e93e3b5 feat: add Role (owner|admin) to the user domain, persistence model and mapper 2026-09-30 00:58:58 +02:00
fsylvain 162fea4afb feat: settings page, sidebar and drawer destination "Settings" (icon settings, after Integration), route /settings (verified), showing only the running build's Version 2026-09-30 00:19:29 +02:00
fsylvain b146dfead7 fix: desktop account menu icons, labels and check mark are now centred in their 32 px rows 2026-09-29 23:36:42 +02:00
fsylvain 27dadbbfa6 fix: account menu matches the redesigned board: System, Light, Dark stay in the menu and the sheet, and the visual-check exception on profile "Account menu" in web/visual/states.ts is removed 2026-09-29 23:31:04 +02:00
fsylvain 6dc47789ef chore: groundwork for new design and features related to users and settings 2026-09-29 23:19:41 +02:00
fsylvain 65ced64568 fix: "save X min ago" only min to min/hours/days 2026-09-29 22:56:05 +02:00
fsylvain c40522a09f fix: scrollable toolbar in mobile editor 2026-09-29 22:53:49 +02:00
fsylvain da36c78bc0 refac: hardening pass with multiple overhauls 2026-09-29 10:55:23 +02:00
fsylvain b0f7b7892b feat(SPA): profile page, display name and the new account menu 2026-09-29 10:13:09 +02:00
fsylvain 55525c06d6 feat: invitation accept screen and api 2026-09-29 09:21:53 +02:00
fsylvain 310cfd528e chore: new design for invitations accept 2026-09-29 08:41:54 +02:00
fsylvain 6afffc1984 feat(SPA): users page and invite modal 2026-09-29 08:35:14 +02:00
fsylvain acdef18b37 feat(API): user invitations and emails 2026-09-29 07:15:17 +02:00
fsylvain 7aae704d0a feat(API): optional display name on users 2026-09-29 06:52:58 +02:00
fsylvain 792aba433d chore: new design groundwork for next features 2026-09-29 06:32:46 +02:00
fsylvain b29d0ed045 feat: editor image removal QOLs 2026-09-29 02:44:31 +02:00
fsylvain 0fc00ceeff refac: cleaning round for image cropping/resizing 2026-09-28 07:56:13 +02:00
fsylvain e15f444603 feat: image cropping / resizing T0 2026-09-28 07:46:12 +02:00
fsylvain cb05b38f36 feat: password reset full design and flow 2026-09-28 05:06:16 +02:00
fsylvain 938263cd6a feat: image upload on articles 2026-09-28 02:28:20 +02:00
fsylvain d4fcfb2bba fix: multiple fixes all accross the SPA, missing buttons actions, styling etc. 2026-09-27 23:16:53 +02:00
fsylvain ad55137883 feat: integration screen 2026-09-27 18:04:43 +02:00
fsylvain a9a208b80a fix: workflow now ignores time senstive visual checks 2026-09-27 17:15:22 +02:00
fsylvain f6d0d01092 feat: articles list screen 2026-09-27 17:12:23 +02:00
fsylvain ca3fe20519 fix: browser was running two copies of ProseMirror's state module (prosemirror-state) at once 2026-09-27 06:31:45 +02:00
fsylvain c47d33eaa9 feat: article creation modal 2026-09-27 06:26:41 +02:00
fsylvain a4734b2c91 feat: article editor core 2026-09-27 02:11:38 +02:00
fsylvain d493a181e1 fix: visuals reference matching overhaul and better workflow 2026-09-26 21:04:51 +02:00
fsylvain 930b836241 feat: home screen and navigation design 2026-09-26 17:46:42 +02:00
fsylvain 30a4df47b1 feat: new emails design 2026-09-26 05:41:34 +02:00
fsylvain 4e41d60142 feat: register T1 (pending, verify) 2026-09-26 04:56:48 +02:00
fsylvain 3c3f7c6194 feat: register T0 2026-09-26 02:48:16 +02:00
fsylvain a5873f8886 fix: changed frontend workflow and fixed login reference matching for real 2026-09-25 22:31:44 +02:00
fsylvain f1e22f7073 fix: login match design reference 2026-09-25 21:28:12 +02:00
fsylvain 001f9f4774 feat: login page T0 2026-09-25 20:15:29 +02:00
fsylvain 12faab7f92 feat: typed API client (useApi) and session store (useSession) with the global 401, unverified-403, 429 and offline handling from states.md 2026-09-25 17:33:40 +02:00
fsylvain eed661bb24 feat: PrimeVue replaced by Nuxt UI using token files from web/src/theme, with AuthShell, DashboardShell, AppBoot and the route guards from routes.md 2026-09-25 17:09:34 +02:00
540 changed files with 79774 additions and 1742 deletions

No files matched your search

+4 -2
View File
@@ -1,9 +1,10 @@
PUBLIC_URL=http://localhost:5173 PUBLIC_URL=http://localhost:5173
JWT_SECRET=change-me-to-a-long-random-string JWT_SECRET=change-me-to-a-long-random-string
SMTP_EMAIL=a@b.c
SMTP_PASSWORD=12341234
SMTP_HOST=mail.service.abc SMTP_HOST=mail.service.abc
SMTP_PORT=465 SMTP_PORT=465
SMTP_LOGIN=a@b.c
SMTP_PASSWORD=12341234
SMTP_SENDER=a@b.c
ENVIRONMENT=development ENVIRONMENT=development
PORT=8080 PORT=8080
@@ -13,3 +14,4 @@ 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=
UPDATE_FEED_URL=https://git.floriansylvain.fr
+5
View File
@@ -20,5 +20,10 @@ build-errors.log
uploadedImages/ uploadedImages/
*.exe *.exe
# AI fest
.claude/ .claude/
CLAUDE.md CLAUDE.md
.codex/
.agents/
AGENTS.md
codex-workflow.md
+4
View File
@@ -15,6 +15,10 @@ cp .env.example .env # fill in PUBLIC_URL, JWT_SECRET and SMTP_*
Data is stored in `./data/` by default. For a real server (systemd, HTTPS, backups), see **[docs/deployment.md](docs/deployment.md)**. Data is stored in `./data/` by default. For a real server (systemd, HTTPS, backups), see **[docs/deployment.md](docs/deployment.md)**.
### Updates from the browser
On Linux with systemd, install v2.6.0-beta or newer manually, then follow [the browser-update setup guide](docs/deployment.md#browser-updates). It covers finding the actual database directory, installing the helper, testing a restart and troubleshooting. Other platforms use manual upgrades.
### Develop ### Develop
Requires Go 1.27+, Node.js 22, [Bun](https://bun.sh) and [Task](https://taskfile.dev). Requires Go 1.27+, Node.js 22, [Bun](https://bun.sh) and [Task](https://taskfile.dev).
+32 -2
View File
@@ -66,6 +66,13 @@ tasks:
cmds: cmds:
- bun run vitest run - bun run vitest run
visual:check:
desc: Screenshot a design screen's states next to the built SPA (Playwright) → tmp/visual/<screen>/
dir: web
deps: [web:install]
cmds:
- bun visual/check.ts {{.CLI_ARGS}}
lint: lint:
desc: gofmt check, go vet, eslint (--fix) and vue-tsc desc: gofmt check, go vet, eslint (--fix) and vue-tsc
cmds: cmds:
@@ -115,14 +122,37 @@ tasks:
- go build -trimpath -ldflags "{{.LDFLAGS}}" -o bin/{{.BINARY}}{{exeExt}} ./cmd/server - go build -trimpath -ldflags "{{.LDFLAGS}}" -o bin/{{.BINARY}}{{exeExt}} ./cmd/server
release: release:
desc: Cross-compile production binaries for all release targets → bin/ desc: Cross-compile and sign production binaries for all release targets → bin/ (needs RELEASE_SIGNING_KEY)
deps: [build:web]
cmds: cmds:
- task: release:check
- task: build:web
- for: { var: RELEASE_TARGETS } - for: { var: RELEASE_TARGETS }
task: build:target task: build:target
vars: vars:
GOOS: '{{index (splitList "/" .ITEM) 0}}' GOOS: '{{index (splitList "/" .ITEM) 0}}'
GOARCH: '{{index (splitList "/" .ITEM) 1}}' GOARCH: '{{index (splitList "/" .ITEM) 1}}'
- go run ./cmd/releasesign checksums bin --match "{{.BINARY}}_{{.VERSION}}_*"
- go run ./cmd/releasesign sign bin/checksums.txt
- go run ./cmd/releasesign verify bin/checksums.txt
release:check:
internal: true
cmds:
- cmd: 'test -n "$RELEASE_SIGNING_KEY" || { echo "RELEASE_SIGNING_KEY is not set. Point it at the private release key file (see task release:keygen)." >&2; exit 1; }'
silent: true
- cmd: 'test -f "$RELEASE_SIGNING_KEY" || { echo "RELEASE_SIGNING_KEY points to a missing file: $RELEASE_SIGNING_KEY" >&2; exit 1; }'
silent: true
- mkdir -p tmp
- echo probe > tmp/release-probe.txt
- defer: rm -f tmp/release-probe.txt tmp/release-probe.txt.sig
- go run ./cmd/releasesign sign tmp/release-probe.txt
release:keygen:
desc: One-time release key pair. Usage, task release:keygen -- <private key path outside the repository>
cmds:
- cmd: 'test -n "{{.CLI_ARGS}}" || { echo "usage: task release:keygen -- <private key path outside the repository>" >&2; exit 1; }'
silent: true
- go run ./cmd/releasesign keygen {{.CLI_ARGS}}
build:target: build:target:
internal: true internal: true
+170 -15
View File
@@ -3,16 +3,24 @@ package api
import ( import (
domainArticle "RenewCMS/internal/domain/article" domainArticle "RenewCMS/internal/domain/article"
domainImage "RenewCMS/internal/domain/image" domainImage "RenewCMS/internal/domain/image"
domainInvite "RenewCMS/internal/domain/invite"
domainMail "RenewCMS/internal/domain/mail" domainMail "RenewCMS/internal/domain/mail"
domainUpdate "RenewCMS/internal/domain/update"
domainUser "RenewCMS/internal/domain/user" domainUser "RenewCMS/internal/domain/user"
"RenewCMS/internal/infrastructure/config" "RenewCMS/internal/infrastructure/config"
"RenewCMS/internal/infrastructure/hashing" "RenewCMS/internal/infrastructure/hashing"
"RenewCMS/internal/infrastructure/mailer" "RenewCMS/internal/infrastructure/mailer"
"RenewCMS/internal/infrastructure/persistence/models" "RenewCMS/internal/infrastructure/persistence/models"
persistence "RenewCMS/internal/infrastructure/persistence/repositories" persistence "RenewCMS/internal/infrastructure/persistence/repositories"
"RenewCMS/internal/infrastructure/update"
"RenewCMS/internal/infrastructure/useCases" "RenewCMS/internal/infrastructure/useCases"
"crypto/ed25519"
"fmt"
"log"
"os" "os"
"path/filepath" "path/filepath"
"runtime"
"time"
"github.com/glebarez/sqlite" "github.com/glebarez/sqlite"
"github.com/go-chi/jwtauth/v5" "github.com/go-chi/jwtauth/v5"
@@ -33,41 +41,112 @@ type UseCases struct {
CancelRegistrationUseCase *useCases.CancelRegistrationUseCase CancelRegistrationUseCase *useCases.CancelRegistrationUseCase
RequestPasswordResetUseCase *useCases.RequestPasswordResetUseCase RequestPasswordResetUseCase *useCases.RequestPasswordResetUseCase
ResetPasswordUseCase *useCases.ResetPasswordUseCase ResetPasswordUseCase *useCases.ResetPasswordUseCase
UpdateUserProfileUseCase *useCases.UpdateUserProfileUseCase
ListUsersUseCase *useCases.ListUsersUseCase ListUsersUseCase *useCases.ListUsersUseCase
CreateInviteUseCase *useCases.CreateInviteUseCase
CancelInviteUseCase *useCases.CancelInviteUseCase
RenewInviteUseCase *useCases.RenewInviteUseCase
ListUsersAndInvitesUseCase *useCases.ListUsersAndInvitesUseCase
GetInviteUseCase *useCases.GetInviteUseCase
AcceptInviteUseCase *useCases.AcceptInviteUseCase
SendMailUseCase *useCases.SendMailUseCase SendMailUseCase *useCases.SendMailUseCase
CreateImageUseCase *useCases.CreateImageUseCase CreateImageUseCase *useCases.CreateImageUseCase
DeleteImageUseCase *useCases.DeleteImageUseCase ListMediaUseCase *useCases.ListMediaUseCase
RenameMediaUseCase *useCases.RenameMediaUseCase
DeleteMediaUseCase *useCases.DeleteMediaUseCase
MergeMediaUseCase *useCases.MergeMediaUseCase
GetMediaUsageUseCase *useCases.GetMediaUsageUseCase
GetSettingsUseCase *useCases.GetSettingsUseCase
GetUpdateStatusUseCase *useCases.GetUpdateStatusUseCase
CheckForUpdateUseCase *useCases.CheckForUpdateUseCase
StartUpdateDownloadUseCase *useCases.StartUpdateDownloadUseCase
RequestRestartUseCase *useCases.RequestRestartUseCase
RecordRunningInfoUseCase *useCases.RecordRunningInfoUseCase
} }
type Repositories struct { type Repositories struct {
ArticleRepo domainArticle.Repository ArticleRepo domainArticle.Repository
UserRepo domainUser.Repository UserRepo domainUser.Repository
ImageRepo domainImage.Repository ImageRepo domainImage.Repository
MailRepo domainMail.Repository InviteRepo domainInvite.Repository
MailRepo domainMail.Repository
ReleaseFeed domainUpdate.ReleaseFeed
UpdateStore domainUpdate.StatusStore
UpdateJobs domainUpdate.JobStore
UpdateHelper domainUpdate.HelperDetector
AssetFetcher domainUpdate.AssetFetcher
SignatureVerifier domainUpdate.SignatureVerifier
StagedRunner domainUpdate.StagedBinaryRunner
DatabaseBackup domainUpdate.DatabaseBackup
UpdateResults domainUpdate.ResultStore
RestartRequests domainUpdate.RestartRequestStore
RunningInfo domainUpdate.RunningInfoStore
} }
func getDb(dbName string) *gorm.DB { const (
sqliteBusyTimeoutMs = 5000
updateStatusFileName = "update-status.json"
updateJobFileName = "update-job.json"
updateHelperFileName = "update-helper.json"
updatesDirName = "updates"
backupsDirName = "backups"
)
func SQLiteDSN(dbName string) string {
return fmt.Sprintf("%s?_pragma=busy_timeout(%d)", dbName, sqliteBusyTimeoutMs)
}
func getDb(dbName string, uploadDir string) *gorm.DB {
if err := os.MkdirAll(filepath.Dir(dbName), os.ModePerm); err != nil { if err := os.MkdirAll(filepath.Dir(dbName), os.ModePerm); err != nil {
panic("Unable to create necessary subdirectories: " + err.Error()) panic("Unable to create necessary subdirectories: " + err.Error())
} }
db, err := gorm.Open(sqlite.Open(dbName), &gorm.Config{}) db, err := gorm.Open(sqlite.Open(SQLiteDSN(dbName)), &gorm.Config{})
if err != nil { if err != nil {
panic("Unable to open the database: " + err.Error()) panic("Unable to open the database: " + err.Error())
} }
if err := db.AutoMigrate(&models.Article{}, &models.User{}); err != nil { if err := db.AutoMigrate(&models.Article{}, &models.Image{}, &models.User{}, &models.Invite{}); err != nil {
panic("Failed to migrate database: " + err.Error()) panic("Failed to migrate database: " + err.Error())
} }
if err := persistence.BackfillUserRoles(db); err != nil {
panic("Failed to backfill user roles: " + err.Error())
}
if err := persistence.BackfillImageMetadata(db, uploadDir); err != nil {
panic("Failed to backfill image metadata: " + err.Error())
}
return db return db
} }
func releasePublicKey() ed25519.PublicKey {
key, err := update.EmbeddedPublicKey()
if err != nil {
panic("Unable to read the embedded release key: " + err.Error())
}
return key
}
func getRepositories(db *gorm.DB, settings config.Settings) *Repositories { func getRepositories(db *gorm.DB, settings config.Settings) *Repositories {
dataDir := filepath.Dir(settings.DBFile)
return &Repositories{ return &Repositories{
ArticleRepo: persistence.NewArticleRepository(db), ArticleRepo: persistence.NewArticleRepository(db),
UserRepo: persistence.NewUserRepository(db), UserRepo: persistence.NewUserRepository(db),
ImageRepo: persistence.NewImageRepository(db, settings.UploadDir), ImageRepo: persistence.NewImageRepository(db, settings.UploadDir),
MailRepo: mailer.NewMailRepository(settings.Smtp), InviteRepo: persistence.NewInviteRepository(db),
MailRepo: mailer.NewMailRepository(settings.Smtp),
ReleaseFeed: update.NewGiteaReleaseFeed(settings.UpdateFeedURL),
UpdateStore: update.NewJSONStatusStore(filepath.Join(dataDir, updateStatusFileName)),
UpdateJobs: update.NewJSONJobStore(filepath.Join(dataDir, updateJobFileName)),
UpdateHelper: update.NewFileHelperDetector(filepath.Join(dataDir, updateHelperFileName)),
AssetFetcher: update.NewHTTPAssetFetcher(settings.UpdateFeedURL),
SignatureVerifier: update.NewEd25519SignatureVerifier(releasePublicKey()),
StagedRunner: update.NewExecStagedBinaryRunner(),
DatabaseBackup: update.NewSQLiteDatabaseBackup(db, filepath.Join(dataDir, backupsDirName), time.Now),
UpdateResults: update.NewJSONResultStore(filepath.Join(dataDir, domainUpdate.ResultFileName)),
RestartRequests: update.NewJSONRestartRequestStore(filepath.Join(dataDir, domainUpdate.RestartRequestFileName)),
RunningInfo: update.NewJSONRunningInfoStore(filepath.Join(dataDir, domainUpdate.RunningInfoFileName)),
} }
} }
@@ -80,7 +159,7 @@ func getUseCases(repos *Repositories, settings config.Settings) *UseCases {
GetArticleUseCase: useCases.NewGetArticleUseCase(repos.ArticleRepo), GetArticleUseCase: useCases.NewGetArticleUseCase(repos.ArticleRepo),
ListArticlesUseCase: useCases.NewListArticlesUseCase(repos.ArticleRepo), ListArticlesUseCase: useCases.NewListArticlesUseCase(repos.ArticleRepo),
UpdateArticleUseCase: useCases.NewUpdateArticleUseCase(repos.ArticleRepo), UpdateArticleUseCase: useCases.NewUpdateArticleUseCase(repos.ArticleRepo),
DeleteArticleUseCase: useCases.NewDeleteArticleUseCase(repos.ArticleRepo, repos.ImageRepo), DeleteArticleUseCase: useCases.NewDeleteArticleUseCase(repos.ArticleRepo),
GetUserUseCase: useCases.NewGetUserUseCase(repos.UserRepo), GetUserUseCase: useCases.NewGetUserUseCase(repos.UserRepo),
CreateUserUseCase: useCases.NewCreateUserUseCase(repos.UserRepo, hasher, repos.MailRepo, settings.PublicURL), CreateUserUseCase: useCases.NewCreateUserUseCase(repos.UserRepo, hasher, repos.MailRepo, settings.PublicURL),
AuthenticateUserUseCase: useCases.NewAuthenticateUserUseCase(repos.UserRepo, hasher), AuthenticateUserUseCase: useCases.NewAuthenticateUserUseCase(repos.UserRepo, hasher),
@@ -88,15 +167,52 @@ func getUseCases(repos *Repositories, settings config.Settings) *UseCases {
CancelRegistrationUseCase: useCases.NewCancelRegistrationUseCase(repos.UserRepo), CancelRegistrationUseCase: useCases.NewCancelRegistrationUseCase(repos.UserRepo),
RequestPasswordResetUseCase: useCases.NewRequestPasswordResetUseCase(repos.UserRepo, hasher, repos.MailRepo, settings.PublicURL), RequestPasswordResetUseCase: useCases.NewRequestPasswordResetUseCase(repos.UserRepo, hasher, repos.MailRepo, settings.PublicURL),
ResetPasswordUseCase: useCases.NewResetPasswordUseCase(repos.UserRepo, hasher), ResetPasswordUseCase: useCases.NewResetPasswordUseCase(repos.UserRepo, hasher),
UpdateUserProfileUseCase: useCases.NewUpdateUserProfileUseCase(repos.UserRepo),
ListUsersUseCase: useCases.NewListUsersUseCase(repos.UserRepo), ListUsersUseCase: useCases.NewListUsersUseCase(repos.UserRepo),
CreateInviteUseCase: useCases.NewCreateInviteUseCase(repos.UserRepo, repos.InviteRepo, hasher, repos.MailRepo, settings.PublicURL),
CancelInviteUseCase: useCases.NewCancelInviteUseCase(repos.InviteRepo),
RenewInviteUseCase: useCases.NewRenewInviteUseCase(repos.UserRepo, repos.InviteRepo, hasher, repos.MailRepo, settings.PublicURL),
ListUsersAndInvitesUseCase: useCases.NewListUsersAndInvitesUseCase(repos.UserRepo, repos.InviteRepo),
GetInviteUseCase: useCases.NewGetInviteUseCase(repos.InviteRepo, hasher),
AcceptInviteUseCase: useCases.NewAcceptInviteUseCase(repos.UserRepo, repos.InviteRepo, hasher),
SendMailUseCase: useCases.NewSendMailUseCase(repos.MailRepo), SendMailUseCase: useCases.NewSendMailUseCase(repos.MailRepo),
CreateImageUseCase: useCases.NewCreateImageUseCase(repos.ImageRepo), CreateImageUseCase: useCases.NewCreateImageUseCase(repos.ImageRepo),
DeleteImageUseCase: useCases.NewDeleteImageUseCase(repos.ImageRepo), ListMediaUseCase: useCases.NewListMediaUseCase(repos.ImageRepo, repos.ArticleRepo, repos.UserRepo),
RenameMediaUseCase: useCases.NewRenameMediaUseCase(repos.ImageRepo),
DeleteMediaUseCase: useCases.NewDeleteMediaUseCase(repos.ImageRepo),
MergeMediaUseCase: useCases.NewMergeMediaUseCase(repos.ImageRepo, repos.ArticleRepo),
GetMediaUsageUseCase: useCases.NewGetMediaUsageUseCase(repos.ImageRepo, repos.ArticleRepo),
GetSettingsUseCase: useCases.NewGetSettingsUseCase(settings.Version),
GetUpdateStatusUseCase: useCases.NewGetUpdateStatusUseCase(repos.UpdateStore, repos.UpdateJobs, repos.UpdateHelper, repos.UpdateResults, repos.RestartRequests, settings.Version, time.Now),
CheckForUpdateUseCase: useCases.NewCheckForUpdateUseCase(repos.ReleaseFeed, repos.UpdateStore, settings.Version, time.Now),
StartUpdateDownloadUseCase: startUpdateDownloadUseCase(repos, settings),
RequestRestartUseCase: useCases.NewRequestRestartUseCase(repos.UpdateStore, repos.UpdateJobs, repos.UpdateHelper, repos.UpdateResults, repos.RestartRequests, settings.Version, time.Now),
RecordRunningInfoUseCase: useCases.NewRecordRunningInfoUseCase(repos.RunningInfo, settings.Version, os.Getpid(), time.Now),
} }
} }
func startUpdateDownloadUseCase(repos *Repositories, settings config.Settings) *useCases.StartUpdateDownloadUseCase {
return useCases.NewStartUpdateDownloadUseCase(useCases.StartUpdateDownloadDependencies{
Store: repos.UpdateStore,
Jobs: repos.UpdateJobs,
Helper: repos.UpdateHelper,
Results: repos.UpdateResults,
Requests: repos.RestartRequests,
Fetcher: repos.AssetFetcher,
Verifier: repos.SignatureVerifier,
Runner: repos.StagedRunner,
Backup: repos.DatabaseBackup,
Staging: update.NewOSStagingArea(filepath.Join(filepath.Dir(settings.DBFile), updatesDirName)),
Logger: log.Default(),
CurrentVersion: settings.Version,
Platform: domainUpdate.Platform{OS: runtime.GOOS, Arch: runtime.GOARCH},
FeedURL: settings.UpdateFeedURL,
Now: time.Now,
})
}
func InitContainer(settings config.Settings) (*UseCases, func() error) { func InitContainer(settings config.Settings) (*UseCases, func() error) {
db := getDb(settings.DBFile) db := getDb(settings.DBFile, settings.UploadDir)
repos := getRepositories(db, settings) repos := getRepositories(db, settings)
return getUseCases(repos, settings), closeDb(db) return getUseCases(repos, settings), closeDb(db)
} }
@@ -110,3 +226,42 @@ func closeDb(db *gorm.DB) func() error {
return sqlDb.Close() return sqlDb.Close()
} }
} }
type BrowserUpdateCommands struct {
Enable *useCases.EnableBrowserUpdatesUseCase
Disable *useCases.DisableBrowserUpdatesUseCase
}
func InitBrowserUpdateCommands() *BrowserUpdateCommands {
units := update.NewSystemdUnits()
dependencies := useCases.ManageBrowserUpdatesDependencies{
Probe: update.NewSystemMachineProbe(),
Locator: units,
Units: units,
Manager: update.NewSystemctlControl(domainUpdate.ServiceUnitName),
Status: update.NewJSONHelperStatusWriter(),
Now: time.Now,
}
return &BrowserUpdateCommands{
Enable: useCases.NewEnableBrowserUpdatesUseCase(dependencies),
Disable: useCases.NewDisableBrowserUpdatesUseCase(dependencies),
}
}
func InitApplyUpdateCommand(options domainUpdate.InstallOptions) *useCases.ApplyRestartRequestUseCase {
layout := domainUpdate.HelperLayout{DataDir: options.DataDir, BinaryPath: options.Binary}
files := update.NewNoFollowFilesystem()
return useCases.NewApplyRestartRequestUseCase(useCases.ApplyRestartRequestDependencies{
Requests: update.NewFSRestartRequestStore(files, layout.RestartRequestPath()),
Results: update.NewFSResultStore(files, layout.ResultPath()),
Running: update.NewJSONRunningInfoStore(filepath.Join(options.DataDir, domainUpdate.RunningInfoFileName)),
Files: files,
Service: update.NewSystemctlControl(options.Service),
Health: update.NewHTTPHealthChecker(options.Port),
Verifier: update.NewEd25519SignatureVerifier(releasePublicKey()),
Clock: update.NewSystemClock(),
Logger: log.Default(),
Layout: layout,
Platform: domainUpdate.Platform{OS: runtime.GOOS, Arch: runtime.GOARCH},
})
}
+102
View File
@@ -0,0 +1,102 @@
package auth
import (
"RenewCMS/api/pkg/apperr"
validator "RenewCMS/api/pkg/validator"
"RenewCMS/internal/domain/invite"
"RenewCMS/internal/domain/user"
"RenewCMS/internal/infrastructure/useCases"
"encoding/json"
"errors"
"net/http"
"github.com/go-chi/jwtauth/v5"
)
type AcceptInviteHandler struct {
Token *jwtauth.JWTAuth
GetInviteUseCase *useCases.GetInviteUseCase
AcceptInviteUseCase *useCases.AcceptInviteUseCase
IsProduction bool
}
type AcceptInviteRequest struct {
Code string `json:"code" validate:"required"`
Username string `json:"username" validate:"required,min=3,max=20"`
Password string `json:"password" validate:"required,min=8"`
}
type inviteEmailResponse struct {
Email string `json:"email"`
}
func NewAcceptInviteHandler(getInvite *useCases.GetInviteUseCase, acceptInvite *useCases.AcceptInviteUseCase, token *jwtauth.JWTAuth, isProduction bool) *AcceptInviteHandler {
return &AcceptInviteHandler{
Token: token,
GetInviteUseCase: getInvite,
AcceptInviteUseCase: acceptInvite,
IsProduction: isProduction,
}
}
func (h *AcceptInviteHandler) GetInvite(w http.ResponseWriter, r *http.Request) {
found, err := h.GetInviteUseCase.GetInvite(r.URL.Query().Get("c"))
if err != nil {
writeAcceptInviteError(w, err)
return
}
body, err := json.Marshal(inviteEmailResponse{Email: found.Email})
if err != nil {
http.Error(w, "Internal server error", http.StatusInternalServerError)
return
}
w.Header().Set("Cache-Control", "no-store")
_, _ = w.Write(body)
}
func (h *AcceptInviteHandler) AcceptInvite(w http.ResponseWriter, r *http.Request) {
var request AcceptInviteRequest
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
}
createdUser, err := h.AcceptInviteUseCase.AcceptInvite(useCases.AcceptInviteCommand{
Code: request.Code,
Username: request.Username,
Password: request.Password,
})
if err != nil {
writeAcceptInviteError(w, err)
return
}
if err := setJwtCookie(w, h.Token, h.IsProduction, createdUser); err != nil {
http.Error(w, "Internal server error", http.StatusInternalServerError)
return
}
message, _ := json.Marshal(map[string]any{"message": "Invite accepted! HTTPonly jwt cookie created"})
_, _ = w.Write(message)
}
func writeAcceptInviteError(w http.ResponseWriter, err error) {
switch {
case errors.Is(err, invite.ErrInviteInvalid):
http.Error(w, apperr.InviteInvalidErrorMessage, http.StatusNotFound)
case errors.Is(err, invite.ErrInviteExpired):
http.Error(w, apperr.InviteExpiredErrorMessage, http.StatusGone)
case errors.Is(err, user.ErrUsernameTaken):
http.Error(w, apperr.UsernameTakenErrorMessage, http.StatusConflict)
case errors.Is(err, invite.ErrEmailHasAccount):
http.Error(w, apperr.EmailHasAccountErrorMessage, http.StatusConflict)
default:
http.Error(w, "Internal server error", http.StatusInternalServerError)
}
}
+8 -4
View File
@@ -52,22 +52,26 @@ func removeJwtCookie(w http.ResponseWriter, isProduction bool) {
}) })
} }
func (h *LoginHandler) SetJwtCookie(w *http.ResponseWriter, u user.User) error { func setJwtCookie(w http.ResponseWriter, token *jwtauth.JWTAuth, isProduction bool, u user.User) error {
_, tokenString, err := h.Token.Encode(map[string]any{"user_id": u.ID, "token_version": u.TokenVersion}) _, tokenString, err := token.Encode(map[string]any{"user_id": u.ID, "token_version": u.TokenVersion})
if err != nil { if err != nil {
return err return err
} }
http.SetCookie(*w, &http.Cookie{ http.SetCookie(w, &http.Cookie{
Name: "jwt", Name: "jwt",
Value: tokenString, Value: tokenString,
Expires: time.Now().Add(24 * time.Hour), Expires: time.Now().Add(24 * time.Hour),
Secure: h.IsProduction, Secure: isProduction,
HttpOnly: true, HttpOnly: true,
Path: "/", Path: "/",
}) })
return nil return nil
} }
func (h *LoginHandler) SetJwtCookie(w *http.ResponseWriter, u user.User) error {
return setJwtCookie(*w, h.Token, h.IsProduction, u)
}
func (h *LoginHandler) Login(w http.ResponseWriter, r *http.Request) { func (h *LoginHandler) Login(w http.ResponseWriter, r *http.Request) {
var credentials LoginCredentials var credentials LoginCredentials
+2 -1
View File
@@ -3,6 +3,7 @@ package auth
import ( import (
"RenewCMS/api/pkg/apperr" "RenewCMS/api/pkg/apperr"
"RenewCMS/api/pkg/claims" "RenewCMS/api/pkg/claims"
"RenewCMS/api/pkg/publicuser"
"RenewCMS/internal/domain/user" "RenewCMS/internal/domain/user"
"RenewCMS/internal/infrastructure/useCases" "RenewCMS/internal/infrastructure/useCases"
"encoding/json" "encoding/json"
@@ -37,7 +38,7 @@ func (h *MeHandler) Me(w http.ResponseWriter, r *http.Request) {
return return
} }
body, err := json.Marshal(newPublicUser(loadedUser)) body, err := json.Marshal(publicuser.New(loadedUser))
if err != nil { if err != nil {
http.Error(w, "Internal server error", http.StatusInternalServerError) http.Error(w, "Internal server error", http.StatusInternalServerError)
return return
+2 -22
View File
@@ -3,13 +3,13 @@ package auth
import ( import (
"RenewCMS/api/pkg/apperr" "RenewCMS/api/pkg/apperr"
"RenewCMS/api/pkg/claims" "RenewCMS/api/pkg/claims"
"RenewCMS/api/pkg/publicuser"
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"
"encoding/json" "encoding/json"
"errors" "errors"
"net/http" "net/http"
"time"
) )
type VerificationHandler struct { type VerificationHandler struct {
@@ -22,26 +22,6 @@ type VerifyCredentials struct {
Code string `json:"code" validate:"required"` Code string `json:"code" validate:"required"`
} }
type PublicUser struct {
ID uint32 `json:"id"`
Username string `json:"username"`
Email string `json:"email"`
IsVerified bool `json:"is_verified"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
func newPublicUser(u user.User) PublicUser {
return PublicUser{
ID: u.ID,
Username: u.Username,
Email: u.Email,
IsVerified: u.IsVerified,
CreatedAt: u.CreatedAt,
UpdatedAt: u.UpdatedAt,
}
}
func NewVerificationHandler(verify *useCases.VerifyUserUseCase, cancel *useCases.CancelRegistrationUseCase, isProduction bool) *VerificationHandler { func NewVerificationHandler(verify *useCases.VerifyUserUseCase, cancel *useCases.CancelRegistrationUseCase, isProduction bool) *VerificationHandler {
return &VerificationHandler{ return &VerificationHandler{
VerifyUseCase: verify, VerifyUseCase: verify,
@@ -84,7 +64,7 @@ func (h *VerificationHandler) Verify(w http.ResponseWriter, r *http.Request) {
return return
} }
body, err := json.Marshal(newPublicUser(verifiedUser)) body, err := json.Marshal(publicuser.New(verifiedUser))
if err != nil { if err != nil {
http.Error(w, "Internal server error", http.StatusInternalServerError) http.Error(w, "Internal server error", http.StatusInternalServerError)
return return
-89
View File
@@ -1,89 +0,0 @@
package image
import (
"RenewCMS/api/pkg/apperr"
domainArticle "RenewCMS/internal/domain/article"
domainImage "RenewCMS/internal/domain/image"
"RenewCMS/internal/infrastructure/useCases"
"encoding/json"
"errors"
"net/http"
"strconv"
"github.com/go-chi/chi/v5"
)
type Handler struct {
CreateUseCase *useCases.CreateImageUseCase
GetUseCase *useCases.GetArticleUseCase
UpdateUseCase *useCases.UpdateArticleUseCase
}
func NewHandler(create *useCases.CreateImageUseCase, get *useCases.GetArticleUseCase, update *useCases.UpdateArticleUseCase) *Handler {
return &Handler{
CreateUseCase: create,
GetUseCase: get,
UpdateUseCase: update,
}
}
func writeInternalServerError(w http.ResponseWriter) {
http.Error(w, "Internal server error", http.StatusInternalServerError)
}
func writeArticleError(w http.ResponseWriter, err error) {
if errors.Is(err, domainArticle.ErrArticleNotFound) {
http.Error(w, apperr.ArticleNotFoundErrorMessage, http.StatusNotFound)
return
}
writeInternalServerError(w)
}
func (h *Handler) PostImage(w http.ResponseWriter, r *http.Request) {
articleId, err := strconv.ParseUint(chi.URLParam(r, "id"), 10, 32)
if err != nil {
http.Error(w, apperr.IdUint32ErrorMessage, http.StatusBadRequest)
return
}
if _, err := h.GetUseCase.GetArticle(uint32(articleId)); err != nil {
writeArticleError(w, err)
return
}
file, fileHeader, err := r.FormFile("file")
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
defer file.Close()
newImage, err := h.CreateUseCase.CreateImage(domainImage.ImageInput{
Content: file,
Filename: fileHeader.Filename,
Size: fileHeader.Size,
ContentType: fileHeader.Header.Get("Content-Type"),
})
if err != nil {
if errors.Is(err, domainImage.ErrImageTypeNotAllowed) || errors.Is(err, domainImage.ErrImageTooLarge) {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
writeInternalServerError(w)
return
}
if err := h.UpdateUseCase.AddImage(uint32(articleId), newImage.ID); err != nil {
writeArticleError(w, err)
return
}
responseJson, err := json.Marshal(map[string]any{"location": newImage.Path})
if err != nil {
writeInternalServerError(w)
return
}
w.WriteHeader(http.StatusCreated)
_, _ = w.Write(responseJson)
}
+317
View File
@@ -0,0 +1,317 @@
package media
import (
"RenewCMS/api/pkg/apperr"
"RenewCMS/api/pkg/claims"
"RenewCMS/api/pkg/upload"
validator "RenewCMS/api/pkg/validator"
domainImage "RenewCMS/internal/domain/image"
"RenewCMS/internal/infrastructure/useCases"
"encoding/json"
"errors"
"net/http"
"net/url"
"strconv"
"strings"
"time"
"github.com/go-chi/chi/v5"
)
type Handler struct {
CreateUseCase *useCases.CreateImageUseCase
ListUseCase *useCases.ListMediaUseCase
RenameUseCase *useCases.RenameMediaUseCase
DeleteUseCase *useCases.DeleteMediaUseCase
MergeUseCase *useCases.MergeMediaUseCase
UsageUseCase *useCases.GetMediaUsageUseCase
}
type RenameRequest struct {
Filename string `json:"filename" validate:"required"`
}
type MergeRequest struct {
KeepID uint32 `json:"keep_id" validate:"required,gt=0"`
MergeIDs []uint32 `json:"merge_ids" validate:"required,min=1,dive,gt=0"`
}
type mediaItemResponse struct {
ID uint32 `json:"id"`
Filename string `json:"filename"`
URL string `json:"url"`
Size int64 `json:"size"`
ContentType string `json:"content_type"`
Width *int `json:"width"`
Height *int `json:"height"`
SHA256 string `json:"sha256"`
UploadedBy string `json:"uploaded_by"`
CreatedAt time.Time `json:"created_at"`
UsedIn int `json:"used_in"`
Duplicate bool `json:"duplicate"`
}
type countsResponse struct {
All int `json:"all"`
Unused int `json:"unused"`
Duplicates int `json:"duplicates"`
}
type listResponse struct {
Items []mediaItemResponse `json:"items"`
NextCursor *string `json:"next_cursor"`
Counts countsResponse `json:"counts"`
}
type usageResponse struct {
ID uint32 `json:"id"`
Title string `json:"title"`
Published bool `json:"published"`
}
type mergeResponse struct {
ArticlesUpdated int `json:"articles_updated"`
Merged int `json:"merged"`
}
func NewHandler(create *useCases.CreateImageUseCase, list *useCases.ListMediaUseCase, rename *useCases.RenameMediaUseCase, deleteUseCase *useCases.DeleteMediaUseCase, merge *useCases.MergeMediaUseCase, usage *useCases.GetMediaUsageUseCase) *Handler {
return &Handler{
CreateUseCase: create,
ListUseCase: list,
RenameUseCase: rename,
DeleteUseCase: deleteUseCase,
MergeUseCase: merge,
UsageUseCase: usage,
}
}
func writeInternalServerError(w http.ResponseWriter) {
http.Error(w, "Internal server error", http.StatusInternalServerError)
}
func writeJSON(w http.ResponseWriter, status int, payload any) {
body, err := json.Marshal(payload)
if err != nil {
writeInternalServerError(w)
return
}
w.WriteHeader(status)
_, _ = w.Write(body)
}
func writeImageError(w http.ResponseWriter, err error) {
if errors.Is(err, domainImage.ErrImageNotFound) {
http.Error(w, apperr.ImageNotFoundErrorMessage, http.StatusNotFound)
return
}
writeInternalServerError(w)
}
func parseImageId(w http.ResponseWriter, r *http.Request) (uint32, bool) {
id, err := strconv.ParseUint(chi.URLParam(r, "id"), 10, 32)
if err != nil {
http.Error(w, apperr.IdUint32ErrorMessage, http.StatusBadRequest)
return 0, false
}
return uint32(id), true
}
func dimension(value int) *int {
if value == 0 {
return nil
}
return &value
}
func toResponse(item useCases.MediaItem) mediaItemResponse {
return mediaItemResponse{
ID: item.Image.ID,
Filename: item.Image.Filename,
URL: item.Image.Path,
Size: item.Image.Size,
ContentType: item.Image.ContentType,
Width: dimension(item.Image.Width),
Height: dimension(item.Image.Height),
SHA256: item.Image.SHA256,
UploadedBy: item.UploadedBy,
CreatedAt: item.Image.CreatedAt,
UsedIn: item.UsedIn,
Duplicate: item.Duplicate,
}
}
func parseListQuery(r *http.Request) (domainImage.ListQuery, error) {
values, err := url.ParseQuery(r.URL.RawQuery)
if err != nil {
return domainImage.ListQuery{}, domainImage.ErrInvalidQuery
}
query := domainImage.NewListQuery()
query.Search = values.Get("q")
query.Hash = strings.ToLower(values.Get("hash"))
query.Cursor = values.Get("cursor")
if values.Has("filter") {
query.Filter = domainImage.Filter(values.Get("filter"))
}
if values.Has("sort") {
query.Sort = domainImage.Sort(values.Get("sort"))
}
if values.Has("limit") {
limit, err := strconv.Atoi(values.Get("limit"))
if err != nil {
return domainImage.ListQuery{}, domainImage.ErrInvalidQuery
}
query.Limit = limit
}
return query, nil
}
func (h *Handler) List(w http.ResponseWriter, r *http.Request) {
query, err := parseListQuery(r)
if err != nil {
http.Error(w, apperr.MediaQueryErrorMessage, http.StatusBadRequest)
return
}
page, err := h.ListUseCase.List(query)
if err != nil {
if errors.Is(err, domainImage.ErrInvalidQuery) {
http.Error(w, apperr.MediaQueryErrorMessage, http.StatusBadRequest)
return
}
writeInternalServerError(w)
return
}
items := make([]mediaItemResponse, 0, len(page.Items))
for _, item := range page.Items {
items = append(items, toResponse(item))
}
response := listResponse{
Items: items,
Counts: countsResponse{All: page.Counts.All, Unused: page.Counts.Unused, Duplicates: page.Counts.Duplicates},
}
if page.NextCursor != "" {
response.NextCursor = &page.NextCursor
}
writeJSON(w, http.StatusOK, response)
}
func (h *Handler) Upload(w http.ResponseWriter, r *http.Request) {
userId, _ := claims.UserId(r)
input, closeFile, ok := upload.ReadImageInput(w, r, userId)
if !ok {
return
}
defer closeFile()
created, err := h.CreateUseCase.CreateImage(input)
if err != nil {
upload.WriteCreateError(w, err)
return
}
h.writeItem(w, http.StatusCreated, created)
}
func (h *Handler) writeItem(w http.ResponseWriter, status int, img domainImage.Image) {
item, err := h.ListUseCase.Describe(img)
if err != nil {
writeInternalServerError(w)
return
}
writeJSON(w, status, toResponse(item))
}
func (h *Handler) Rename(w http.ResponseWriter, r *http.Request) {
id, ok := parseImageId(w, r)
if !ok {
return
}
var request RenameRequest
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, apperr.MediaFilenameErrorMessage, http.StatusBadRequest)
return
}
renamed, err := h.RenameUseCase.Rename(id, request.Filename)
if err != nil {
if errors.Is(err, domainImage.ErrInvalidFilename) {
http.Error(w, apperr.MediaFilenameErrorMessage, http.StatusBadRequest)
return
}
writeImageError(w, err)
return
}
h.writeItem(w, http.StatusOK, renamed)
}
func (h *Handler) Delete(w http.ResponseWriter, r *http.Request) {
id, ok := parseImageId(w, r)
if !ok {
return
}
if err := h.DeleteUseCase.Delete(id); err != nil {
writeImageError(w, err)
return
}
w.WriteHeader(http.StatusNoContent)
}
func (h *Handler) Usage(w http.ResponseWriter, r *http.Request) {
id, ok := parseImageId(w, r)
if !ok {
return
}
articles, err := h.UsageUseCase.Usage(id)
if err != nil {
writeImageError(w, err)
return
}
response := make([]usageResponse, 0, len(articles))
for _, a := range articles {
response = append(response, usageResponse{ID: a.ID, Title: a.Title, Published: a.IsOnline})
}
writeJSON(w, http.StatusOK, response)
}
func (h *Handler) Merge(w http.ResponseWriter, r *http.Request) {
var request MergeRequest
if err := json.NewDecoder(r.Body).Decode(&request); err != nil {
http.Error(w, apperr.MediaMergeRequestErrorMessage, http.StatusBadRequest)
return
}
if err := validator.Validate.Struct(request); err != nil {
http.Error(w, apperr.MediaMergeRequestErrorMessage, http.StatusBadRequest)
return
}
result, err := h.MergeUseCase.Merge(request.KeepID, request.MergeIDs)
if err != nil {
writeMergeError(w, err)
return
}
writeJSON(w, http.StatusOK, mergeResponse{ArticlesUpdated: result.ArticlesUpdated, Merged: result.Merged})
}
func writeMergeError(w http.ResponseWriter, err error) {
switch {
case errors.Is(err, domainImage.ErrInvalidMergeRequest):
http.Error(w, apperr.MediaMergeRequestErrorMessage, http.StatusBadRequest)
case errors.Is(err, domainImage.ErrMergeCopyMissing), errors.Is(err, domainImage.ErrMergeHashMismatch):
http.Error(w, apperr.MediaMergeConflictErrorMessage, http.StatusConflict)
default:
writeImageError(w, err)
}
}
+24
View File
@@ -0,0 +1,24 @@
package settings
import (
"RenewCMS/internal/infrastructure/useCases"
"encoding/json"
"net/http"
)
type Handler struct {
GetSettingsUseCase *useCases.GetSettingsUseCase
}
func NewHandler(getSettings *useCases.GetSettingsUseCase) *Handler {
return &Handler{GetSettingsUseCase: getSettings}
}
func (h *Handler) GetSettings(w http.ResponseWriter, _ *http.Request) {
body, err := json.Marshal(h.GetSettingsUseCase.GetSettings())
if err != nil {
http.Error(w, "Internal server error", http.StatusInternalServerError)
return
}
_, _ = w.Write(body)
}
@@ -12,7 +12,7 @@ import (
"github.com/go-chi/chi/v5" "github.com/go-chi/chi/v5"
) )
const cacheControl = "public, max-age=31536000, immutable" const cacheControl = "public, no-cache"
const svgContentSecurityPolicy = "default-src 'none'; style-src 'unsafe-inline'; sandbox" const svgContentSecurityPolicy = "default-src 'none'; style-src 'unsafe-inline'; sandbox"
const fallbackContentType = "application/octet-stream" const fallbackContentType = "application/octet-stream"
+162
View File
@@ -0,0 +1,162 @@
package update
import (
"RenewCMS/api/pkg/apperr"
"RenewCMS/api/pkg/claims"
validator "RenewCMS/api/pkg/validator"
domain "RenewCMS/internal/domain/update"
"RenewCMS/internal/domain/user"
"RenewCMS/internal/infrastructure/useCases"
"encoding/json"
"errors"
"io"
"net/http"
"strings"
)
const restartBodyLimitBytes = 1024
type Handler struct {
GetUpdateStatusUseCase *useCases.GetUpdateStatusUseCase
CheckForUpdateUseCase *useCases.CheckForUpdateUseCase
StartUpdateDownloadUseCase *useCases.StartUpdateDownloadUseCase
RequestRestartUseCase *useCases.RequestRestartUseCase
GetUserUseCase *useCases.GetUserUseCase
}
type restartRequest struct {
Kind *string `json:"kind" validate:"omitempty,oneof=update restart"`
}
func NewHandler(getStatus *useCases.GetUpdateStatusUseCase, checkForUpdate *useCases.CheckForUpdateUseCase, startDownload *useCases.StartUpdateDownloadUseCase, requestRestart *useCases.RequestRestartUseCase, getUser *useCases.GetUserUseCase) *Handler {
return &Handler{
GetUpdateStatusUseCase: getStatus,
CheckForUpdateUseCase: checkForUpdate,
StartUpdateDownloadUseCase: startDownload,
RequestRestartUseCase: requestRestart,
GetUserUseCase: getUser,
}
}
func (h *Handler) GetStatus(w http.ResponseWriter, r *http.Request) {
isOwner, ok := h.isOwner(w, r)
if !ok {
return
}
writeStatus(w, http.StatusOK, h.GetUpdateStatusUseCase.GetStatus(isOwner))
}
func (h *Handler) Check(w http.ResponseWriter, r *http.Request) {
if _, err := h.CheckForUpdateUseCase.Check(); err != nil {
http.Error(w, "Internal server error", http.StatusInternalServerError)
return
}
isOwner, ok := h.isOwner(w, r)
if !ok {
return
}
writeStatus(w, http.StatusOK, h.GetUpdateStatusUseCase.GetStatus(isOwner))
}
func (h *Handler) Download(w http.ResponseWriter, _ *http.Request) {
status, err := h.StartUpdateDownloadUseCase.Start()
if err != nil {
writeDownloadError(w, err)
return
}
writeStatus(w, http.StatusAccepted, status)
}
func (h *Handler) Restart(w http.ResponseWriter, r *http.Request) {
kind, ok := decodeRestartKind(w, r)
if !ok {
return
}
userId, ok := claims.UserId(r)
if !ok {
http.Error(w, apperr.UnauthorizedErrorMessage, http.StatusUnauthorized)
return
}
status, err := h.RequestRestartUseCase.Request(userId, kind)
if err != nil {
writeRestartError(w, err)
return
}
writeStatus(w, http.StatusAccepted, status)
}
func decodeRestartKind(w http.ResponseWriter, r *http.Request) (string, bool) {
body, err := io.ReadAll(http.MaxBytesReader(w, r.Body, restartBodyLimitBytes))
if err != nil {
http.Error(w, apperr.BodyErrorMessage, http.StatusBadRequest)
return "", false
}
if strings.TrimSpace(string(body)) == "" {
return "", true
}
var request restartRequest
if err := json.Unmarshal(body, &request); err != nil || validator.Validate.Struct(request) != nil {
http.Error(w, apperr.BodyErrorMessage, http.StatusBadRequest)
return "", false
}
if request.Kind == nil {
return "", true
}
return *request.Kind, true
}
func (h *Handler) isOwner(w http.ResponseWriter, r *http.Request) (bool, bool) {
userId, ok := claims.UserId(r)
if !ok {
http.Error(w, apperr.UnauthorizedErrorMessage, http.StatusUnauthorized)
return false, false
}
currentUser, err := h.GetUserUseCase.GetUser(userId)
if err != nil {
if errors.Is(err, user.ErrUserNotFound) {
http.Error(w, apperr.UnauthorizedErrorMessage, http.StatusUnauthorized)
return false, false
}
http.Error(w, "Internal server error", http.StatusInternalServerError)
return false, false
}
return currentUser.Role == user.RoleOwner, true
}
func writeDownloadError(w http.ResponseWriter, err error) {
switch {
case errors.Is(err, domain.ErrNotPrepared):
http.Error(w, apperr.UpdateNotPreparedErrorMessage, http.StatusConflict)
case errors.Is(err, domain.ErrJobInProgress), errors.Is(err, domain.ErrRestartPending):
http.Error(w, apperr.UpdateAlreadyRunningErrorMessage, http.StatusConflict)
case errors.Is(err, domain.ErrNothingToUpdate):
http.Error(w, apperr.NothingToUpdateErrorMessage, http.StatusBadRequest)
case errors.Is(err, domain.ErrPreflightRefused):
http.Error(w, apperr.UpdateRefusedErrorMessage, http.StatusUnprocessableEntity)
default:
http.Error(w, "Internal server error", http.StatusInternalServerError)
}
}
func writeRestartError(w http.ResponseWriter, err error) {
switch {
case errors.Is(err, domain.ErrNotPrepared):
http.Error(w, apperr.UpdateNotPreparedErrorMessage, http.StatusConflict)
case errors.Is(err, domain.ErrJobInProgress), errors.Is(err, domain.ErrRestartPending):
http.Error(w, apperr.UpdateAlreadyRunningErrorMessage, http.StatusConflict)
case errors.Is(err, domain.ErrRestartKindMismatch):
http.Error(w, apperr.UpdateRestartMismatchErrorMessage, http.StatusConflict)
default:
http.Error(w, "Internal server error", http.StatusInternalServerError)
}
}
func writeStatus(w http.ResponseWriter, code int, status domain.UpdateStatus) {
body, err := json.Marshal(status)
if err != nil {
http.Error(w, "Internal server error", http.StatusInternalServerError)
return
}
w.WriteHeader(code)
_, _ = w.Write(body)
}
+204
View File
@@ -0,0 +1,204 @@
package user
import (
"RenewCMS/api/pkg/apperr"
"RenewCMS/api/pkg/claims"
validator "RenewCMS/api/pkg/validator"
"RenewCMS/internal/domain/invite"
"RenewCMS/internal/domain/user"
"RenewCMS/internal/infrastructure/useCases"
"encoding/json"
"errors"
"net/http"
"strconv"
"time"
"github.com/go-chi/chi/v5"
)
type InviteHandler struct {
CreateInviteUseCase *useCases.CreateInviteUseCase
CancelInviteUseCase *useCases.CancelInviteUseCase
RenewInviteUseCase *useCases.RenewInviteUseCase
ListUsersAndInvitesUseCase *useCases.ListUsersAndInvitesUseCase
}
type CreateInviteRequest struct {
Email string `json:"email" validate:"required,inviteemail"`
}
type inviteResponse struct {
ID uint32 `json:"id"`
Kind string `json:"kind"`
Email string `json:"email"`
Status string `json:"status"`
CreatedAt time.Time `json:"created_at"`
ExpiresAt time.Time `json:"expires_at"`
}
type inviteListItem struct {
ID uint32 `json:"id"`
Kind string `json:"kind"`
Email string `json:"email"`
Status string `json:"status"`
CreatedAt time.Time `json:"created_at"`
}
type userListItem struct {
ID uint32 `json:"id"`
Kind string `json:"kind"`
Username string `json:"username"`
DisplayName string `json:"display_name"`
Email string `json:"email"`
Role string `json:"role"`
Status string `json:"status"`
CreatedAt time.Time `json:"created_at"`
}
func NewInviteHandler(createInvite *useCases.CreateInviteUseCase, cancelInvite *useCases.CancelInviteUseCase, renewInvite *useCases.RenewInviteUseCase, listUsersAndInvites *useCases.ListUsersAndInvitesUseCase) *InviteHandler {
return &InviteHandler{
CreateInviteUseCase: createInvite,
CancelInviteUseCase: cancelInvite,
RenewInviteUseCase: renewInvite,
ListUsersAndInvitesUseCase: listUsersAndInvites,
}
}
func (h *InviteHandler) CreateInvite(w http.ResponseWriter, r *http.Request) {
var request CreateInviteRequest
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
}
userId, ok := claims.UserId(r)
if !ok {
http.Error(w, apperr.UnauthorizedErrorMessage, http.StatusUnauthorized)
return
}
created, err := h.CreateInviteUseCase.CreateInvite(useCases.CreateInviteCommand{
Email: request.Email,
InvitedBy: userId,
})
if err != nil {
writeCreateInviteError(w, err)
return
}
writeInviteResponse(w, http.StatusCreated, created)
}
func writeInviteResponse(w http.ResponseWriter, status int, entry invite.Invite) {
body, err := json.Marshal(inviteResponse{
ID: entry.ID,
Kind: useCases.EntryKindInvite,
Email: entry.Email,
Status: string(entry.StatusAt(time.Now())),
CreatedAt: entry.CreatedAt,
ExpiresAt: entry.ExpiresAt,
})
if err != nil {
http.Error(w, "Internal server error", http.StatusInternalServerError)
return
}
w.Header().Set("Cache-Control", "no-store")
w.WriteHeader(status)
_, _ = w.Write(body)
}
func parseInviteId(r *http.Request) (uint32, error) {
id, err := strconv.ParseUint(chi.URLParam(r, "id"), 10, 32)
return uint32(id), err
}
func (h *InviteHandler) CancelInvite(w http.ResponseWriter, r *http.Request) {
id, err := parseInviteId(r)
if err != nil {
http.Error(w, apperr.IdUint32ErrorMessage, http.StatusBadRequest)
return
}
if err := h.CancelInviteUseCase.CancelInvite(id); err != nil {
writeManageInviteError(w, err)
return
}
w.WriteHeader(http.StatusNoContent)
}
func (h *InviteHandler) RenewInvite(w http.ResponseWriter, r *http.Request) {
id, err := parseInviteId(r)
if err != nil {
http.Error(w, apperr.IdUint32ErrorMessage, http.StatusBadRequest)
return
}
userId, ok := claims.UserId(r)
if !ok {
http.Error(w, apperr.UnauthorizedErrorMessage, http.StatusUnauthorized)
return
}
renewed, err := h.RenewInviteUseCase.RenewInvite(useCases.RenewInviteCommand{ID: id, RenewedBy: userId})
if err != nil {
writeManageInviteError(w, err)
return
}
writeInviteResponse(w, http.StatusOK, renewed)
}
func writeManageInviteError(w http.ResponseWriter, err error) {
switch {
case errors.Is(err, invite.ErrInviteNotFound):
http.Error(w, apperr.InviteNotFoundErrorMessage, http.StatusNotFound)
case errors.Is(err, invite.ErrInviteAlreadyAccepted):
http.Error(w, apperr.InviteAlreadyAcceptedErrorMessage, http.StatusConflict)
case errors.Is(err, invite.ErrInviteEmailNotSent):
http.Error(w, apperr.InviteNotSentErrorMessage, http.StatusInternalServerError)
case errors.Is(err, user.ErrUserNotFound):
http.Error(w, apperr.UnauthorizedErrorMessage, http.StatusUnauthorized)
default:
http.Error(w, "Internal server error", http.StatusInternalServerError)
}
}
func writeCreateInviteError(w http.ResponseWriter, err error) {
switch {
case errors.Is(err, invite.ErrEmailHasAccount):
http.Error(w, apperr.EmailHasAccountErrorMessage, http.StatusConflict)
case errors.Is(err, invite.ErrPendingInvite):
http.Error(w, apperr.PendingInviteErrorMessage, http.StatusConflict)
case errors.Is(err, invite.ErrInviteEmailNotSent):
http.Error(w, apperr.InviteNotSentErrorMessage, http.StatusInternalServerError)
case errors.Is(err, user.ErrUserNotFound):
http.Error(w, apperr.UnauthorizedErrorMessage, http.StatusUnauthorized)
default:
http.Error(w, "Internal server error", http.StatusInternalServerError)
}
}
func (h *InviteHandler) ListUsers(w http.ResponseWriter, _ *http.Request) {
entries := h.ListUsersAndInvitesUseCase.ListUsersAndInvites()
items := make([]any, 0, len(entries))
for _, entry := range entries {
if entry.Kind == useCases.EntryKindInvite {
items = append(items, inviteListItem{entry.ID, entry.Kind, entry.Email, entry.Status, entry.CreatedAt})
continue
}
items = append(items, userListItem{entry.ID, entry.Kind, entry.Username, entry.DisplayName, entry.Email, entry.Role, entry.Status, entry.CreatedAt})
}
body, err := json.Marshal(items)
if err != nil {
http.Error(w, "Internal server error", http.StatusInternalServerError)
return
}
w.Header().Set("Cache-Control", "no-store")
_, _ = w.Write(body)
}
+70
View File
@@ -0,0 +1,70 @@
package user
import (
"RenewCMS/api/pkg/apperr"
"RenewCMS/api/pkg/claims"
"RenewCMS/api/pkg/publicuser"
validator "RenewCMS/api/pkg/validator"
"RenewCMS/internal/domain/user"
"RenewCMS/internal/infrastructure/useCases"
"encoding/json"
"errors"
"net/http"
)
type Handler struct {
UpdateProfileUseCase *useCases.UpdateUserProfileUseCase
}
type UpdateProfileRequest struct {
DisplayName *string `json:"display_name" validate:"required"`
}
func NewHandler(updateProfile *useCases.UpdateUserProfileUseCase) *Handler {
return &Handler{
UpdateProfileUseCase: updateProfile,
}
}
func (h *Handler) UpdateMe(w http.ResponseWriter, r *http.Request) {
var request UpdateProfileRequest
err := json.NewDecoder(r.Body).Decode(&request)
if err != nil {
http.Error(w, apperr.BodyErrorMessage, http.StatusBadRequest)
return
}
err = validator.Validate.Struct(request)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
userId, ok := claims.UserId(r)
if !ok {
http.Error(w, apperr.UnauthorizedErrorMessage, http.StatusUnauthorized)
return
}
updatedUser, err := h.UpdateProfileUseCase.UpdateDisplayName(userId, *request.DisplayName)
if err != nil {
if errors.Is(err, user.ErrInvalidDisplayName) {
http.Error(w, apperr.DisplayNameErrorMessage, http.StatusBadRequest)
return
}
if errors.Is(err, user.ErrUserNotFound) {
http.Error(w, apperr.UnauthorizedErrorMessage, http.StatusUnauthorized)
return
}
http.Error(w, "Internal server error", http.StatusInternalServerError)
return
}
body, err := json.Marshal(publicuser.New(updatedUser))
if err != nil {
http.Error(w, "Internal server error", http.StatusInternalServerError)
return
}
w.Header().Set("Cache-Control", "no-store")
_, _ = w.Write(body)
}
+18
View File
@@ -77,3 +77,21 @@ func RequireVerifiedUser(getUser *useCases.GetUserUseCase) func(http.Handler) ht
}) })
} }
} }
func RequireOwner(getUser *useCases.GetUserUseCase) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
currentUser, ok := resolveCurrentUser(getUser, w, r)
if !ok {
return
}
if currentUser.Role != user.RoleOwner {
http.Error(w, apperr.OwnerRequiredErrorMessage, http.StatusForbidden)
return
}
next.ServeHTTP(w, r)
})
}
}
+15 -1
View File
@@ -2,6 +2,7 @@ package middleware
import ( import (
"RenewCMS/api/pkg/apperr" "RenewCMS/api/pkg/apperr"
"RenewCMS/api/pkg/claims"
"net/http" "net/http"
"strconv" "strconv"
"sync" "sync"
@@ -14,12 +15,25 @@ type rateLimitWindow struct {
} }
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 })
}
func NewUserRateLimiter(maxAttempts int, window time.Duration) func(http.Handler) http.Handler {
return newKeyedRateLimiter(maxAttempts, window, userRateLimitKey)
}
func userRateLimitKey(r *http.Request) string {
userId, _ := claims.UserId(r)
return strconv.FormatUint(uint64(userId), 10)
}
func newKeyedRateLimiter(maxAttempts int, window time.Duration, keyOf func(*http.Request) string) func(http.Handler) http.Handler {
var mu sync.Mutex var mu sync.Mutex
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, r.RemoteAddr, maxAttempts, window) retryAfter, allowed := recordAttempt(&mu, windows, keyOf(r), maxAttempts, window)
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)
+20
View File
@@ -4,6 +4,8 @@ const LogsErrorMessage = "Access to the requested resource is forbidden due to i
const BodyErrorMessage = "The request cannot be processed due to a mismatch in the format of the body." const BodyErrorMessage = "The request cannot be processed due to a mismatch in the format of the body."
const IdUint32ErrorMessage = "The server expects the ID to be in the format of an unsigned 32-bit integer (uint32)." const IdUint32ErrorMessage = "The server expects the ID to be in the format of an unsigned 32-bit integer (uint32)."
const ArticleNotFoundErrorMessage = "Article not found" const ArticleNotFoundErrorMessage = "Article not found"
const ImageNotFoundErrorMessage = "Image not found"
const DisplayNameErrorMessage = "Display name must be 60 characters or fewer."
const ArticleTitleErrorMessage = "Article title must be between 3 and 200 characters." const ArticleTitleErrorMessage = "Article title must be between 3 and 200 characters."
const RegistrationClosedErrorMessage = "You are not allowed to create a user. Log in or reset database." const RegistrationClosedErrorMessage = "You are not allowed to create a user. Log in or reset database."
const RegistrationFailedErrorMessage = "Registration failed. Please try again later." const RegistrationFailedErrorMessage = "Registration failed. Please try again later."
@@ -14,3 +16,21 @@ 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 EmailHasAccountErrorMessage = "This address already has an account."
const PendingInviteErrorMessage = "There's already a pending invite for this address."
const InviteNotSentErrorMessage = "Couldn't send the invite. Try again in a moment."
const InviteNotFoundErrorMessage = "Invite not found"
const InviteAlreadyAcceptedErrorMessage = "This invite has already been accepted."
const InviteInvalidErrorMessage = "This invite link doesn't work."
const InviteExpiredErrorMessage = "This invite has expired."
const OwnerRequiredErrorMessage = "Only the owner can do this."
const UsernameTakenErrorMessage = "That username is taken. Try another."
const MediaQueryErrorMessage = "The media query is invalid."
const MediaFilenameErrorMessage = "Enter a filename."
const MediaMergeConflictErrorMessage = "Some of the images to merge changed. Refresh and try again."
const MediaMergeRequestErrorMessage = "Choose an image to keep and at least one other image to merge into it."
const UpdateNotPreparedErrorMessage = "This server cannot update itself yet."
const UpdateAlreadyRunningErrorMessage = "An update is already running or waiting to be installed."
const NothingToUpdateErrorMessage = "There is nothing to update."
const UpdateRefusedErrorMessage = "This update cannot be downloaded."
const UpdateRestartMismatchErrorMessage = "The update state changed. Reload the page and try again."
+30
View File
@@ -0,0 +1,30 @@
package publicuser
import (
"RenewCMS/internal/domain/user"
"time"
)
type PublicUser struct {
ID uint32 `json:"id"`
Username string `json:"username"`
Email string `json:"email"`
IsVerified bool `json:"is_verified"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
DisplayName string `json:"display_name"`
Role user.Role `json:"role"`
}
func New(u user.User) PublicUser {
return PublicUser{
ID: u.ID,
Username: u.Username,
Email: u.Email,
IsVerified: u.IsVerified,
CreatedAt: u.CreatedAt,
UpdatedAt: u.UpdatedAt,
DisplayName: u.DisplayName,
Role: u.Role,
}
}
+49
View File
@@ -0,0 +1,49 @@
package upload
import (
"RenewCMS/api/pkg/apperr"
"RenewCMS/internal/domain/image"
"errors"
"net/http"
)
const multipartOverheadAllowance = 1 << 20
const fileField = "file"
func ReadImageInput(w http.ResponseWriter, r *http.Request, uploadedById uint32) (image.ImageInput, func(), bool) {
r.Body = http.MaxBytesReader(w, r.Body, image.MaxImageSize+multipartOverheadAllowance)
file, header, err := r.FormFile(fileField)
if err != nil {
var tooLarge *http.MaxBytesError
if errors.As(err, &tooLarge) {
http.Error(w, image.ErrImageTooLarge.Error(), http.StatusRequestEntityTooLarge)
return image.ImageInput{}, nil, false
}
http.Error(w, apperr.BodyErrorMessage, http.StatusBadRequest)
return image.ImageInput{}, nil, false
}
input := image.ImageInput{
Content: file,
Filename: header.Filename,
Size: header.Size,
ContentType: header.Header.Get("Content-Type"),
UploadedByID: uploadedById,
}
return input, func() { _ = file.Close() }, true
}
func WriteCreateError(w http.ResponseWriter, err error) {
switch {
case errors.Is(err, image.ErrImageTypeNotAllowed):
http.Error(w, err.Error(), http.StatusUnsupportedMediaType)
case errors.Is(err, image.ErrImageTooLarge):
http.Error(w, err.Error(), http.StatusRequestEntityTooLarge)
case errors.Is(err, image.ErrImageUnreadable):
http.Error(w, err.Error(), http.StatusBadRequest)
default:
http.Error(w, "Internal server error", http.StatusInternalServerError)
}
}
+14 -1
View File
@@ -1,9 +1,22 @@
package validator package validator
import "github.com/go-playground/validator/v10" import (
"regexp"
"github.com/go-playground/validator/v10"
)
const inviteEmailTag = "inviteemail"
var inviteEmailPattern = regexp.MustCompile(`^[^\s@]+@[^\s@.]+(\.[^\s@.]+)+$`)
var Validate *validator.Validate var Validate *validator.Validate
func InitValidator() { func InitValidator() {
Validate = validator.New() Validate = validator.New()
_ = Validate.RegisterValidation(inviteEmailTag, isInviteEmail)
}
func isInviteEmail(field validator.FieldLevel) bool {
return inviteEmailPattern.MatchString(field.Field().String())
} }
+104 -3
View File
@@ -4,12 +4,16 @@ import (
"RenewCMS/api/handlers/article" "RenewCMS/api/handlers/article"
"RenewCMS/api/handlers/auth" "RenewCMS/api/handlers/auth"
"RenewCMS/api/handlers/frontend" "RenewCMS/api/handlers/frontend"
"RenewCMS/api/handlers/image" "RenewCMS/api/handlers/media"
"RenewCMS/api/handlers/settings"
"RenewCMS/api/handlers/staticimages" "RenewCMS/api/handlers/staticimages"
"RenewCMS/api/handlers/update"
"RenewCMS/api/handlers/user"
"RenewCMS/api/middleware" "RenewCMS/api/middleware"
"RenewCMS/internal/infrastructure/config" "RenewCMS/internal/infrastructure/config"
"encoding/json" "encoding/json"
"net/http" "net/http"
"time"
"github.com/MadAppGang/httplog" "github.com/MadAppGang/httplog"
"github.com/go-chi/chi/v5" "github.com/go-chi/chi/v5"
@@ -33,7 +37,6 @@ func NewArticleRouter(container *UseCases) http.Handler {
r := chi.NewRouter() r := chi.NewRouter()
articleHandler := article.NewHandler(container.CreateArticleUseCase, container.GetArticleUseCase, container.ListArticlesUseCase, container.DeleteArticleUseCase, container.UpdateArticleUseCase, container.GetUserUseCase) articleHandler := article.NewHandler(container.CreateArticleUseCase, container.GetArticleUseCase, container.ListArticlesUseCase, container.DeleteArticleUseCase, container.UpdateArticleUseCase, container.GetUserUseCase)
imageHandler := image.NewHandler(container.CreateImageUseCase, container.GetArticleUseCase, container.UpdateArticleUseCase)
r.Group(func(r chi.Router) { r.Group(func(r chi.Router) {
r.Get("/", articleHandler.ListArticles) r.Get("/", articleHandler.ListArticles)
@@ -48,7 +51,6 @@ func NewArticleRouter(container *UseCases) http.Handler {
r.Patch("/{id}", articleHandler.UpdateArticleBody) r.Patch("/{id}", articleHandler.UpdateArticleBody)
r.Patch("/{id}/publish", articleHandler.PublishArticle) r.Patch("/{id}/publish", articleHandler.PublishArticle)
r.Patch("/{id}/unpublish", articleHandler.UnpublishArticle) r.Patch("/{id}/unpublish", articleHandler.UnpublishArticle)
r.Post("/{id}/image", imageHandler.PostImage)
}) })
return r return r
} }
@@ -60,6 +62,7 @@ func NewAuthRouter(container *UseCases, isProduction bool, rateLimit config.Auth
verificationHandler := auth.NewVerificationHandler(container.VerifyUserUseCase, container.CancelRegistrationUseCase, isProduction) verificationHandler := auth.NewVerificationHandler(container.VerifyUserUseCase, container.CancelRegistrationUseCase, isProduction)
meHandler := auth.NewMeHandler(container.GetUserUseCase) meHandler := auth.NewMeHandler(container.GetUserUseCase)
passwordResetHandler := auth.NewPasswordResetHandler(container.RequestPasswordResetUseCase, container.ResetPasswordUseCase) passwordResetHandler := auth.NewPasswordResetHandler(container.RequestPasswordResetUseCase, container.ResetPasswordUseCase)
acceptInviteHandler := auth.NewAcceptInviteHandler(container.GetInviteUseCase, container.AcceptInviteUseCase, container.Token, isProduction)
r.Post("/register", loginHandler.Register) r.Post("/register", loginHandler.Register)
r.Get("/registration", loginHandler.RegistrationStatus) r.Get("/registration", loginHandler.RegistrationStatus)
@@ -75,6 +78,12 @@ func NewAuthRouter(container *UseCases, isProduction bool, rateLimit config.Auth
r.Post("/password-reset", passwordResetHandler.RequestPasswordReset) r.Post("/password-reset", passwordResetHandler.RequestPasswordReset)
}) })
r.Post("/password-reset/confirm", passwordResetHandler.ResetPassword) r.Post("/password-reset/confirm", passwordResetHandler.ResetPassword)
r.Group(func(r chi.Router) {
r.Use(middleware.TrustedProxyRealIP(trustedProxies))
r.Use(middleware.NewRateLimiter(rateLimit.MaxAttempts, rateLimit.Window))
r.Get("/invite", acceptInviteHandler.GetInvite)
r.Post("/invite/accept", acceptInviteHandler.AcceptInvite)
})
r.Group(func(r chi.Router) { r.Group(func(r chi.Router) {
r.Use(jwtauth.Verifier(container.Token)) r.Use(jwtauth.Verifier(container.Token))
r.Use(jwtauth.Authenticator(container.Token)) r.Use(jwtauth.Authenticator(container.Token))
@@ -86,6 +95,94 @@ func NewAuthRouter(container *UseCases, isProduction bool, rateLimit config.Auth
return r return r
} }
func NewUserRouter(container *UseCases, rateLimit config.AuthRateLimitSettings, trustedProxies []string) http.Handler {
r := chi.NewRouter()
userHandler := user.NewHandler(container.UpdateUserProfileUseCase)
inviteHandler := user.NewInviteHandler(container.CreateInviteUseCase, container.CancelInviteUseCase, container.RenewInviteUseCase, container.ListUsersAndInvitesUseCase)
r.Use(jwtauth.Verifier(container.Token))
r.Use(jwtauth.Authenticator(container.Token))
r.Use(middleware.RequireCurrentToken(container.GetUserUseCase))
r.Use(middleware.RequireVerifiedUser(container.GetUserUseCase))
r.Patch("/me", userHandler.UpdateMe)
r.Get("/", inviteHandler.ListUsers)
r.Group(func(r chi.Router) {
r.Use(middleware.RequireOwner(container.GetUserUseCase))
r.Use(middleware.TrustedProxyRealIP(trustedProxies))
r.Use(middleware.NewRateLimiter(rateLimit.MaxAttempts, rateLimit.Window))
r.Post("/invite", inviteHandler.CreateInvite)
r.Delete("/invite/{id}", inviteHandler.CancelInvite)
r.Post("/invite/{id}/renew", inviteHandler.RenewInvite)
})
return r
}
func NewSettingsRouter(container *UseCases) http.Handler {
r := chi.NewRouter()
settingsHandler := settings.NewHandler(container.GetSettingsUseCase)
r.Use(jwtauth.Verifier(container.Token))
r.Use(jwtauth.Authenticator(container.Token))
r.Use(middleware.RequireCurrentToken(container.GetUserUseCase))
r.Use(middleware.RequireVerifiedUser(container.GetUserUseCase))
r.Get("/", settingsHandler.GetSettings)
return r
}
const (
updateCheckMaxAttempts = 5
updateCheckWindow = time.Minute
updateDownloadMaxAttempts = 5
updateDownloadWindow = time.Minute
)
func NewSystemRouter(container *UseCases) http.Handler {
r := chi.NewRouter()
updateHandler := update.NewHandler(container.GetUpdateStatusUseCase, container.CheckForUpdateUseCase, container.StartUpdateDownloadUseCase, container.RequestRestartUseCase, container.GetUserUseCase)
r.Use(jwtauth.Verifier(container.Token))
r.Use(jwtauth.Authenticator(container.Token))
r.Use(middleware.RequireCurrentToken(container.GetUserUseCase))
r.Use(middleware.RequireVerifiedUser(container.GetUserUseCase))
r.Get("/update", updateHandler.GetStatus)
r.Group(func(r chi.Router) {
r.Use(middleware.RequireOwner(container.GetUserUseCase))
r.Use(middleware.NewUserRateLimiter(updateCheckMaxAttempts, updateCheckWindow))
r.Post("/update/check", updateHandler.Check)
})
r.Group(func(r chi.Router) {
r.Use(middleware.RequireOwner(container.GetUserUseCase))
r.Use(middleware.NewUserRateLimiter(updateDownloadMaxAttempts, updateDownloadWindow))
r.Post("/update/download", updateHandler.Download)
})
r.Group(func(r chi.Router) {
r.Use(middleware.RequireOwner(container.GetUserUseCase))
r.Post("/update/restart", updateHandler.Restart)
})
return r
}
func NewMediaRouter(container *UseCases) http.Handler {
r := chi.NewRouter()
mediaHandler := media.NewHandler(container.CreateImageUseCase, container.ListMediaUseCase, container.RenameMediaUseCase, container.DeleteMediaUseCase, container.MergeMediaUseCase, container.GetMediaUsageUseCase)
r.Use(jwtauth.Verifier(container.Token))
r.Use(jwtauth.Authenticator(container.Token))
r.Use(middleware.RequireCurrentToken(container.GetUserUseCase))
r.Use(middleware.RequireVerifiedUser(container.GetUserUseCase))
r.Get("/", mediaHandler.List)
r.Post("/", mediaHandler.Upload)
r.Post("/merge", mediaHandler.Merge)
r.Patch("/{id}", mediaHandler.Rename)
r.Delete("/{id}", mediaHandler.Delete)
r.Get("/{id}/usage", mediaHandler.Usage)
return r
}
func InitBackendRoutes(container *UseCases, settings config.Settings) *chi.Mux { func InitBackendRoutes(container *UseCases, settings config.Settings) *chi.Mux {
r := chi.NewRouter() r := chi.NewRouter()
@@ -98,6 +195,10 @@ func InitBackendRoutes(container *UseCases, settings config.Settings) *chi.Mux {
r.Use(jwtauth.Verifier(container.Token)) r.Use(jwtauth.Verifier(container.Token))
r.Mount("/article", NewArticleRouter(container)) r.Mount("/article", NewArticleRouter(container))
}) })
r.Mount("/user", NewUserRouter(container, settings.AuthRateLimit, settings.TrustedProxies))
r.Mount("/settings", NewSettingsRouter(container))
r.Mount("/media", NewMediaRouter(container))
r.Mount("/system", NewSystemRouter(container))
r.Mount("/auth", NewAuthRouter(container, settings.IsProduction(), settings.AuthRateLimit, settings.TrustedProxies)) r.Mount("/auth", NewAuthRouter(container, settings.IsProduction(), settings.AuthRateLimit, settings.TrustedProxies))
return r return r
+10
View File
@@ -0,0 +1,10 @@
package main
import (
"RenewCMS/internal/infrastructure/update/releasesign"
"os"
)
func main() {
os.Exit(releasesign.Run(os.Args[1:], os.Stdout, os.Stderr))
}
+90
View File
@@ -0,0 +1,90 @@
package main
import (
"RenewCMS/api"
"RenewCMS/internal/domain/update"
"flag"
"fmt"
"io"
"log"
)
const (
enableCommand = "enable-browser-updates"
disableCommand = "disable-browser-updates"
applyCommand = "apply-update"
exitOK = 0
exitError = 1
exitUsage = 2
usageText = "usage: renewcms [--version]\n" +
" renewcms enable-browser-updates [--service NAME] [--binary PATH] [--data-dir DIR] [--port PORT]\n" +
" renewcms disable-browser-updates [--service NAME] [--data-dir DIR]\n" +
" renewcms apply-update --binary PATH --data-dir DIR [--service NAME] [--port PORT]"
applyNeedsFlagsMessage = "apply-update needs --binary and --data-dir."
)
func runCommand(args []string, stdout io.Writer, stderr io.Writer) int {
name, rest := args[0], args[1:]
switch name {
case enableCommand:
return withOptions(name, rest, stderr, func(options update.InstallOptions) int {
message, err := api.InitBrowserUpdateCommands().Enable.Enable(options)
return printOutcome(stdout, stderr, message, err)
})
case disableCommand:
return withOptions(name, rest, stderr, func(options update.InstallOptions) int {
message, err := api.InitBrowserUpdateCommands().Disable.Disable(options)
return printOutcome(stdout, stderr, message, err)
})
case applyCommand:
return withOptions(name, rest, stderr, func(options update.InstallOptions) int {
return apply(options, stderr)
})
}
fmt.Fprintln(stderr, usageText)
return exitUsage
}
func withOptions(name string, args []string, stderr io.Writer, run func(update.InstallOptions) int) int {
flags := flag.NewFlagSet(name, flag.ContinueOnError)
flags.SetOutput(stderr)
var options update.InstallOptions
flags.StringVar(&options.Service, "service", "", "systemd service name of RenewCMS")
flags.StringVar(&options.Binary, "binary", "", "path of the RenewCMS binary")
flags.StringVar(&options.DataDir, "data-dir", "", "directory that holds DB_FILE")
flags.StringVar(&options.Port, "port", "", "port RenewCMS listens on")
if err := flags.Parse(args); err != nil {
return exitUsage
}
return run(options)
}
func printOutcome(stdout io.Writer, stderr io.Writer, message string, err error) int {
if err != nil {
fmt.Fprintln(stderr, err)
return exitError
}
fmt.Fprintln(stdout, message)
return exitOK
}
func apply(options update.InstallOptions, stderr io.Writer) int {
if options.Binary == "" || options.DataDir == "" {
fmt.Fprintln(stderr, applyNeedsFlagsMessage)
return exitUsage
}
if options.Service == "" {
options.Service = update.DefaultService
}
if options.Port == "" {
options.Port = update.DefaultPort
}
if err := api.InitApplyUpdateCommand(options).Apply(); err != nil {
log.Printf("apply-update failed: %v", err)
return exitError
}
return exitOK
}
+27 -6
View File
@@ -8,6 +8,7 @@ import (
"errors" "errors"
"fmt" "fmt"
"log" "log"
"net"
"net/http" "net/http"
"os" "os"
"os/signal" "os/signal"
@@ -32,7 +33,8 @@ var possibleEnvFileLocations = []string{".env", "../.env"}
var requiredEnvVars = []string{ var requiredEnvVars = []string{
"PUBLIC_URL", "PUBLIC_URL",
"JWT_SECRET", "JWT_SECRET",
"SMTP_EMAIL", "SMTP_LOGIN",
"SMTP_SENDER",
"SMTP_PASSWORD", "SMTP_PASSWORD",
"SMTP_HOST", "SMTP_HOST",
"SMTP_PORT", "SMTP_PORT",
@@ -46,9 +48,19 @@ var envDefaults = map[string]string{
"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",
} }
const versionFlag = "--version"
func main() { func main() {
if len(os.Args) == 2 && os.Args[1] == versionFlag {
fmt.Println(version)
return
}
if len(os.Args) > 1 {
os.Exit(runCommand(os.Args[1:], os.Stdout, os.Stderr))
}
if err := run(); err != nil { if err := run(); err != nil {
log.Fatal(err) log.Fatal(err)
} }
@@ -61,13 +73,14 @@ func run() error {
if err != nil { if err != nil {
return err return err
} }
settings.Version = version
container, closeDb := api.InitContainer(settings) container, closeDb := api.InitContainer(settings)
defer closeDatabase(closeDb) defer closeDatabase(closeDb)
validator.InitValidator() validator.InitValidator()
server := newServer(api.InitRoutes(container, settings), settings) server := newServer(api.InitRoutes(container, settings), settings)
return serveUntilStopped(server, settings) return serveUntilStopped(server, settings, container.RecordRunningInfoUseCase.Record)
} }
func initEnvVariables() { func initEnvVariables() {
@@ -118,12 +131,12 @@ func newServer(handler http.Handler, settings config.Settings) *http.Server {
} }
} }
func serveUntilStopped(server *http.Server, settings config.Settings) error { func serveUntilStopped(server *http.Server, settings config.Settings, recordRunning func() error) error {
stopSignal, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) stopSignal, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop() defer stop()
serverErr := make(chan error, 1) serverErr := make(chan error, 1)
go listen(server, serverErr, settings) go listen(server, serverErr, settings, recordRunning)
select { select {
case err := <-serverErr: case err := <-serverErr:
@@ -133,9 +146,17 @@ func serveUntilStopped(server *http.Server, settings config.Settings) error {
} }
} }
func listen(server *http.Server, serverErr chan<- error, settings config.Settings) { func listen(server *http.Server, serverErr chan<- error, settings config.Settings, recordRunning func() error) {
listener, err := net.Listen("tcp", server.Addr)
if err != nil {
serverErr <- err
return
}
if err := recordRunning(); err != nil {
log.Printf("WARNING: could not write the running-version file: %v", err)
}
log.Printf("RenewCMS %s (%s) listening on %s, public URL %s", version, settings.Environment, server.Addr, settings.PublicURL) log.Printf("RenewCMS %s (%s) listening on %s, public URL %s", version, settings.Environment, server.Addr, settings.PublicURL)
err := server.ListenAndServe() err = server.Serve(listener)
if errors.Is(err, http.ErrServerClosed) { if errors.Is(err, http.ErrServerClosed) {
err = nil err = nil
} }
+13
View File
@@ -21,6 +21,19 @@ api/ ──▶ internal/infrastructure/useCases ──▶ internal/domain
Nothing under `internal/` imports `api/`. Nothing under `internal/` imports `api/`.
### Delivery packages
| Package | Role |
|---|---|
| `api/handlers/user` | Authenticated user endpoints: profile update (`UpdateMe`) and the users list with invitations (`CreateInvite`, `ListUsers`). |
| `api/handlers/media` | The media library under `/v1/media` (list, upload, rename, delete, merge, usage). Images belong to the library, not to an article: deleting an article never deletes an image, and an image's "used in" is read from article bodies each time. |
| `api/pkg/upload` | Multipart `file` reading and the mapping of upload errors (415, 413, 400) shared by both upload routes. |
| `api/pkg/publicuser` | `PublicUser`, the JSON shape of a user with no password, codes or token version. `publicuser.New` converts a domain `user.User`, so handlers never serialise the domain struct directly. |
### Image metadata backfill
At boot, `BackfillImageMetadata` fills `filename`, `size`, `content_type`, `width`, `height` and `sha256` for image rows that lack them, reading the files in `UPLOAD_DIR`. It is idempotent, and a row whose file is missing or unreadable is left as it is without stopping the boot. The old `article_id` column and the `article_images` table are kept and never written.
## Frontend ↔ backend ## Frontend ↔ backend
``` ```
+8 -4
View File
@@ -12,7 +12,8 @@ Copy [`.env.example`](../.env.example) to `.env` to get started. When a required
|-----------------|---------------------------------------------------------------------------------------------------------------------|----------------------------| |-----------------|---------------------------------------------------------------------------------------------------------------------|----------------------------|
| `PUBLIC_URL` | Public base URL of the site, including scheme and no trailing slash. Used for links in emails and in the startup log. | `https://cms.example.com` | | `PUBLIC_URL` | Public base URL of the site, including scheme and no trailing slash. Used for links in emails and in the startup log. | `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. Use a long random value; changing it logs everyone out. | `openssl rand -hex 32` |
| `SMTP_EMAIL` | Sender address and SMTP username. | `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_PASSWORD` | SMTP password. | | | `SMTP_PASSWORD` | SMTP password. | |
| `SMTP_HOST` | SMTP server host. | `smtp.example.com` | | `SMTP_HOST` | SMTP server host. | `smtp.example.com` |
| `SMTP_PORT` | SMTP server port. | `465` | | `SMTP_PORT` | SMTP server port. | `465` |
@@ -26,12 +27,15 @@ Copy [`.env.example`](../.env.example) to `.env` to get started. When a required
| `DB_FILE` | `./data/renewcms.db` | Path to the SQLite database file. Missing parent directories are created. The schema is migrated automatically at startup. | | `DB_FILE` | `./data/renewcms.db` | Path to the SQLite database file. Missing parent directories are created. The schema is migrated automatically at startup. |
| `UPLOAD_DIR` | `./data/uploads` | Directory where uploaded images are stored. | | `UPLOAD_DIR` | `./data/uploads` | Directory where uploaded images are stored. |
| `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. 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` or `POST /v1/auth/password-reset` 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 two routes above. | | `AUTH_RATE_LIMIT_WINDOW_SECONDS` | `60` | Length, in seconds, of the fixed rate-limit window for the routes above. |
| `TRUSTED_PROXIES` | *(empty)* | Semicolon-separated list of exact IP addresses (no CIDR) of reverse proxies allowed to supply the client IP via `X-Real-IP` for `POST /v1/auth/login` and `POST /v1/auth/password-reset` rate limiting. 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). |
| `UPDATE_FEED_URL` | `https://git.floriansylvain.fr` | Base URL of the Gitea server that publishes RenewCMS releases. The Settings page asks `{UPDATE_FEED_URL}/api/v1/repos/fsylvain/RenewCMS/releases` when the owner checks for updates. The last result is kept in `update-status.json`, next to `DB_FILE`. |
Relative paths are resolved against the process's working directory. In production, use absolute paths (see [deployment.md](deployment.md)). Relative paths are resolved against the process's working directory. In production, use absolute paths (see [deployment.md](deployment.md)).
For example, `WorkingDirectory=/var/lib/renewcms` with `DB_FILE=./data/renewcms.db` puts the database in `/var/lib/renewcms/data`. Browser-update `--data-dir` must name that directory, because the app reads helper status and update records beside the database. It is not necessarily `WorkingDirectory` or `ReadWritePaths`. Do not change an existing `DB_FILE` merely to match the helper: that could open a different, empty database. See [browser-update setup](deployment.md#browser-updates).
## Adding a variable ## Adding a variable
1. Read it in the code where it is needed (infrastructure or `api/`, never `internal/domain`). 1. Read it in the code where it is needed (infrastructure or `api/`, never `internal/domain`).
+141 -2
View File
@@ -8,7 +8,7 @@ RenewCMS ships as **one self-contained executable**. It serves:
| `/healthz` | Liveness check, returns `200 ok` | | `/healthz` | Liveness check, returns `200 ok` |
| `/*` | The Vue SPA (embedded), with fallback to `index.html` for client-side routes | | `/*` | The Vue SPA (embedded), with fallback to `index.html` for client-side routes |
Its only runtime state is the SQLite database (`DB_FILE`) and the uploads directory (`UPLOAD_DIR`). Nothing else needs to be installed on the server. Runtime state includes the SQLite database (`DB_FILE`), uploads (`UPLOAD_DIR`), and update records, staged binaries and backups beside the database. Running a release binary needs no Go, Bun or Node installation. Browser updates additionally require Linux with systemd and the helper setup below.
## 1. Build ## 1. Build
@@ -19,8 +19,146 @@ task build # this OS/arch → bin/renewcms[.exe]
task release # all targets → bin/renewcms_<version>_<os>_<arch>[.exe] task release # all targets → bin/renewcms_<version>_<os>_<arch>[.exe]
``` ```
`task release` also signs the release: it writes `bin/checksums.txt` (SHA-256 of the six binaries) and signs it into `bin/checksums.txt.sig` with an Ed25519 key. It refuses to start, before building anything, unless `RELEASE_SIGNING_KEY` points to the private key file and that key matches the public key committed as `internal/infrastructure/update/release.pub`. The one-time setup is below.
The frontend is built once and embedded into every binary. The binaries are static (`CGO_ENABLED=0`), so a Linux build runs on any distribution. The version comes from `git describe`: tag a release (`git tag v1.2.0`) before building, and the binary logs its version at startup. The frontend is built once and embedded into every binary. The binaries are static (`CGO_ENABLED=0`), so a Linux build runs on any distribution. The version comes from `git describe`: tag a release (`git tag v1.2.0`) before building, and the binary logs its version at startup.
### Release signing key (maintainers, once)
1. Run `task release:keygen -- <path>` with a path outside the repository (for example `~/.renewcms/release.key`). The private key is written there and never leaves your machine; keygen refuses a path inside the work tree.
2. Commit the printed public key as `internal/infrastructure/update/release.pub`. A placeholder key (32 zero bytes) prevents signing. Official releases already embed the project's public key; this setup is for release maintainers, not site operators. Never copy the private signing key to a CMS server.
3. Export `RELEASE_SIGNING_KEY=<path to the private key>` before every `task release`.
To check a download by hand: `go run ./cmd/releasesign verify checksums.txt`, with `checksums.txt.sig` next to it, then compare the binary's hash with the matching line of `checksums.txt`.
### Update checks
The owner's Settings page asks the release feed for the newest release (see `UPDATE_FEED_URL` in [configuration.md](configuration.md)) and keeps the last result in `update-status.json`, next to `DB_FILE`. Back it up with the rest of the data directory if you like; it is rebuilt by the next check when missing. The Settings page reports a newer version. To install it from the browser, set up [Browser updates](#browser-updates) once on the server.
### Update downloads
Once the restart helper is installed (it writes `update-helper.json` next to `DB_FILE`), the owner's Update button downloads the new binary, `checksums.txt` and `checksums.txt.sig` from the release feed host over https only, checks the ed25519 signature and the SHA-256, runs the staged binary with `--version`, copies the database into `backups/` (the last 3 copies are kept) and stages everything under `updates/<tag>/`, all next to `DB_FILE`. The job record is `update-job.json`. Nothing running is replaced and the site is not restarted by the download: the owner's Restart button does that, as described in [Browser updates](#browser-updates). `renewcms --version` prints the build version and exits.
### Browser updates
The owner's Restart button installs a downloaded update, or just restarts the site, without touching the server by hand. The app itself stays unprivileged: the systemd unit below keeps `ProtectSystem=strict` and only the data directory (the directory that holds `DB_FILE`) is writable. The only privileged code is a small helper, the same binary started as `renewcms apply-update` by a systemd service that runs as root.
First install v2.6.0-beta or newer manually, back up the database, uploads and current binary, and confirm the app runs as an unprivileged service user. The binary and its parent directory should be controlled by root. Owners can start updates and restarts; admins have read-only update status.
#### Find the actual database directory
The helper's `--data-dir` must be the directory containing `DB_FILE`. Inspect the relevant settings without printing the configuration's secrets:
```sh
sudo systemctl show renewcms -p User -p WorkingDirectory
sudo grep '^DB_FILE=' /etc/renewcms/renewcms.env
```
| WorkingDirectory | DB_FILE | Correct --data-dir |
| --- | --- | --- |
| `/var/lib/renewcms` | `/var/lib/renewcms/renewcms.db` | `/var/lib/renewcms` |
| `/var/lib/renewcms` | `./data/renewcms.db` | `/var/lib/renewcms/data` |
Leave an existing `DB_FILE` unchanged: changing it can open a different, empty database. Configure the helper to match the existing database instead.
#### Enable the helper
For this guide's absolute database path and port 8080, run:
```sh
sudo /opt/renewcms/renewcms enable-browser-updates \
--service renewcms \
--binary /opt/renewcms/renewcms \
--data-dir /var/lib/renewcms \
--port 8080
```
Replace these flags with your actual paths and port. For the relative database example above and port 8788, use `--data-dir /var/lib/renewcms/data --port 8788`. The absolute executable path works even when `/opt/renewcms` is absent from sudo's PATH.
Without explicit flags, discovery reads `/etc/systemd/system/renewcms.service` and takes its first `ReadWritePaths` entry as the data directory. It does not resolve `DB_FILE`, so explicit flags are necessary when these directories differ or the unit lives elsewhere. The port comes from `--port`, else `PORT` in the unit's `EnvironmentFile`, else 8080. The helper polls `/healthz` on `127.0.0.1` at that port. It then:
- writes `renewcms-update.path` and `renewcms-update.service` next to your other units in `/etc/systemd/system` (no secret and no environment value goes into them);
- runs `systemctl daemon-reload` and enables and starts the path unit;
- writes `update-helper.json` in the data directory last, so the Settings page only offers Update and Restart once everything else worked.
Running it again rewrites the units and the status file to the current values. If a step fails, the units it wrote are removed again and `update-helper.json` is not written.
#### Verify setup and test a plain restart
For the layout above, run these checks, substituting your service user and database directory if different:
```sh
systemctl is-active renewcms-update.path
systemctl is-enabled renewcms-update.path
sudo systemctl cat renewcms-update.service
sudo -u renewcms cat /var/lib/renewcms/update-helper.json
```
Expect `active`, `enabled`, an `ExecStart` with the correct paths and port, and readable JSON. Reload Settings as owner. With no update waiting, Restart should appear. Press it, confirm the plain restart dialog, and expect the overlay followed by the site returning and a “Site restarted” message.
Then run:
```sh
systemctl is-active renewcms
sudo cat /var/lib/renewcms/update-result.json
sudo cat /var/lib/renewcms/update-running.json
sudo journalctl -u renewcms-update.service -n 30 --no-pager
curl --retry 5 --retry-connrefused --retry-delay 2 -fsS http://127.0.0.1:8080/healthz
```
Expect an active app service, result `kind: restart` with `outcome: succeeded`, the installed version and a new process in `update-running.json`, and health response `ok`. Check `/healthz` through your public HTTPS hostname too. A brief connection refusal during startup can be transient. The oneshot helper normally becomes inactive after success; the path unit stays active.
#### Install a future update
When a newer signed release exists, check for updates in Settings, read its notes and click Update. The site stays online while the files are downloaded, verified and backed up. Wait for Ready to install, then click Restart and confirm installation. Afterwards, check the version in Settings, public health, the helper journal and `update-result.json`: expect `kind: update` and `outcome: succeeded`.
On the latest release you can test only a plain restart. Test installation, forced rollback and hostile-file cases on an isolated Linux/systemd machine with its own data and service. The helper unit names are fixed, so setting up another instance on the same machine replaces that machine's existing helper configuration.
#### Troubleshooting
- **Restart is missing:** reload Settings, confirm you are owner, and inspect `GET /v1/system/update` in the browser's Network panel. For an idle owner, `can_apply: false` means the app did not detect the helper. Check that `update-helper.json` is beside the actual database and readable by the service user.
- **Wrong helper directory:** disable the helper with the old `--data-dir`, then enable it with the correct directory and port. Do not change `DB_FILE` to compensate.
- **Overlay does not clear:** inspect the helper journal, `update-result.json` and `update-running.json` in the actual database directory. Check localhost health on the configured port, then public health through the proxy. Do not cache `/healthz` at the proxy.
- **Old binary panics on `--version`:** older releases may interpret it as normal startup and require server environment variables. v2.6.0-beta and newer print their version without loading configuration. A separately launched process failing this way does not stop the systemd service.
- **Download or verification fails:** inspect the app journal. All assets and redirects must use HTTPS on the configured feed host. The release must include the six binaries, `checksums.txt` and `checksums.txt.sig`.
- **Update rolls back:** check the previous version and helper journal. Automatic rollback restores the binary, not the database; schema changes still require a recovery plan.
#### Disable the helper
Use the same database directory you supplied when enabling it:
```sh
sudo /opt/renewcms/renewcms disable-browser-updates \
--service renewcms \
--data-dir /var/lib/renewcms
```
This stops and disables the path unit, removes both unit files and `update-helper.json`, and runs `systemctl daemon-reload`. The restart request, result, staged files and backups stay. `can_apply` becomes false: Settings shows “Not prepared” when an update is available, or “You're up to date” without Restart otherwise.
How it works: pressing Restart makes the app write `update-restart-request.json` in the data directory. The path unit notices it and starts the helper, which deletes the request, checks the staged files again, installs the update, restarts the service and waits up to 60 seconds for the site to answer `/healthz` and for the new process to write `update-running.json`. The helper writes its outcome to `update-result.json`; the Settings page reads it. The technical reason of a failure goes to the journal only (`journalctl -u renewcms-update`).
Files in the data directory:
| File | Written by | What |
|------|------------|------|
| `update-restart-request.json` | the app | The request: `kind` (`update` or `restart`), `tag` (updates only), `requested_at`, `requested_by`. The helper deletes it first. |
| `update-result.json` | the helper | The outcome: `running`, `succeeded`, `rolled_back` or `failed`, with `kind`, `tag`, `from_version`, `started_at`, `finished_at`. It stays until the next download or restart. |
| `update-helper.json` | `enable-browser-updates` | Marks browser updates as set up (`version`, `service`, `binary`, `data_dir`, `installed_at`). |
| `update-running.json` | the server, at every start | `version`, `pid` and `started_at` of the running process. The helper uses it to tell a new process from an old one. |
What is supported and what is not:
- Linux with systemd only. Not Windows, macOS, Docker or other init systems: there the command refuses with a clear message and the Settings page keeps showing "Not prepared".
- Before the swap the helper copies the staged files into a private temp directory, checks the signature and the SHA-256 on that copy and installs the copy. It refuses symbolic links under `updates/` and on the request file.
- The previous binary is kept as `<name>.previous` next to the binary, and the update download keeps a database backup in `backups/`.
- If the new version does not come up within 60 seconds, the helper puts `<name>.previous` back, restarts the service and records `rolled_back`. If even that fails the result is `failed` and the journal says so loudly.
- A plain restart (no update waiting) restarts the service the same way and records `succeeded` or `failed`; no binary is replaced.
- Only the owner can press Restart. The site is unavailable for about 10 seconds.
#### Verification status
A real v2.6.0-beta plain browser restart was confirmed on Linux/systemd on 2026-10-02: the path unit triggered the helper, a new server process started, the result was `succeeded`, and public health returned `ok`. Real signed installation, forced rollback and adversarial filesystem checks remain unverified. The manual cases are listed in [the restart QA procedure](../features/updates_restart_helper.qa.md).
## 2. Lay out the server ## 2. Lay out the server
The following is a suggested layout for Linux: The following is a suggested layout for Linux:
@@ -47,7 +185,8 @@ PORT=8080
DB_FILE=/var/lib/renewcms/renewcms.db DB_FILE=/var/lib/renewcms/renewcms.db
UPLOAD_DIR=/var/lib/renewcms/uploads UPLOAD_DIR=/var/lib/renewcms/uploads
JWT_SECRET=<openssl rand -hex 32> JWT_SECRET=<openssl rand -hex 32>
SMTP_EMAIL=noreply@example.com SMTP_LOGIN=noreply@example.com
SMTP_SENDER=noreply@example.com
SMTP_PASSWORD=... SMTP_PASSWORD=...
SMTP_HOST=smtp.example.com SMTP_HOST=smtp.example.com
SMTP_PORT=465 SMTP_PORT=465
+12 -4
View File
@@ -11,7 +11,7 @@ The visual spec of record for the back-office SPA and the transactional emails,
| `states.md` | Every state of every screen with its trigger, and the HTTP-status-to-copy table | | `states.md` | Every state of every screen with its trigger, and the HTTP-status-to-copy table |
| `screens/<screen>.md` | One file per screen: route, API, and per state the exact copy, fields, alerts, dialogs and toasts | | `screens/<screen>.md` | One file per screen: route, API, and per state the exact copy, fields, alerts, dialogs and toasts |
| `foundations.md` | Colors, contrast, type, spacing, motion and icons, and where the token files are | | `foundations.md` | Colors, contrast, type, spacing, motion and icons, and where the token files are |
| `emails.md` | The two email templates and their variables | | `emails.md` | The three email templates and their variables |
| `source/` | The raw Claude Design export. Open the `.dc.html` boards in a browser for the drawings (they load `support.js` locally and fonts from Google). | | `source/` | The raw Claude Design export. Open the `.dc.html` boards in a browser for the drawings (they load `support.js` locally and fonts from Google). |
## Screens ## Screens
@@ -25,15 +25,23 @@ The visual spec of record for the back-office SPA and the transactional emails,
| [Forgot password](screens/forgot-password.md) | `/register/reset/request` | 6 | `source/RenewCMS Screens Auth.dc.html` | | [Forgot password](screens/forgot-password.md) | `/register/reset/request` | 6 | `source/RenewCMS Screens Auth.dc.html` |
| [Reset password](screens/reset-password.md) | `/register/reset/validate?c=CODE&email=EMAIL` | 7 | `source/RenewCMS Screens Auth.dc.html` | | [Reset password](screens/reset-password.md) | `/register/reset/validate?c=CODE&email=EMAIL` | 7 | `source/RenewCMS Screens Auth.dc.html` |
| [Boot](screens/boot.md) | `any route, first load` | 1 | `source/RenewCMS Screens Back-office.dc.html` | | [Boot](screens/boot.md) | `any route, first load` | 1 | `source/RenewCMS Screens Back-office.dc.html` |
| [Home](screens/home.md) | `/home` | 4 | `source/RenewCMS Screens Back-office.dc.html` | | [Home](screens/home.md) | `/home` | 6 | `source/RenewCMS Screens Back-office.dc.html` |
| [Articles](screens/articles.md) | `/article` | 14 | `source/RenewCMS Screens Back-office.dc.html` | | [Articles](screens/articles.md) | `/article` | 14 | `source/RenewCMS Screens Back-office.dc.html` |
| [New article](screens/new-article.md) | `modal from anywhere · /article/new` | 5 | `source/RenewCMS Screens Back-office.dc.html` | | [New article](screens/new-article.md) | `modal from anywhere · /article/new` | 5 | `source/RenewCMS Screens Back-office.dc.html` |
| [Editor](screens/editor.md) | `/article/:id/edit` | 19 | `source/RenewCMS Screens Back-office.dc.html` | | [Editor](screens/editor.md) | `/article/:id/edit` | 22 | `source/RenewCMS Screens Back-office.dc.html` |
| [Media](screens/media.md) | `/media` | 41 | `source/RenewCMS Screens Back-office.dc.html` |
| [Media picker](screens/media-picker.md) | `/article/:id/edit` (dialog) | 13 | `source/RenewCMS Screens Back-office.dc.html` |
| [Integration](screens/integration.md) | `/integration` | 2 | `source/RenewCMS Screens Back-office.dc.html` | | [Integration](screens/integration.md) | `/integration` | 2 | `source/RenewCMS Screens Back-office.dc.html` |
| [Users](screens/users.md) | `/users` | 17 | `source/RenewCMS Screens Back-office.dc.html` |
| [Settings](screens/settings.md) | `/settings` | 25 | `source/RenewCMS Screens Back-office.dc.html` |
| [Profile](screens/profile.md) | `/profile` | 13 | `source/RenewCMS Screens Back-office.dc.html` |
| [Accept invite](screens/accept-invite.md) | `/invite/accept?c=CODE` | 9 | `source/RenewCMS Screens Auth.dc.html` |
| [Global](screens/global.md) | `any route` | 4 | `source/RenewCMS Screens Back-office.dc.html` | | [Global](screens/global.md) | `any route` | 4 | `source/RenewCMS Screens Back-office.dc.html` |
## Other boards ## Other boards
- `source/MediaFrame.dc.html`: the frame that draws the Media and Media picker states (the Back-office board imports it). Like `AppFrame.dc.html`, it holds the exact values.
- `source/RenewCMS Prototype.dc.html`: the clickable flows (first run, edit and publish, password reset, delete, session expiry mid-edit). - `source/RenewCMS Prototype.dc.html`: the clickable flows (first run, edit and publish, password reset, delete, session expiry mid-edit).
- `source/RenewCMS Handoff.dc.html`: the handoff page the markdown here was generated from. - `source/RenewCMS Handoff.dc.html`: the handoff page the first markdown here was generated from. It predates the Users and Profile screens and the invitation email, so it does not list them. Those are written by hand from the Back-office board, `AppFrame.dc.html`, the Prototype and `emails/invitation.html`.
- `source/RenewCMS Components Product.dc.html`: not regenerated for the new screens either. The matching component changes are in `components.md`, under "Added with the Users and Profile screens" and "Added with roles, invite actions and Settings".
- `source/RenewCMS Directions.dc.html`: the three brand directions (history only). - `source/RenewCMS Directions.dc.html`: the three brand directions (history only).
+142 -10
View File
@@ -6,7 +6,14 @@
|---|---|---|---|---|---| |---|---|---|---|---|---|
| AuthShell | UPageCard, UColorModeSelect | title, description? | none | default, notice, footer | All public routes | | AuthShell | UPageCard, UColorModeSelect | title, description? | none | default, notice, footer | All public routes |
| DashboardShell | UDashboardGroup, UDashboardSidebar, UNavigationMenu, UDashboardPanel, UDashboardNavbar, UBreadcrumb | none (reads route.meta and the session store) | none | default, navbar-right | All verified routes | | DashboardShell | UDashboardGroup, UDashboardSidebar, UNavigationMenu, UDashboardPanel, UDashboardNavbar, UBreadcrumb | none (reads route.meta and the session store) | none | default, navbar-right | All verified routes |
| UserMenu | UDropdownMenu, UButton, UAvatar | none | logout | none | DashboardShell | | UserMenu | UDropdownMenu, UButton, UAvatar (a bottom sheet below md) | displayName?, username, email | logout | none | DashboardShell |
| UsersTable | UTable | rows: UserRow[], loading, canManage: boolean, busyIds: Set | cancel-invite, renew-invite | none | Users (md and up) |
| UserCardList | custom list | same as UsersTable | same as UsersTable | none | Users (below md) |
| RoleBadge | UBadge | role: 'owner'\|'admin' | none | none | Users |
| SettingsPage | custom card | none (reads GET /v1/settings) | none | none | Settings |
| InviteStatusBadge | UBadge | status: 'accepted'\|'pending'\|'expired' | none | none | Users |
| InviteUserModal | UModal, UForm, UFormField, UInput | none | invited(invite) | none | Users |
| ProfileCard | custom card (border, padding, optional footer strip) | title, description | none | default, footer | Profile |
| PageHeader | UPageHeader | title, description? | none | actions, meta | Home, Articles, Integration | | PageHeader | UPageHeader | title, description? | none | actions, meta | Home, Articles, Integration |
| ArticleStatusBadge | UBadge | online: boolean, size?: 'sm'\|'md', pending?: 'publish'\|'unpublish' | none | none | Home, Articles, Editor | | ArticleStatusBadge | UBadge | online: boolean, size?: 'sm'\|'md', pending?: 'publish'\|'unpublish' | none | none | Home, Articles, Editor |
| ArticleTable | UTabs, UInput, UTable, UDropdownMenu, UPagination | articles: Article[], loading, busyIds: Set<number> | publish, unpublish, delete, copy-url | empty, toolbar-right | Articles (md and up) | | ArticleTable | UTabs, UInput, UTable, UDropdownMenu, UPagination | articles: Article[], loading, busyIds: Set<number> | publish, unpublish, delete, copy-url | empty, toolbar-right | Articles (md and up) |
@@ -19,16 +26,16 @@
| SaveStatus | custom (span + UButton) | state: 'clean'\|'dirty'\|'saving'\|'saved'\|'error'\|'offline', savedAt?: Date | retry | none | Editor | | SaveStatus | custom (span + UButton) | state: 'clean'\|'dirty'\|'saving'\|'saved'\|'error'\|'offline', savedAt?: Date | retry | none | Editor |
| PublishControl | UButton | online: boolean, dirty: boolean, pending?: string, disabled? | publish, unpublish | none | Editor | | PublishControl | UButton | online: boolean, dirty: boolean, pending?: string, disabled? | publish, unpublish | none | Editor |
| ArticleDetails | UCard (desktop) / USlideover (mobile) | article: Article | copy-url | none | Editor | | ArticleDetails | UCard (desktop) / USlideover (mobile) | article: Article | copy-url | none | Editor |
| CharacterCounter | custom | value: number, max: number, min?: number, warnAt?: number | none | none | NewArticleModal, Editor, Register | | CharacterCounter | custom | value: number, max: number, min?: number, warnAt?: number | none | none | NewArticleModal, Editor, Register, Accept invite |
| PasswordStrengthHint | custom (in UFormField #help) | rules: { label, met }[], showErrors: boolean | none | none | Register, Reset | | PasswordStrengthHint | custom (in UFormField #help) | rules: { label, met }[], showErrors: boolean | none | none | Register, Reset, Accept invite |
| ResultPanel | custom + UButton | tone: 'success'\|'error'\|'info', icon, title, description, actions: ButtonProps[] | none | default | Pending, Verify, Reset request, Reset, Register (403) | | ResultPanel | custom + UButton | tone: 'success'\|'error'\|'info', icon, title, description, actions: ButtonProps[] | none | default | Pending, Verify, Reset request, Reset, Accept invite, Register (403) |
| CodeBlock | custom (shiki) + UButton | code: string, lang: string, label? | none | none | Integration | | CodeBlock | custom (shiki) + UButton | code: string, lang: string, label? | none | none | Integration |
| EndpointCard | UCard, UBadge, UTabs | method: 'GET', path, description, examples: { fetch, curl, response } | none | none | Integration | | EndpointCard | UCard, UBadge, UTabs | method: 'GET', path, description, examples: { fetch, curl, response } | none | none | Integration |
| ErrorView | custom + UButton | kind: 'not-found'\|'error' | retry | none | Not found, error boundary | | ErrorView | custom + UButton | kind: 'not-found'\|'error' | retry | none | Not found, error boundary |
| OfflineBanner | UBanner | none (reads useOnline) | none | none | DashboardShell | | OfflineBanner | UBanner | none (reads useOnline) | none | none | DashboardShell |
| AppBoot | USkeleton inside DashboardShell | none | none | none | First load of any verified route | | AppBoot | USkeleton inside DashboardShell | none | none | none | First load of any verified route |
Composables behind these components: `useSession`, `useApi`, `useArticles` (the list cache plus actions shared by the table, cards and editor), `useArticleDraft` (dirty state, save, and the sessionStorage mirror), `useImageUpload` (XHR with progress) and `useRetryAfter` (429 countdown). Composables behind these components: `useSession` (it also carries the display name), `useUsers` (the list and the invite action), `useProfile` (the display name draft and save), `useApi`, `useArticles` (the list cache plus actions shared by the table, cards and editor), `useArticleDraft` (dirty state, save, and the sessionStorage mirror), `useImageUpload` (XHR with progress) and `useRetryAfter` (429 countdown).
## Product component specs ## Product component specs
@@ -58,7 +65,7 @@ Responsive 400 px card from sm up, with its top 12 vh from the top. Below sm , t
### DashboardShell ### DashboardShell
The sidebar has three destinations, and the user menu sits at its foot. The top bar carries the breadcrumbs and page title. Collapsing the sidebar leaves a 56 px icon rail. Below lg , the sidebar becomes a slideover. The sidebar has five destinations (Home, Articles, Users, Integration, Settings), and the user menu sits at its foot. The top bar carries the breadcrumbs and page title. Collapsing the sidebar leaves a 56 px icon rail. Below lg , the sidebar becomes a slideover.
RenewCMS RenewCMS
@@ -92,7 +99,7 @@ Mobile top bar. The menu button opens the sidebar as a left slideover.
Built from UDashboardGroup storage="local" › UDashboardSidebar collapsible :resizable="false" :default-size="16" :collapsed-size="4" with the #header (AppLogo), #default ( UNavigationMenu orientation="vertical" :collapsed ) and #footer (UserMenu) slots. Each page is a UDashboardPanel , with a UDashboardNavbar holding UDashboardSidebarCollapse and UBreadcrumb . On mobile, UDashboardSidebarToggle appears and the sidebar's built-in slideover takes over. Built from UDashboardGroup storage="local" › UDashboardSidebar collapsible :resizable="false" :default-size="16" :collapsed-size="4" with the #header (AppLogo), #default ( UNavigationMenu orientation="vertical" :collapsed ) and #footer (UserMenu) slots. Each page is a UDashboardPanel , with a UDashboardNavbar holding UDashboardSidebarCollapse and UBreadcrumb . On mobile, UDashboardSidebarToggle appears and the sidebar's built-in slideover takes over.
UserMenu UDropdownMenu :content="{ side: 'top', align: 'start' }" on a ghost UButton block with a UAvatar and the username. The groups are: the account label; System, Light and Dark as checkbox items; then Log out. There are no profile or password items, because the API doesn't support them. UserMenu UDropdownMenu :content="{ side: 'top', align: 'start' }" on a ghost UButton block with a UAvatar and the username. The groups are: the account label; System, Light and Dark as checkbox items; then Log out. There are no profile or password items, because the API doesn't support them. Superseded: see "UserMenu (changed)" under "Added with the Users and Profile screens", which restores the System, Light and Dark items.
Props, slots No props, because the shell reads the user from the session Pinia store. The navbar reads route.meta.title and route.meta.breadcrumb . Slots navbar-right (page actions on mobile) and default . It shows the offline banner when navigator.onLine is false. Props, slots No props, because the shell reads the user from the session Pinia store. The navbar reads route.meta.title and route.meta.breadcrumb . Slots navbar-right (page actions on mobile) and default . It shows the offline banner when navigator.onLine is false.
@@ -252,7 +259,7 @@ Responsive Below lg , the details panel becomes a right slideover, opened with i
### ImageUploader ### ImageUploader
Opens from the editor's image button in a small modal. Files are checked in the browser before anything is sent. After a successful upload the image goes in at the cursor and the modal closes. Opens from the editor's image button in a small modal. Files are checked in the browser before anything is sent. A JPEG, PNG or WEBP then goes through a crop-and-resize step before it uploads; an SVG skips straight to uploading. After a successful upload the image goes in at the cursor and the modal closes.
Drop an image here Choose file PNG, JPEG, WEBP, SVG · max 10 MB Drop an image here Choose file PNG, JPEG, WEBP, SVG · max 10 MB
@@ -262,9 +269,21 @@ Drop to upload
dragging over dragging over
north-wall.jpg 62% Crop and resize north-wall.jpg · 3.9 MB
Uploading 2.4 of 3.9 MB crop, default: whole image selected, width "1600 px"
Crop and resize north-wall.jpg · 3.9 MB
crop, ratio locked to 16:9
Crop and resize north-wall.jpg · 3.9 MB
crop, crop narrower than the chosen width
north-wall.jpg 43%
Uploading 180 of 420 KB
uploading uploading
@@ -282,6 +301,10 @@ server error
Built from UModal title="Add an image" › UFileUpload accept="image/png,image/jpeg,image/webp,image/svg+xml" :multiple="false" layout="list" + UProgress size="xs" . Uploads go through XMLHttpRequest , because fetch has no upload progress, as FormData with the field name file . The 201 location is inserted with insertImage(location, '') . Built from UModal title="Add an image" › UFileUpload accept="image/png,image/jpeg,image/webp,image/svg+xml" :multiple="false" layout="list" + UProgress size="xs" . Uploads go through XMLHttpRequest , because fetch has no upload progress, as FormData with the field name file . The 201 location is inserted with insertImage(location, '') .
Crop and resize A JPEG, PNG or WEBP opens on a 640px-wide modal (`md.crop`) between the file picker and the upload, replacing the "Add an image" title with "Crop and resize" and the filename/size as the description. The stage shows the image with the crop frame starting as the whole image: a rule-of-thirds grid (lines at 33.3 %/66.6 %), four 12×12 px corner handles, and a pixel-size label (mono, bottom-left, dark pill) that tracks the frame's current size. The frame is `tabindex="0"`, `aria-label="Crop area. Arrow keys move it, Shift and arrow keys resize it."`; dragging moves it, dragging a handle resizes it, arrow keys nudge it by 1 px and Shift+arrow keys resize it.
Aspect ratio is a `radiogroup` of five pills — Original, Free, 16:9, 4:3, 1:1 — plus Rotate and Reset actions above it. Width is a second `radiogroup` — Original, 1600 px (default), 1200 px, 800 px. A mono line below reads "Uploads as {width} × {height} px · about {size}", where the estimated size is shown in KB under 1 MB and in MB above it. When the chosen width is larger than the crop's own width, the output stays at the crop's size (never upscaled) and an info row explains why: "The crop is {crop width} px wide, so it's uploaded at that size. Enlarging it would make it blurry." The footer becomes "Choose another file" (back to the file picker, `data-act="upload-pick"` from `idle`) and "Upload image" (starts the upload with the cropped, resized file). SVGs never see this step: they upload as soon as they're chosen. The "in progress" state afterwards reports the resized file's size, e.g. "Uploading 180 of 420 KB".
Validation Before uploading, the uploader checks both the MIME type and the file extension, and that size ≤ 10 × 1024 × 1024 . The size error names the file size: "north-wall.tif is 14.2 MB. Images can be up to 10 MB." A server 400 shows the same message as a client-side rejection. Validation Before uploading, the uploader checks both the MIME type and the file extension, and that size ≤ 10 × 1024 × 1024 . The size error names the file size: "north-wall.tif is 14.2 MB. Images can be up to 10 MB." A server 400 shows the same message as a client-side rejection.
Props, emits articleId: number . Emits uploaded(location) , close . A 401 hands off to the global session flow. A 404 means the article was deleted, which the editor handles. Props, emits articleId: number . Emits uploaded(location) , close . A 401 hands off to the global session flow. A 404 means the article was deleted, which the editor handles.
@@ -354,6 +377,51 @@ Built from UError isn't used because it's built for Nuxt's error.vue . Instead t
A11y The error title is the page h1 and gets focus on render. The banner is role="status" , and it can't be dismissed while offline. The offline state blocks Save and Publish and says why in their tooltip. A11y The error title is the page h1 and gets focus on render. The banner is role="status" , and it can't be dismissed while offline. The offline state blocks Save and Publish and says why in their tooltip.
## Added with the Users and Profile screens
The Product components board was not regenerated for these. They are written from `source/RenewCMS Screens Back-office.dc.html`, `source/AppFrame.dc.html` and the Prototype. Their exact values come from AppFrame.
### UserMenu (changed)
The chip at the foot of the sidebar no longer logs out on click. It opens the account menu, which lists Profile, the theme choice and Log out.
- **Chip:** 40 px high, an initials avatar (26 px, sand `#d4c5b0` with ink text), the name, and a chevrons-up-down icon. `aria-haspopup="menu"`, `aria-expanded`, title "Account". While the menu is open, or while `/profile` is the current page, it takes `--rc-sand` with `#111111` text.
- **Name:** the display name when there is one, otherwise the username. Initials come from the first letters of the first two words of the display name, uppercased. Without a display name they come from the username.
- **Desktop menu:** a 224 px popover anchored above the chip on its left edge, with `--rc-shadow-pop`. Header: the name in semibold, the email below it in muted 12 px, a bottom border. Items are 32 px: Profile (circle-user), a separator, System, Light and Dark (14 px text, a check icon at the right edge on the current choice), a separator, Log out (log-out). The current page's item is highlighted with `--ui-bg-elevated`. The theme items are radio-style: choosing one applies at once and keeps the menu open. Nuxt UI: `type: 'checkbox'` items bound to `useColorMode().preference`.
- **Mobile:** the account row in the navigation drawer opens a bottom sheet over an `--rc-overlay` scrim, with a grab handle. Header: 36 px avatar, name in 15 px semibold, email in muted text. Items are 48 px at 15 px text; the theme items keep the same order and separators.
- **Keyboard:** Escape or a click outside closes it. Arrow keys move between items.
- The board now draws the theme items, so the chip, menu and sheet need no visual exception. The board highlights Profile even on Home; the app highlights it only on `/profile`.
### DashboardShell (changed)
The navigation gains **Users** (users icon) between Articles and Integration, in the sidebar and in the mobile drawer. Breadcrumbs for the new pages are "Users" and "Profile". It later gains **Settings** (settings icon) after Integration, with the breadcrumb "Settings".
### UsersTable, UserCardList
Superseded by "UsersTable, UserCardList (changed)" below.
Skeleton rows appear after 150 ms of loading.
### InviteStatusBadge
A 22 px outline-less badge with a 12 px icon and the word, so status is never shown by color alone.
| Status | Icon | Fill and text |
|---|---|---|
| Accepted | circle-check | `--rc-success-soft`, `--ui-success` |
| Pending | mail | `--rc-warning-soft`, `--ui-warning` |
| Expired | clock-alert | transparent, `--ui-text-muted`, border `--ui-border-accented` |
### InviteUserModal
A UModal with one field, following the NewArticleModal pattern: title "Invite a user", the text "We'll email them a link to choose a username and password. The link expires after 3 days.", an Email field (placeholder "name@example.com", focused on open), Cancel and "Send invite". While sending, the field is disabled, the button reads "Sending…" and the dialog can't be dismissed. A field error shows under the input, a request failure shows an alert above the buttons, and the address always stays in the field. On success it closes and emits the new invite.
### ProfileCard
A bordered card with 20 px padding (16 px on mobile), a semibold 14 px title, a muted description, and its content. An optional footer strip sits below a top border on `--ui-bg-muted`, with the status text on the left and the action on the right. The Display name card uses the footer; Account and Password do not.
The Display name field uses CharacterCounter with a maximum of 60, counted in Unicode characters, in the mono style on the right of the help row. Read-only fields (username, email, password) are disabled inputs on `--ui-bg-elevated` with a lock icon at the right.
## Themed primitives ## Themed primitives
Extracted from `source/RenewCMS Components Primitives.dc.html`. Extracted from `source/RenewCMS Components Primitives.dc.html`.
@@ -667,3 +735,67 @@ Three choices: System (the default), Light and Dark. The toggle at the top of th
Nuxt UI In the user menu: a UDropdownMenu group of three type: 'checkbox' items bound to useColorMode().preference . On auth screens: UColorModeSelect in the footer. Nuxt UI's UColorModeButton isn't used because it only toggles between light and dark and hides the system option. colorMode: true in the plugin handles storage and applying the .dark class before first paint. Nuxt UI In the user menu: a UDropdownMenu group of three type: 'checkbox' items bound to useColorMode().preference . On auth screens: UColorModeSelect in the footer. Nuxt UI's UColorModeButton isn't used because it only toggles between light and dark and hides the system option. colorMode: true in the plugin handles storage and applying the .dark class before first paint.
ARIA Menu items use menuitemcheckbox , with aria-checked on the current choice. The segmented variant is a radiogroup named "Theme". ARIA Menu items use menuitemcheckbox , with aria-checked on the current choice. The segmented variant is a radiogroup named "Theme".
## Added with roles, invite actions and Settings
Written from `source/RenewCMS Screens Back-office.dc.html` and `source/AppFrame.dc.html`. The Product components board was not regenerated for these.
### UsersTable, UserCardList (changed)
Columns Email, Display name, Role, Invite status, Created (sorted descending, with an arrow-down icon on the header) and an unlabeled actions column. Grid `minmax(0,1.3fr) minmax(0,1fr) 84px 120px 110px 150px`, 12 px gap, 36 px header on `--ui-bg-elevated`, 48 px rows with a top border. Below md the same rows become cards with a 68 px minimum height: the email line, the display name below it when set, then role badge, status badge and "Created {date}" on one line, then the row action as a 44 px button.
The email cell is medium weight and highlighted, with a mono "you" tag on the current user's row. The display name is highlighted, or a muted `—` when empty. The row of a just-sent or just-renewed invite has `--ui-bg-elevated`. Skeleton rows have one bar per column. The username is not shown.
### RoleBadge
A 20 px badge in IBM Plex Mono 11 px medium, 7 px side padding, no icon.
| Role | Fill | Text | Border |
|---|---|---|---|
| owner | `--ui-primary` | `--ui-bg` | `--ui-primary` |
| admin | transparent | `--ui-text-toned` | `--ui-border-accented` |
### Row action button (Users)
A 28 px outline button on desktop (12 px medium text, 13 px icon, 9 px side padding, `--ui-border-accented` border, `--ui-bg` fill, no wrapping), 44 px on mobile (14 px side padding, 14 px icon). Cancel invite: user-x, text `--ui-error`. Renew invite: refresh-cw, text `--ui-text-highlighted`. While busy: the label becomes "Renewing…", the icon loader-circle, opacity 50 %, disabled. Nuxt UI: `UButton variant="outline" size="xs"` with the classes above.
Cancel goes through `ConfirmDialog` with `tone: 'danger'`: title "Cancel this invite?", the description names the address, the cancel button reads "Keep invite" and the confirm button "Cancel invite", pending label "Cancelling…", and a failure shows a notice inside the dialog.
### SettingsPage
A page header (title "Settings", subtitle "Workspace information."), then one card holding a "Version" row. See [screens/settings.md](screens/settings.md).
## Added with Media
Exact values live in `source/MediaFrame.dc.html`. Copy and states are in [media](screens/media.md) and [media-picker](screens/media-picker.md).
| Component | Nuxt UI base | Props | Emits | Used in |
|---|---|---|---|---|
| MediaToolbar | UTabs, UInput, USelectMenu, UButtonGroup | tab, q, sort, view, counts | update:tab, update:q, update:sort, update:view | Media |
| MediaGrid | custom (buttons in a grid) | items, selected: Set, loading | open(id), toggle(id) | Media |
| MediaTable, MediaCardList | UTable, custom list | same as MediaGrid | same as MediaGrid | Media (md and up, below md) |
| MediaBulkBar | custom, UButton | count | delete, clear | Media |
| MediaDetailPanel | USlideover | id | close, rename, delete, copy-url, review-duplicates | Media |
| MediaUploadPanel | UProgress, UButton | rows | use-existing(row), upload-anyway(row), retry(row), cancel, dismiss | Media |
| DuplicateGroups | custom cards | groups | merge(group, keepId) | Media |
| MediaThumb | custom | item, size | none | Media, picker |
| MediaBadge | UBadge | kind: 'unused'\|'duplicate'\|'used'\|'online'\|'draft', label | none | Media, picker |
| RenameDialog, MergeDialog, DeleteMediaDialog | ConfirmDialog, UForm | item(s) | done | Media |
| MediaPicker | UTabs inside ImageUploader | articleId | picked(item, alt) | Editor |
ImageUploader (changed): it gains the Upload and Library tabs and the "Already in your library" card. The remove-image confirm becomes neutral and only detaches the image from the article.
## Added with Updates
Exact values live in `source/AppFrame.dc.html` (the Settings and Home states). Copy and states are in [settings](screens/settings.md) and [home](screens/home.md).
| Component | Nuxt UI base | Props | Emits | Used in |
|---|---|---|---|---|
| UpdatesCard | custom card, UProgress, UButton, UCollapsible | status: UpdateStatus, role | check, update, restart, copy-command | Settings |
| UpdateStatusBlock | custom (polite live region) | tone, icon, title, text, meta | none | UpdatesCard |
| UpdateProgress | UProgress | label, text, value or indeterminate | none | UpdatesCard |
| ReleaseNotes | UCollapsible | version, date, items | none | UpdatesCard |
| ServerCommand | UButton, code block | line | copy | UpdatesCard (Not prepared) |
| RestartOverlay | custom full-page `role="status"` | title, text, startedAt, slow | reload | App shell |
| UpdateBanner | UAlert | state: 'available'\|'ready' | go-to-settings, dismiss | Home (owner) |
| UpdatePill | UBadge | none | none | DashboardShell Settings item (dot on mobile) |
+4 -2
View File
@@ -5,10 +5,12 @@ Go `html/template` files, ready to replace `internal/infrastructure/mailer/templ
- `source/emails/verification.html` uses `{{.Host}}` and `{{.VerificationCode}}`, linking to `{{.Host}}/register/validate?c={{.VerificationCode}}`. - `source/emails/verification.html` uses `{{.Host}}` and `{{.VerificationCode}}`, linking to `{{.Host}}/register/validate?c={{.VerificationCode}}`.
- `source/emails/password-reset.html` uses `{{.Host}}`, `{{.VerificationCode}}` and `{{.Email}}`, linking to `{{.Host}}/register/reset/validate?c={{.VerificationCode}}&email={{.Email}}`. - `source/emails/password-reset.html` uses `{{.Host}}`, `{{.VerificationCode}}` and `{{.Email}}`, linking to `{{.Host}}/register/reset/validate?c={{.VerificationCode}}&email={{.Email}}`.
- `source/emails/invitation.html` uses `{{.Host}}`, `{{.VerificationCode}}`, `{{.Email}}` and `{{.InvitedBy}}`, linking to `{{.Host}}/invite/accept?c={{.VerificationCode}}`. `{{.Email}}` is the invited address, shown in the body only. `{{.InvitedBy}}` is the inviter's display name, or their username when they have none. The subject is "{{.InvitedBy}} invited you to RenewCMS". The invite expires in 3 days and works once.
Previews: `source/RenewCMS Emails.dc.html`. Previews: `source/RenewCMS Emails.dc.html`.
## Transactional emails ## Transactional emails
Two Go html/template files: emails/verification.html and emails/password-reset.html . They use a table layout with inline CSS and a 600 px maximum width. The button is bulletproof: a colored table cell plus a padded link, so it survives Outlook. Each has a plain-URL fallback, a hidden preheader, and prefers-color-scheme overrides for clients that support them. The mark is live text in a black cell rather than an image, so it shows even when images are blocked. Previews below use example values. Three Go html/template files: emails/verification.html, emails/password-reset.html and emails/invitation.html . They use a table layout with inline CSS and a 600 px maximum width. The button is bulletproof: a colored table cell plus a padded link, so it survives Outlook. Each has a plain-URL fallback, a hidden preheader, and prefers-color-scheme overrides for clients that support them. The mark is live text in a black cell rather than an image, so it shows even when images are blocked. Previews below use example values.
Suggested subjects are "Verify your RenewCMS account" and "Reset your RenewCMS password". html/template escapes the .Email value for the query string in the reset link (the @ becomes %40), and the confirm route reads it back decoded. Suggested subjects are "Verify your RenewCMS account", "Reset your RenewCMS password" and "<InvitedBy> invited you to RenewCMS", where .InvitedBy is the inviter's display name or username. html/template escapes the .Email value for the query string in the reset link (the @ becomes %40), and the confirm route reads it back decoded.
+7 -2
View File
@@ -11,11 +11,16 @@ A global `router.beforeEach` guard reads `meta.auth`. On the first navigation it
| `/register/validate` | AuthShell | public | VerifyPage | POST /v1/auth/verify (+ POST /login inline on 401) | | `/register/validate` | AuthShell | public | VerifyPage | POST /v1/auth/verify (+ POST /login inline on 401) |
| `/register/reset/request` | AuthShell | public | ResetRequestPage | POST /v1/auth/password-reset | | `/register/reset/request` | AuthShell | public | ResetRequestPage | POST /v1/auth/password-reset |
| `/register/reset/validate` | AuthShell | public | ResetConfirmPage | POST /v1/auth/password-reset/confirm | | `/register/reset/validate` | AuthShell | public | ResetConfirmPage | POST /v1/auth/password-reset/confirm |
| `/home` | DashboardShell | verified | HomePage | GET /v1/article/ | | `/home` | DashboardShell | verified | HomePage | GET /v1/article/ · GET /v1/system/update (owner, for the banner) |
| `/article` | DashboardShell | verified | ArticlesPage | GET /v1/article/ · PATCH /{id}/publish\|unpublish · DELETE /{id} | | `/article` | DashboardShell | verified | ArticlesPage | GET /v1/article/ · PATCH /{id}/publish\|unpublish · DELETE /{id} |
| `/article/new` | DashboardShell | verified | ArticlesPage + NewArticleModal | POST /v1/article/ | | `/article/new` | DashboardShell | verified | ArticlesPage + NewArticleModal | POST /v1/article/ |
| `/article/:id/edit` | DashboardShell | verified | EditorPage | GET /{id} · PATCH /{id} · PATCH /{id}/publish\|unpublish · POST /{id}/image · DELETE /{id} | | `/article/:id/edit` | DashboardShell | verified | EditorPage | GET /{id} · PATCH /{id} · PATCH /{id}/publish\|unpublish · GET /v1/media/ · POST /v1/media/ · DELETE /{id} |
| `/media` | DashboardShell | verified | MediaPage | GET /v1/media/ · POST /v1/media/ · PATCH /v1/media/{id} · DELETE /v1/media/{id} · POST /v1/media/merge · GET /v1/media/{id}/usage |
| `/integration` | DashboardShell | verified | IntegrationPage | none | | `/integration` | DashboardShell | verified | IntegrationPage | none |
| `/users` | DashboardShell | verified | UsersPage + InviteUserModal | GET /v1/user/ · POST /v1/user/invite · DELETE /v1/user/invite/:id · POST /v1/user/invite/:id/renew |
| `/settings` | DashboardShell | verified | SettingsPage | GET /v1/settings · GET /v1/system/update · POST /v1/system/update/check · POST /v1/system/update/download · POST /v1/system/update/restart |
| `/profile` | DashboardShell | verified | ProfilePage | GET /v1/auth/me · PATCH /v1/user/me · POST /v1/auth/password-reset |
| `/invite/accept` | AuthShell | public | AcceptInvitePage | GET /v1/auth/invite?c=* · POST /v1/auth/invite/accept* |
| `/:pathMatch(.*)*` | either | any | NotFoundPage | none | | `/:pathMatch(.*)*` | either | any | NotFoundPage | none |
Auth values: `public` needs no session, `session` needs a logged-in account (verified or not), `verified` needs a verified account, `any` applies to redirects and the catch-all. Auth values: `public` needs no session, `session` needs a logged-in account (verified or not), `verified` needs a verified account, `any` applies to redirects and the catch-all.
+114
View File
@@ -0,0 +1,114 @@
# Accept invite
- **Route:** `/invite/accept?c=CODE`
- **API:** GET /v1/auth/invite?c=CODE (pending) · POST /v1/auth/invite/accept (pending)
- **Visual reference:** `source/RenewCMS Screens Auth.dc.html`, group "Accept invite" (open it in a browser; each state is drawn at desktop and mobile, with a light/dark toggle).
Opened from the invitation email. The link carries only the code, so the invited email is looked up on load and shown read-only. Username and password follow the Register rules, including PasswordStrengthHint, with no confirm field. On success the person is logged in and sent to /home with a toast. The account is already verified, because the invite went to their email, so it skips the pending and verify screens.
Neither endpoint exists yet:
- `GET /v1/auth/invite?c=CODE` returns `{ email }`, or 404 or 410.
- `POST /v1/auth/invite/accept` takes `{ code, username, password }`. It returns 200 with the session cookie, 409 for a taken username, or 404 or 410 as above.
Registration stays closed to everyone else: [register.md](register.md) "Registration closed" still applies to `/register`. The board does not draw the case of a logged-in person opening the link; it is not specified.
## States
### Checking the link
**Trigger:** On load, while the invite is looked up.
- Full-card spinner: "Checking your invite…"
### Default
**Trigger:** The code is valid and unused.
- Heading: **Accept your invite**
- Description: "Choose a username and password to finish setting up your account."
- Field `Email`: placeholder "you@example.com"; value "lea.martin@renew.example"; read-only; help "From your invitation."
- Field `Username`: placeholder "e.g. lea"; counter "0 / 20"; help "Letters and numbers, 3 to 20 characters. You'll use it to log in."
- Field `Password`: password with show/hide; checklist "At least 8 characters" (unmet)
- Submit button: "Accept invite"
- Footer: Already have an account? [Log in]
### Validation errors
**Trigger:** Checked on blur and on submit, using the same rules as Register. Nothing is sent.
- Heading: **Accept your invite**
- Description: "Choose a username and password to finish setting up your account."
- Field `Email`: placeholder "you@example.com"; value "lea.martin@renew.example"; read-only; help "From your invitation."
- Field `Username`: placeholder "e.g. lea"; value "ma"; counter "2 / 20" in error; **error "Use 3 to 20 characters."**
- Field `Password`: value "lime"; password with show/hide; checklist "At least 8 characters" (err)
- Submit button: "Accept invite"
- Footer: Already have an account? [Log in]
### Filled, valid
**Trigger:** Every rule is met and the checklist item turns green.
- Heading: **Accept your invite**
- Description: "Choose a username and password to finish setting up your account."
- Field `Email`: placeholder "you@example.com"; value "lea.martin@renew.example"; read-only; help "From your invitation."
- Field `Username`: placeholder "e.g. lea"; value "lea"; counter "3 / 20"; help "Letters and numbers, 3 to 20 characters. You'll use it to log in."
- Field `Password`: value "limewash2026"; password with show/hide; password shown; checklist "At least 8 characters" (met)
- Submit button: "Accept invite"
- Footer: Already have an account? [Log in]
### Submitting
**Trigger:** Fields and button are disabled.
- Heading: **Accept your invite**
- Description: "Choose a username and password to finish setting up your account."
- Field `Email`: placeholder "you@example.com"; value "lea.martin@renew.example"; read-only; help "From your invitation."
- Field `Username`: placeholder "e.g. lea"; value "lea"; counter "3 / 20"; help "Letters and numbers, 3 to 20 characters. You'll use it to log in."
- Field `Password`: value "limewash2026"; password with show/hide; checklist "At least 8 characters" (met)
- Submit button: "Creating account…", loading
- Footer: Already have an account? [Log in]
### Username taken (409)
**Trigger:** Another user has that username. The value is kept and the field gets focus.
- Heading: **Accept your invite**
- Description: "Choose a username and password to finish setting up your account."
- Field `Email`: placeholder "you@example.com"; value "lea.martin@renew.example"; read-only; help "From your invitation."
- Field `Username`: placeholder "e.g. lea"; value "marta"; counter "5 / 20"; focused; **error "That username is taken. Try another."**
- Field `Password`: value "limewash2026"; password with show/hide; checklist "At least 8 characters" (met)
- Submit button: "Accept invite"
- Footer: Already have an account? [Log in]
### Invalid or used link (404)
**Trigger:** The code is wrong, was already accepted, or is missing from the URL. No form is shown.
- ResultPanel (error, link-2-off): **This invite link doesn't work**; text "It may be incomplete, or it may already have been used. If you already set up your account, log in instead."; note "Open the link from your email again, or copy the full address into your browser."; actions "Go to log in" (primary)
### Expired link (410)
**Trigger:** The invite is older than 3 days.
- ResultPanel (error, clock): **This invite has expired**; text "Invites work once, for 3 days. Ask the person who invited you to send a new one."; actions "Go to log in" (secondary)
### Server error
**Trigger:** A 500 or no response. The values are kept.
- Alert (error, circle-x): **Couldn't create the account** "Something went wrong on the server. Try again in a moment."
- Heading: **Accept your invite**
- Description: "Choose a username and password to finish setting up your account."
- Field `Email`: placeholder "you@example.com"; value "lea.martin@renew.example"; read-only; help "From your invitation."
- Field `Username`: placeholder "e.g. lea"; value "lea"; counter "3 / 20"; help "Letters and numbers, 3 to 20 characters. You'll use it to log in."
- Field `Password`: value "limewash2026"; password with show/hide; checklist "At least 8 characters" (met)
- Submit button: "Accept invite"
- Footer: Already have an account? [Log in]
### Success
**Trigger:** 200 sets the session cookie → /home after 800 ms, with a toast. No verification step.
- ResultPanel (success, circle-check): **Your account is ready**; text "Taking you to your dashboard…"
- Toast (circle-check): **Welcome to RenewCMS** "You're logged in as lea."
+4 -4
View File
@@ -88,7 +88,7 @@ Rows update when the server responds, not optimistically. Search, tab and sort a
- Breadcrumbs: Articles (mobile title "Articles") - Breadcrumbs: Articles (mobile title "Articles")
- Modal: **Delete this article?** - Modal: **Delete this article?**
- text ""Winter checklist for timber windows" and its 3 images will be deleted. This can't be undone." - text ""Winter checklist for timber windows" will be deleted. Its images stay in your library. This can't be undone."
- cancel "Cancel" - cancel "Cancel"
- confirm "Delete article" (danger) - confirm "Delete article" (danger)
@@ -98,7 +98,7 @@ Rows update when the server responds, not optimistically. Search, tab and sort a
- Breadcrumbs: Articles (mobile title "Articles") - Breadcrumbs: Articles (mobile title "Articles")
- Modal: **Delete this article?** - Modal: **Delete this article?**
- text ""Winter checklist for timber windows" and its 3 images will be deleted. This can't be undone." - text ""Winter checklist for timber windows" will be deleted. Its images stay in your library. This can't be undone."
- cancel "Cancel" - cancel "Cancel"
- confirm "Deleting…" (danger), loading, not dismissible - confirm "Deleting…" (danger), loading, not dismissible
@@ -108,7 +108,7 @@ Rows update when the server responds, not optimistically. Search, tab and sort a
- Breadcrumbs: Articles (mobile title "Articles") - Breadcrumbs: Articles (mobile title "Articles")
- Modal: **Delete this article?** - Modal: **Delete this article?**
- text ""Winter checklist for timber windows" and its 3 images will be deleted. This can't be undone." - text ""Winter checklist for timber windows" will be deleted. Its images stay in your library. This can't be undone."
- Alert: "Couldn't delete the article, so it's still there. Try again in a moment." - Alert: "Couldn't delete the article, so it's still there. Try again in a moment."
- cancel "Cancel" - cancel "Cancel"
- confirm "Delete article" (danger) - confirm "Delete article" (danger)
@@ -118,5 +118,5 @@ Rows update when the server responds, not optimistically. Search, tab and sort a
**Trigger:** 204: the row is removed and focus moves to the next row. This is also where a delete from the editor ends up. **Trigger:** 204: the row is removed and focus moves to the next row. This is also where a delete from the editor ends up.
- Breadcrumbs: Articles (mobile title "Articles") - Breadcrumbs: Articles (mobile title "Articles")
- Toast (success, circle-check): **Article deleted** ""Winter checklist for timber windows" and its images are gone." - Toast (success, circle-check): **Article deleted** ""Winter checklist for timber windows" is gone."
- Tab counts (All, Online, Drafts): 5, 4, 1 - Tab counts (All, Online, Drafts): 5, 4, 1
+40 -3
View File
@@ -83,13 +83,50 @@ On mobile, Save and Publish sit in a sticky bottom bar and the details panel ope
- Editor: status "draft", save "dirty" - Editor: status "draft", save "dirty"
- Mobile: leading arrow-left button, trailing ellipsis - Mobile: leading arrow-left button, trailing ellipsis
### Upload: crop and resize
**Trigger:** A JPEG, PNG or WEBP passed the checks, and nothing is sent yet. The crop starts as the whole image and the width defaults to 1600 px. SVGs skip this step.
- Breadcrumbs: Articles › How we price a bathroom renovation (mobile title "Edit article")
- Modal: **Crop and resize** "north-wall.jpg · 3.9 MB"
- crop: ratio "Original", width "1600 px"
- cancel "Choose another file"
- confirm "Upload image"
- Editor: status "draft", save "dirty"
- Mobile: leading arrow-left button, trailing ellipsis
### Upload: crop to a ratio
**Trigger:** 16:9 chosen. The frame keeps the ratio while it's dragged or resized. Arrow keys move it; Shift and arrow keys resize it.
- Breadcrumbs: Articles › How we price a bathroom renovation (mobile title "Edit article")
- Modal: **Crop and resize** "north-wall.jpg · 3.9 MB"
- crop: ratio "16:9", width "1600 px"
- cancel "Choose another file"
- confirm "Upload image"
- Editor: status "draft", save "dirty"
- Mobile: leading arrow-left button, trailing ellipsis
### Upload: crop narrower than the width
**Trigger:** The crop is smaller than the chosen width, so it keeps its own size.
- Breadcrumbs: Articles › How we price a bathroom renovation (mobile title "Edit article")
- Modal: **Crop and resize** "north-wall.jpg · 3.9 MB"
- crop: ratio "1:1", width "1600 px"
- note: "The crop is 640 px wide, so it's uploaded at that size. Enlarging it would make it blurry."
- cancel "Choose another file"
- confirm "Upload image"
- Editor: status "draft", save "dirty"
- Mobile: leading arrow-left button, trailing ellipsis
### Upload: in progress ### Upload: in progress
**Trigger:** A valid file is uploading. Closing the dialog cancels the upload. **Trigger:** Upload image was pressed. The cropped, resized file is uploading. Closing the dialog cancels the upload.
- Breadcrumbs: Articles › How we price a bathroom renovation (mobile title "Edit article") - Breadcrumbs: Articles › How we price a bathroom renovation (mobile title "Edit article")
- Modal: **Add an image** - Modal: **Add an image**
- upload state: state "uploading" - upload state: state "uploading" ("Uploading 180 of 420 KB")
- cancel "Cancel upload" - cancel "Cancel upload"
- Editor: status "draft", save "dirty" - Editor: status "draft", save "dirty"
- Mobile: leading arrow-left button, trailing ellipsis - Mobile: leading arrow-left button, trailing ellipsis
@@ -146,7 +183,7 @@ On mobile, Save and Publish sit in a sticky bottom bar and the details panel ope
- Breadcrumbs: Articles › How we price a bathroom renovation (mobile title "Edit article") - Breadcrumbs: Articles › How we price a bathroom renovation (mobile title "Edit article")
- Modal: **Delete this article?** - Modal: **Delete this article?**
- text ""How we price a bathroom renovation" and its 3 images will be deleted. This can't be undone." - text ""How we price a bathroom renovation" will be deleted. Its images stay in your library. This can't be undone."
- cancel "Cancel" - cancel "Cancel"
- confirm "Delete article" (danger) - confirm "Delete article" (danger)
- Editor: status "draft", save "saved" - Editor: status "draft", save "saved"
+15 -1
View File
@@ -4,7 +4,7 @@
- **API:** GET /v1/article/ - **API:** GET /v1/article/
- **Visual reference:** `source/RenewCMS Screens Back-office.dc.html`, group "Home" (open it in a browser; each state is drawn at desktop and mobile, with a light/dark toggle). - **Visual reference:** `source/RenewCMS Screens Back-office.dc.html`, group "Home" (open it in a browser; each state is drawn at desktop and mobile, with a light/dark toggle).
The counts come from the list, so there's no separate endpoint. The five most recently updated articles link to the editor. The greeting reads "Good morning, {name}", where the name is the display name when the user has saved one and the username otherwise. The counts come from the list, so there's no separate endpoint. The five most recently updated articles link to the editor.
## States ## States
@@ -40,3 +40,17 @@ The counts come from the list, so there's no separate endpoint. The five most re
- Breadcrumbs: Home (mobile title "Home") - Breadcrumbs: Home (mobile title "Home")
- Subtitle: "Here's where things stand on your site." - Subtitle: "Here's where things stand on your site."
- Error state for the list request - Error state for the list request
### Update available (owner)
**Trigger:** The owner only. A quiet banner above the content, and an "Update" pill on the Settings sidebar item (a dot on the menu icon on mobile, read as "Update available"). Dismissing hides the banner until the next version; the pill stays. Admins see neither.
- Breadcrumbs: Home (mobile title "Home")
- Subtitle: "Here's where things stand on your site."
- Banner: `role="region"` labelled "Update available", info tone, `circle-arrow-up` icon, title "Version 2.3.0 is available", text "Update it from Settings. It takes about 2 minutes and the site stays online.", button "Go to Settings", and a dismiss button
### Update ready to install (owner)
**Trigger:** The download is checked. The same banner changes its copy, and a dismiss comes back on the next visit because the update is waiting.
- Banner: success tone, `circle-check` icon, title "Version 2.3.0 is ready to install", text "Restart from Settings to finish. The site is unavailable for about 10 seconds.", button "Go to Settings"
+56
View File
@@ -0,0 +1,56 @@
# Media picker (editor)
- **Route:** `/article/:id/edit` (inside the editor's existing "Add an image" dialog)
- **API:** GET /v1/media/?q=&limit=&cursor= · POST /v1/media/ (same as the Media page)
- **Visual reference:** `source/RenewCMS Screens Back-office.dc.html`, group "Media picker", drawn by `source/MediaFrame.dc.html`.
The existing "Add an image" dialog gains two tabs, Upload and Library. The Upload tab is the current flow unchanged, so it still offers crop and resize, and a new image lands in the library and is inserted as before. The Library tab opens on the Library tab when the library has images and on Upload when it is empty. Images load 24 at a time with "Load more". Newest first, and images already in this article carry "In this article". Alt text is set here and lives only in the article. The dialog is 640 px wide on desktop and a bottom sheet on mobile.
This supersedes the upload-only "Add an image" dialog described in [editor](editor.md), and the "Remove this image?" confirmation from `features/editor_image_removal.feature`.
## Dialog
Title "Add an image", `x` to close, 640 px wide on desktop (bottom sheet on mobile). Two tabs under the title: **Upload** (`upload` icon) and **Library** (`images` icon). The dialog opens on Library when the library has images and on Upload when it is empty; dropping a file onto the editor opens Upload with the file provided, as before. Footer: "Cancel", and on Library a primary "Insert image", disabled until an image is selected.
**Upload tab.** The current flow unchanged (drop zone "Drop an image here, or choose a file", help "PNG, JPEG, WEBP, SVG · max 10 MB", crop and resize, rejected, uploading and failed states). Two changes: the new image lands in the library and is inserted as before, and a chosen file whose content matches an existing image sends nothing and shows an info-bordered card: thumbnail, "Already in your library", `north-wall.jpg matches an image uploaded on 12 Sep 2026 by Marta Alves.`, with "Use existing" (primary) and "Upload anyway". "Use existing" goes to the alt text step for the existing image; "Upload anyway" continues to crop and upload.
**Library tab.** Search field ("Search by filename"), the line "Newest first · 48 images", a grid of square tiles (4 columns on desktop, 3 on mobile; scrolls inside the dialog) with the filename under each, and "Load more" below (24 images per page). Tiles are buttons labelled with filename, size and use; Enter or Space selects (single selection). A tile of an image already in this article carries a sand "In this article" tag. The selected tile gets a primary outline and a check. Once one is selected, the grid shrinks and a panel appears below it: 56 px thumbnail, filename, `dimensions · size`, and a field "Alt text (optional)" with placeholder "e.g. North wall of the kitchen before plastering" and 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." Alt text lives only in the article, never on the image.
| Library state | Copy |
|---|---|
| Empty | `images` icon, "Your library is empty" / "Images you upload appear here, ready to use in any article." / "Upload an image" (switches to Upload) |
| No results | `search` icon, `No images match "wall"` / "Check the spelling, or search for a shorter part of the filename." / "Clear search" |
| Failed | error alert "Couldn't load your library" / "Check your connection and try again." / "Try again" |
| Loading more | button reads "Loading…" with a loader, skeleton tiles at the end |
Insert (either tab): the image goes in at the cursor with the chosen alt text (empty alt means decorative), the draft becomes "Unsaved changes", and a toast appears: `circle-check`, "Image added" / "Save to keep it in the article." The dialog then closes.
## Removing an image from the article
The "Remove image" button on a selected image in the editor (and Backspace or Delete on it) now opens a neutral (not red) confirm, because nothing is deleted:
- Title: "Remove this image from the article?"
- Description: "It's removed from this article only. The file stays in your library and in any other article that uses it."
- Body: thumbnail, filename, "Stays in the library · 3.9 MB"
- Buttons: "Cancel" / "Remove image"
- Done: the image leaves the body, the draft becomes "Unsaved changes", and a toast appears: `circle-check`, "Image removed" / "It's still in your library."
No API call is made. Removing is a body edit only.
## States
| State | Trigger and behaviour |
|---|---|
| Upload tab | The image button in the toolbar. Identical to the current "Add an image" content; only the tabs are new. Rejected, uploading and failed states are unchanged. |
| Upload tab: already in your library | A chosen file has the same content as an existing image. Nothing is sent. "Use existing" inserts the existing image (the alt text step follows); "Upload anyway" continues to crop and upload as usual. |
| Library: loading | The Library tab was opened, or a search changed. Skeleton tiles after 150 ms. |
| Library: nothing selected | Newest first. Tiles are buttons labelled with filename, size and use, and Enter or Space selects. Images already in this article carry "In this article". "Insert image" is disabled. |
| Library: selected | One image selected (single selection). Below the grid: thumbnail, filename, dimensions and size, and an optional alt text field. "Insert image" turns on. |
| Library: alt text entered | Alt text is optional. Empty alt text is inserted as a decorative image. It is not saved on the image. |
| Library: loading more | "Load more" pressed. The button shows progress and new skeleton tiles appear at the end. Focus stays on the button until the new tiles arrive, then moves to the first new tile. |
| Library: empty | Zero images. "Upload an image" switches to the Upload tab. |
| Library: no results | Search matched nothing. "Clear search" resets it. |
| Library: failed to load | A 500 or network failure. The error shows in the dialog and Try again repeats the request. A 429 uses the same countdown alert as the Media page, and a 401 is handled globally. |
| Inserted | Insert image from either tab. The image goes in at the cursor with the chosen alt text, and the article now has unsaved changes. |
| Remove image: confirm | Remove image on an image in the article. It now only removes it from this article, and the copy says the file stays in the library. The confirm button is neutral, not red, because nothing is deleted. Title: "Remove this image from the article?" |
| Removed | Confirmed. The image leaves the article body, which now has unsaved changes. |
+159
View File
@@ -0,0 +1,159 @@
# Media
- **Route:** `/media` (verified users)
- **API:** GET /v1/media/ · POST /v1/media/ · PATCH /v1/media/{id} · DELETE /v1/media/{id} · POST /v1/media/merge · GET /v1/media/{id}/usage
- **Visual reference:** `source/RenewCMS Screens Back-office.dc.html`, group "Media", drawn by `source/MediaFrame.dc.html` (open it in a browser; each state is drawn at desktop and mobile, with a light/dark toggle).
The library of every uploaded image. It replaces "images belong to one article": an image belongs to the library and can be used in any number of articles. Deleting an article never deletes images. The sidebar gains **Media** (`images` icon) between Articles and Users, breadcrumb "Media".
New route for verified users, in the sidebar between Articles and Users with the images icon. Images belong to the library, not to an article: one image can be used in many articles, and deleting an article never deletes images. Uploads from this page are not cropped or resized, and the file is stored as chosen. "Used in" is read from article bodies each time the list loads. Duplicates are images with identical content, whatever their filenames. Alt text is not stored on the image; it is set when inserting into an article. Search, filter, sort and view are stored in the query string. Keyboard: grid items are buttons in one tab stop each; Enter opens the detail panel, Space toggles selection, and Escape closes the panel or clears the selection. Selection changes are announced ("north-wall.jpg selected, 1 selected").
## Layout
Header: title "Media", subtitle "Every image you've uploaded, ready to use in any article.", primary "Upload" button (`upload` icon) on the right. On mobile the button is a full-width 48 px button pinned to the bottom (it turns into "Try again in 0:42" while rate limited, and is replaced by the bulk bar while items are selected).
Toolbar: tabs **All**, **Unused** and **Duplicates** (count badge of duplicate groups, only while groups exist), then search ("Search by filename"), sort and the grid/list toggle. Sort options: Newest (default), Oldest, Name, Largest. Below md the toolbar stacks: search, tabs, then sort and toggle.
Grid (default): 5 columns on desktop, 2 on mobile, 16 px gap (10 px on mobile). Each card is one button: 4:3 thumbnail (checkerboard behind transparent PNG and SVG), filename (medium, ellipsis), `size · dimensions` (SVG dimensions read "Vector"), then badges. The accessible name reads "north-wall.jpg, 3.9 MB, used in 2 articles" or "…, unused". A "Select all" row with the image count sits above the grid.
| Badge | Look |
|---|---|
| Unused | warning-soft fill, `unlink` icon |
| Duplicate | info-soft fill, `copy` icon |
| Used in N | outline, toned text |
List view: table from md up, columns Filename (with 40 px thumbnail and Duplicate badge), Dimensions, Size, Type, Used in (underlined count, opens the detail panel), Uploaded by, Uploaded (sorted, `arrow-down`); 56 px rows, 36 px header, first column is the checkbox. Below md it is a card list with a 44 px checkbox column, a 56 px thumbnail, filename, `size · dimensions · type`, badges plus `uploader · date`, and a trailing `chevron-right`.
Selection: selected items take the sand fill (`--rc-sand`) with a primary outline. The checkbox shows on hover, on keyboard focus, on mobile, and whenever anything is selected. The bulk bar is sticky at the bottom (400 px wide on desktop, full width above the bottom edge on mobile): inverted fill, "3 selected", a danger "Delete" button (`trash-2`) and an inverted "Clear".
Detail panel: right-hand slideover 460 px wide on desktop (`x` to close), full screen on mobile with an `arrow-left`. Title is the filename. Body: 16:10 preview (4:3 on mobile), actions Copy URL (`link`), Rename (`pencil`), Delete (`trash-2`, error text), an info alert for duplicates, a metadata list (Type, Size, Dimensions, Uploaded, Uploaded by, URL in mono), then the "Used in" section.
Detail panel copy:
| Where | Copy |
|---|---|
| Duplicate alert | "Identical to 2 other images" / "floorboards-copy.jpg and IMG_2208.jpg have the same content." / action "Review duplicates" (`arrow-right`) |
| Used | "Used in 2 articles", then one row per article: title (underlined link to the editor), badge "Online" (`globe`, inverted) or "Draft" (`pencil-line`, outline), `arrow-up-right`. Footnote: "Counted from the text of your articles each time you open this page." |
| Not used | "Not used in any article" / "This image is safe to delete. No article shows it." |
## Dialogs
All dialogs use the existing ConfirmDialog look (`UModal`, `sm:max-w-md`, bottom sheet on mobile, cancel first). While a request runs the confirm button shows a `loader-circle`, both buttons are disabled and the dialog cannot be dismissed. A failure shows an error alert at the top of the dialog body and the dialog stays open.
| Dialog | Title | Description | Body | Cancel / Confirm (pending) |
|---|---|---|---|---|
| Rename | "Rename image" | "Only the filename changes. The URL stays the same, so articles that use this image keep working." | Field "Filename" with the extension fixed as a mono suffix (`.jpg`); help "Letters, numbers, dashes and underscores. The .jpg ending stays."; error "Enter a filename." on empty or only symbols | "Cancel" / "Rename" ("Renaming…") |
| Delete, unused | "Delete this image?" | ""window-frame.jpg" will be deleted from your library. No article uses it. This can't be undone." | none | "Cancel" / "Delete image" ("Deleting…"), danger |
| Delete, in use | "Delete an image that's in use?" | ""north-wall.jpg" is used in 2 articles. If you delete it, they will show a broken image. This can't be undone." | list of affected articles with Online or Draft badges | "Cancel" / "Delete image" ("Deleting…"), danger |
| Bulk delete | "Delete 3 images?" | "2 of them are used in 4 articles, which will show a broken image. The other one isn't used anywhere. This can't be undone." | one row per image: filename and "Used in N" or "Unused" | "Cancel" / "Delete 3 images" ("Deleting…"), danger |
| Merge | "Merge into floorboards.jpg?" | "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." | the kept image: thumbnail, filename, "Kept · used in 4 articles now" | "Cancel" / "Merge 2 copies" ("Merging…"), danger |
Dialog errors: rename "Couldn't rename the image. Your text is still here. Try again in a moment."; delete "Couldn't delete the image, so it's still there. Try again in a moment."; merge (500) "Couldn't merge the copies. Nothing was changed. Try again in a moment."; merge (409) "One of these images changed, so nothing was merged. The list is up to date now. Check it and try again."
## Upload panel
A panel above the images while files are in flight and until dismissed. Header: "Uploading 6 images" with "2 of 6 done" and "Cancel all" (after it settles: "Upload finished" / "5 images" and "Dismiss"; if nothing was added: "Nothing was uploaded"). Files upload two at a time, one row each: 40 px thumbnail, filename, size, then per status:
| Status | Row |
|---|---|
| Waiting | "Waiting" |
| Uploading | "Uploading 1.1 of 2.6 MB" with a 4 px progress bar and a cancel `x` |
| Added | `circle-check` "Added to your library" |
| Duplicate | "Already in your library" / `Same as "floorboards.jpg", uploaded 14 Jun 2026 by Inès Duarte.` / "Use existing" and "Upload anyway" |
| Rejected | `file-x` title, then "Images can be up to 10 MB. Use a PNG, JPEG, WEBP or SVG image." Titles: `scan.tif is 14.2 MB` (too large), `notes.pdf isn't an image` (type), `broken.png couldn't be read` with "The server couldn't read this image. Save it again as a PNG or JPEG, then try again." (400) |
| Failed | `circle-x` "Upload failed" / "The server didn't accept the file. Nothing was added to your library." / "Try again" (`rotate-cw`) |
Summary line when settled: "2 uploaded · 1 already in your library · 2 need attention". Type and size are checked in the browser before anything is sent (PNG, JPEG, WEBP, SVG; 10 MB), by MIME type and by extension, exactly as the editor's uploader does. Dropping files onto the page shows a dashed primary-bordered area "Drop images to upload" / "PNG, JPEG, WEBP, SVG · max 10 MB each".
## Duplicates view
Groups stacked with 16 px gap. Each group is a bordered card: header "Group 1" and "3 identical images · 2.4 MB each · 3600 × 2400"; one column per copy (stacked on mobile) with thumbnail, filename, "Uploaded 14 Jun 2026 by Inès Duarte", underlined "Used in 4 articles", and a "Merge into this one" button (`merge` icon). The suggested copy has the sand fill, a primary outline, a "Suggested" tag and a primary button; the others are outline. Footer: "Suggested: the most used copy, then the oldest. Choosing another copy switches articles to it." Empty: `copy` icon, "No duplicates" / "Every image in your library is different." / "Back to all images".
## Other copy
| Where | Copy |
|---|---|
| Empty library | `images` icon, "No images yet" / "Upload your first image. You can use it in any article." / primary "Upload an image"; under it "PNG, JPEG, WEBP, SVG · max 10 MB each" |
| No results | `search` icon, `No images match "wall"` / "Nothing matches in Unused. Check the spelling, or clear the filters." / "Clear filters" |
| List error | error alert "Couldn't load your images" / "Check your connection and try again." / "Try again" |
| Rate limited | info alert `timer` "Too many uploads" / "For your security, wait a moment before uploading again."; the Upload button reads "Try again in 0:42" and is disabled |
| Offline banner | `wifi-off` "You're offline. You can look through the images that are loaded, but uploading, renaming and deleting need a connection." |
Toasts (success 5 s unless noted):
| Trigger | Icon, title, description |
|---|---|
| Copy URL | `circle-check` "URL copied" / "Paste it wherever you need the image address." |
| Rename | `circle-check` "Image renamed" / `It's now "north-wall-01.jpg". The URL is the same.` |
| Delete | `circle-check` "Image deleted" / `"window-frame.jpg" is gone from your library.` |
| Bulk delete | `circle-check` "3 images deleted" / "They're gone from your library." |
| Bulk delete, partial | error, stays until retried or dismissed: `circle-x` "Couldn't delete 1 image" / "2 images were deleted. window-frame.jpg is still in your library. Try again." / "Retry" |
| Merge | `circle-check` "Copies merged" / "2 copies merged. 5 articles updated." |
| 404 | info `info` "That image no longer exists" / "It was deleted somewhere else, so we removed it from the library." |
## Status to copy
| Status | Where | Copy |
|---|---|---|
| 200 / 201 | Upload, rename, merge | Upload: row reads "Added to your library". Rename and merge: toasts above. |
| 204 | Delete, bulk delete | Toasts above. |
| 400 | Upload row | "broken.png couldn't be read" / "The server couldn't read this image. Save it again as a PNG or JPEG, then try again." In a dialog: "Something in the form isn't valid. Check the highlighted fields." |
| 401 | any | Global: /login?redirect=/media&reason=expired. No local copy. |
| 403 | any, unverified | Global: /register/pending. |
| 404 | rename, delete, merge, panel | The info toast above; the panel or dialog closes. |
| 409 | merge | Dialog alert above. |
| 413 | upload row | "scan.tif is 14.2 MB" / "Images can be up to 10 MB. Use a PNG, JPEG, WEBP or SVG image." |
| 415 | upload row | "notes.pdf isn't an image" / same description. |
| 429 | upload | Rate-limited alert above, counting down Retry-After. |
| 500 / network | list, upload row, rename, delete, merge | The copy for each place above. |
| Offline | whole page | Banner above. |
## Keyboard and accessibility
Grid items are buttons, one tab stop each. Enter opens the detail panel, Space toggles selection, arrow keys move focus across the grid, Escape closes the panel or clears the selection. Focus returns to the item when the panel closes, and moves to the next item after a delete. Selection changes are announced ("north-wall.jpg selected, 1 selected"), as are upload completion and the merge result. Search, filter, sort and view live in the query string.
## States
| State | Trigger and behaviour |
|---|---|
| Grid, many images | Default view. 12 images, newest first. Each item is a button labelled like "north-wall.jpg, 3.9 MB, used in 2 articles". Badges: "Unused" (warm), "Duplicate" (info), "Used in N" (outline). The Duplicates tab carries a count of groups only while duplicates exist. |
| Grid, few images | Three images. Cards keep their size instead of stretching. Checkerboard shows behind the SVG. |
| List view | The list icon in the toggle. A table from md up (Filename, Dimensions, Size, Type, Used in, Uploaded by, Uploaded) and a card list below md. The "Used in" count opens the article list in the detail panel. |
| Loading | The first load, a retry, or a change of search or filter. Skeleton cards appear after 150 ms. |
| Empty library, first run | Zero images. Toolbar and tabs are hidden; one call to action. Copy: "No images yet" / "Upload your first image. You can use it in any article." / "Upload an image". |
| No results | Search or filter matched nothing. "Clear filters" resets the search and goes back to All. |
| Hover, focus and keyboard | Hover (second item) darkens the border, adds the pop shadow and reveals the checkbox. Keyboard focus (third item) shows the 2 px primary ring with a 2 px offset and reveals the checkbox. Tab moves between items, Enter opens the detail panel, Space toggles selection, and arrow keys move focus across the grid. |
| Selection and bulk bar | Checkbox on any item, or Space. Selected items take the sand fill with a primary outline, and Select all shows a partial state. The bar is sticky at the bottom (above the bottom edge on mobile, replacing the Upload button). Announced: "3 selected". Escape or Clear empties it. |
| Bulk delete: confirm | Delete in the bulk bar. The dialog says how many of the selection are in use and lists them. The confirm button carries the count. |
| Bulk delete: in progress | Requests in flight. The dialog can't be dismissed. |
| Bulk delete: partly failed | Some requests failed. Deleted images leave the grid, failed ones stay selected, and the toast stays until retried or dismissed. |
| Bulk delete: done | 204 for all. Focus moves to the next item. |
| Detail panel: in use | Click or Enter on an item. Right-hand slideover on desktop, full screen on mobile with a back arrow. Actions: Copy URL, Rename, Delete. "Used in 2 articles" lists title, Online or Draft, and links to the editor. Focus returns to the item on close. |
| Detail panel: unused | Used in nothing. The section reads "Not used in any article" and says the image is safe to delete. |
| Detail panel: duplicate | The image has identical copies. An info alert links to the duplicates view. |
| Copy URL | Copy URL. Clipboard write succeeded. Success toasts last 5 s. |
| Rename: dialog | Rename in the panel. The field holds the name without its extension, and the .jpg ending is fixed. The description says the URL stays the same. |
| Rename: saving | PATCH in flight. Field and buttons disabled, dialog can't be dismissed. |
| Rename: validation | Empty or only symbols, on submit or blur. Nothing is sent. |
| Rename: failed | 500 or network failure. The error shows inside the dialog. |
| Rename: done | 200: the panel title and list update in place. |
| Delete: unused image | Delete in the panel. Plain confirm. Says what happens and that it can't be undone. |
| Delete: image in use | Stronger confirm. Lists the affected articles and states that they will show a broken image. |
| Delete: in progress | DELETE in flight. The dialog can't be dismissed. |
| Delete: failed | 500 or network failure. The error shows inside the dialog, as in the article delete. |
| Delete: done | 204: the panel closes, the item leaves the grid and focus moves to the next item. |
| Image already gone (404) | Any action on an image that was deleted elsewhere. The panel closes and the item leaves the list. |
| Upload: drag over the page | Files dragged onto the page. A dashed drop area covers the content. Dropping starts the upload straight away; there is no crop step on this page. |
| Upload: several files, mixed | Upload button or drop, several files. Each file has its own row and progress. Files upload two at a time. A row can end as added, "Already in your library", rejected in the browser, or failed. Rejected and failed rows stay until dismissed. |
| Upload: summary | All rows settled. The summary counts each outcome. "Use existing" selects the existing image and drops the row; "Upload anyway" stores a second copy, which then appears under Duplicates. "Try again" retries one file. Announced when it finishes. |
| Upload: rejected files (413, 400) | Type and size are checked in the browser first, so nothing is sent. A server 413 or 400 for a file that got through shows the same row with its own message. |
| Upload: too many requests (429) | Rate limited. Retry-After is counted down in the button. It re-enables at zero. Already-added files are kept. |
| Duplicates: groups | The Duplicates tab. Groups of identical images side by side, each with its uploader, upload date and "Used in N articles". The suggested copy to keep is the most used, then the oldest. |
| Duplicates: empty | No groups. The Duplicates tab loses its count badge. |
| Merge: confirm | "Merge into this one" on floorboards.jpg. The dialog says articles using the other copies will switch to this image and the other copies will be deleted, with the article count. |
| Merge: in progress | Request in flight. The dialog can't be dismissed. |
| Merge: failed | 500 or network failure. Nothing is switched or deleted. |
| Merge: conflict (409) | A copy was deleted, or a new copy appeared, since the page loaded. |
| Merge: done | 200: the group leaves the list. When it was the last one, "No duplicates" shows. |
| List failed to load | A 500 or network failure on the list request. The alert replaces the images; Try again repeats the request. |
| Offline | navigator.onLine is false. Loaded images stay browsable. Upload, Rename, Delete and Merge are disabled, and the banner says why. |
+179
View File
@@ -0,0 +1,179 @@
# Profile
- **Route:** `/profile`
- **API:** GET /v1/auth/me · PATCH /v1/user/me (pending) · POST /v1/auth/password-reset
- **Visual reference:** `source/RenewCMS Screens Back-office.dc.html`, group "Profile" (open it in a browser; each state is drawn at desktop and mobile, with a light/dark toggle).
Opened from the account menu at the bottom of the sidebar. Username, email and password are read-only. The display name is optional, trimmed, and up to 60 characters.
Once saved it replaces the username everywhere a person is named:
- the sidebar chip and the account menu (name, and the avatar initials)
- the Home greeting ("Good morning, Marta Alves")
- the Display name column of the Users list
- the emails RenewCMS sends, such as "Marta Alves invited you to RenewCMS"
Saving it empty goes back to the username. Logging in still uses the username.
The reset link uses the same flow as "Forgot password" and ends on the auth board's "Choose a new password" screen ([reset-password.md](reset-password.md)).
## The page
Three cards under the title "Profile" and the subtitle "Your account on this RenewCMS workspace.", 720 px wide at most.
| Card | Content |
|---|---|
| Display name | Title "Display name". Text "Shown instead of your username across the back-office and in the emails RenewCMS sends. Leave it empty to use your username." One input, label "Display name (optional)", placeholder "e.g. Marta Alves", with a live counter "n / 60" in mono on the right of the help row. A footer strip holds a status line on the left and the Save button on the right. |
| Account | Title "Account". Text "Set when your account was created. You log in with your username, even after adding a display name." Two disabled inputs with a lock icon: Username and Email (two columns on desktop, one on mobile). |
| Password | Title "Password". Text "To change it, we'll email a reset link to marta@renew.example. The link works once, within 1 hour." A disabled input showing "••••••••••••" beside the button "Send reset link" (mail icon). A note appears under them once a request has been made. |
**Footer status line** (12 px): "Unsaved changes" in the warning color while dirty and not saving. Otherwise "You appear as “Marta Alves”." when a display name is saved, or "You appear as “marta”, your username." when it isn't.
**Save button:** full opacity when the value changed and is valid, or while saving. 40 % opacity and inert otherwise. Enter in the field saves.
**Counting:** characters are counted as Unicode characters, not bytes or UTF-16 units. The counter turns red over 60.
**Leaving the page** with unsaved changes asks for confirmation.
**Mobile:** cards use 16 px padding, inputs are 44 px, the two account inputs stack, and the password input and its button stack.
## The account menu
Opened from the account chip at the bottom of the sidebar (chevrons-up-down icon; `aria-haspopup="menu"`, `aria-expanded`). The chip takes the sand fill with ink text while the menu is open, and while `/profile` is the current page.
Desktop: a 224 px popover above the chip, aligned to its left. Mobile: the account row in the navigation drawer opens it as a bottom sheet with a grab handle. Escape or a click outside closes both.
| Part | Content |
|---|---|
| Header | The name in semibold (display name, or the username), and the email in muted 12 px (14 px on mobile, with a 36 px initials avatar beside them) |
| Item | Profile (circle-user icon), highlighted while on `/profile` |
| Separator | |
| Items | System, Light, Dark: a radio-style group, the current choice carries a check icon at the right edge; choosing one applies the theme at once and keeps the menu open |
| Separator | |
| Item | Log out (log-out icon) |
Avatar initials come from the first letters of the first two words of the display name, uppercased ("Marta Alves" gives MA). Without a display name they come from the username.
The board's menu now carries System, Light and Dark, matching the shipped UserMenu. The theme choice stays in the account menu; the Profile page does not repeat it. Items are 32 px on desktop and 48 px in the mobile sheet.
## States
### Account menu
**Trigger:** The account chip at the bottom of the sidebar. On mobile, the account row in the navigation drawer opens it as a sheet. Escape or a click outside closes it.
- Breadcrumbs: Home (mobile title "Home")
- Page behind the menu: Home, default
- Menu open, as described above, with the System, Light and Dark group between Profile and Log out. The board shows Light checked
### Loading
**Trigger:** Opened directly by URL before /auth/me has returned. From the menu, the cached user renders straight away.
- Breadcrumbs: Profile (mobile title "Profile")
- Three skeleton cards (one input, two inputs, one input)
### Default, no display name
**Trigger:** The usual first visit. The username is used everywhere.
- Breadcrumbs: Profile (mobile title "Profile")
- Display name: empty, placeholder "e.g. Marta Alves", counter "0 / 60"
- Footer: "You appear as “marta”, your username."
- Save: 40 % opacity
### Editing
**Trigger:** Typing in the field. Save turns on, and leaving the page asks for confirmation.
- Breadcrumbs: Profile (mobile title "Profile")
- Display name: "Marta Alves"; focused; counter "11 / 60"
- Footer: "Unsaved changes" (warning)
- Save: enabled
### Too long
**Trigger:** Over 60 characters. Checked as you type, and Save stays off.
- Breadcrumbs: Profile (mobile title "Profile")
- Display name: "Marta Alves, Head of Renovations, Brussels and Wallonia office"; focused; counter red
- **Error "Use 60 characters or fewer."**
- Footer: "Unsaved changes" (warning)
- Save: 40 % opacity
### Saving
**Trigger:** Save, or Enter in the field. The field is disabled.
- Breadcrumbs: Profile (mobile title "Profile")
- Display name: "Marta Alves", disabled, dimmed
- Save: "Saving…" with a loader
### Saved
**Trigger:** 200: the sidebar and account menu switch to the display name at once, and a toast confirms.
- Breadcrumbs: Profile (mobile title "Profile")
- Sidebar chip: "Marta Alves", initials MA
- Display name: "Marta Alves"; counter "11 / 60"
- Footer: "You appear as “Marta Alves”."
- Toast (success, circle-check): **Display name saved** "You now appear as Marta Alves across RenewCMS and in emails."
### Save failed
**Trigger:** 500 or network failure. The typed value is kept.
- Breadcrumbs: Profile (mobile title "Profile")
- Alert (error) in the Display name card: "Couldn't save your display name. Your text is still here. Try again in a moment."
- Display name: "Marta Alves"
- Footer: "Unsaved changes" (warning)
- Save: enabled
### Reset: sending
**Trigger:** "Send reset link". No confirmation, since it only sends an email.
- Breadcrumbs: Profile (mobile title "Profile")
- Button: "Sending…" with a loader
- Sidebar chip shows the display name "Marta Alves"
### Reset: sent
**Trigger:** 200. The message stays until the page is left. "Send again" sends a new link and the old one stops working.
- Breadcrumbs: Profile (mobile title "Profile")
- Button: "Send again" (mail)
- Note (success, mail-check): **Reset link sent** "Check marta@renew.example. The link works once, within 1 hour."
### Reset: too many requests (429)
**Trigger:** Rate limited. The button is disabled for 5 minutes.
- Breadcrumbs: Profile (mobile title "Profile")
- Button: "Send reset link", 40 % opacity, disabled
- Note (warning, clock-alert): **Too many requests** "You've asked for several links recently. Wait a few minutes, then try again."
### Reset: failed
**Trigger:** 500 or network failure. The button can be pressed again.
- Breadcrumbs: Profile (mobile title "Profile")
- Button: "Send reset link"
- Note (error, circle-x): **Couldn't send the link** "Check your connection and try again."
### Display names in the Users list
**Trigger:** The Display name column of the Users list shows the name when one is set and a dash when not. Your own row follows your saved name. This state needs the Users page ([users.md](users.md)).
- Breadcrumbs: Users (mobile title "Users")
- Signed-in user's display name: "Marta Alves" (sidebar chip shows it too)
- Row `marta@renew.example` (you): display name "Marta Alves", role owner, Accepted
- Row `ines.duarte@renew.example`: display name "Inès Duarte", role admin, Accepted
- Row `jonas@renew.example`: display name "—" (muted), role admin, Accepted
## Notes for implementation
- `PATCH /v1/user/me` is marked pending by the design: it does not exist yet. `GET /v1/auth/me` has to start returning the display name.
- The Password card sends the reset email to the account's own address through the existing `POST /v1/auth/password-reset`. The link ends on the reset confirm screen, and a successful reset invalidates the current session like any other reset.
- "Disabled for 5 minutes" is the design's number. The real window comes from the `Retry-After` header, as on the login and reset screens.
- Resolved: the theme choice (System, Light, Dark) stays in the account menu, as the board now draws it. The board still draws Profile highlighted on Home; the app highlights it only on `/profile`.
+125
View File
@@ -0,0 +1,125 @@
# Settings
- **Route:** `/settings`
- **API:** GET /v1/settings (version) · GET /v1/system/update · POST /v1/system/update/check · POST /v1/system/update/download · POST /v1/system/update/restart
- **Visual reference:** `source/RenewCMS Screens Back-office.dc.html`, group "Settings", drawn by `source/AppFrame.dc.html` (open it in a browser; each state is drawn at desktop and mobile, with a light/dark toggle).
Opened from the sidebar (Settings, settings icon, after Integration) and from the mobile drawer. Every verified user sees it. It holds two sections: Version (everyone) and Updates (the owner has the buttons, admins read the status).
The Updates card lets a non-technical owner update the site without a terminal. **Update** downloads the new version and checks it, and changes nothing. **Restart** installs it and restarts the site (about 10 seconds). "Restart later" is simply closing the dialog or leaving the page; the update waits. A plain **Restart** appears only when no update is waiting. The state lives on the server, so any owner on any device sees the same card, and the buttons are disabled while any step runs.
Out of scope: choosing versions, downgrades, automatic updates, update history.
## The page
Title "Settings", subtitle "Workspace information.", 720 px at most, 20 px between sections. Page padding 32 px on desktop and `20px 16px 88px` on mobile.
**Version card** (unchanged): label "Version" and the running build's version in IBM Plex Mono 14 px, shown exactly as the server reports it (for example `v2.2.0-beta`).
**Updates card**, under it: `--ui-bg`, 1 px `--ui-border`, 20 px padding (16 px on mobile), 16 px gap. A region labelled by its heading "Updates" (`id="updates-h"`, `tabindex="-1"`, focus ring `2px solid var(--ui-primary)` with 4 px offset when focus is moved there). Inside:
| Part | Content |
|---|---|
| Status block | A polite live region (`aria-live="polite"`): 14 px padding, 12 px gap, an 18 px icon, a semibold title, the text, and a muted `meta` line. Background and icon color follow the tone: neutral `--ui-bg-muted`, success, info, warning, error (`--rc-<tone>-soft` fill, `--ui-<tone>` icon). |
| Progress | A `progressbar` with a value (`aria-valuenow`) while downloading, labelled for example "Downloading version 2.3.0", with the text `42% · 11 of 26 MB`. Indeterminate while verifying (35 % wide moving bar), labelled "Checking the download", text "Almost there". Announced at 25 % steps and when the step changes, never on every tick. |
| Release notes | A button "What's new in 2.3.0" with `aria-expanded` and a chevron, collapsed by default. Open: "Released 24 Sep 2026" and a plain-text list. |
| Server command | Only in the "Not prepared" state: "For whoever manages the server", a one-line `code` block, a Copy button (reads "Copied" with a check for 2 s, announced), and the note "They run this once on the server. After that, Update and Restart appear here." The command shown is `renewcms enable-browser-updates` and is subject to the real one. |
| Buttons | 32 px high (44 px on mobile, stacked full width), 14 px side padding. One primary at most. Disabled buttons use 40 % opacity. |
| Hint | 12 px muted line under the buttons. |
| Link | Underlined, with an `arrow-up-right`: "How to update" or "Read the release notes". |
Buttons used: **Check for updates** (`refresh-cw`, secondary), **Update** (`download`, primary), **Restart** (`power`, primary when an update is ready, otherwise secondary), **Try again** (`rotate-cw`, primary), and the disabled "Checking…" and "Updating…" (`loader-circle`). Copy such as "Version 2.3.0" names the newer release. Decision for the spec: show the release tag without its leading `v` ("Version 2.3.0-beta" for tag `v2.3.0-beta`), while the Version card keeps the running build exactly as the server reports it.
## Copy
| Where | Copy |
|---|---|
| Up to date | `circle-check`, success: "You're up to date" / "You have the latest version of RenewCMS." / "Last checked today at 09:41"; buttons "Check for updates" and "Restart"; hint "Restart takes about 10 seconds. Your site is unavailable while it restarts." |
| Checking | `loader-circle`: "Checking for updates…" / "This usually takes a few seconds."; "Checking…" disabled |
| Check failed | `wifi-off`, warning: "Couldn't check for updates" / "RenewCMS couldn't reach the update server. Check your connection and try again. Your site isn't affected." / "Last checked yesterday at 18:12"; "Try again" (primary) and "Restart" |
| Available | `circle-arrow-up`, info: "Version 2.3.0 is available" / "You have v2.2.0-beta. Update downloads the new version and checks it. Nothing changes until you restart."; "Update"; hint "Takes about 2 minutes. Your site stays online." |
| Downloading | `download`, info: "Downloading version 2.3.0…" / "You can leave this page. The download continues and your site stays online."; "Updating…" disabled |
| Verifying | `shield-check`, info: "Checking the download…" / "Making sure the file is complete and safe to install. This takes a few seconds." |
| Ready | `circle-check`, success: "Version 2.3.0 is ready to install" / "The download is checked. Restart to install it. Your site will be unavailable for about 10 seconds." / "Nothing has changed yet."; "Restart"; hint "Not now? Leave this page. The update waits here, and the banner on Home reminds you." |
| Done | "You're on version 2.3.0" / "The update is installed and your site is running again." / "Updated today at 09:52"; link "Read the release notes"; toast `circle-check` "Update installed" / "RenewCMS is now on version 2.3.0." |
| Rolled back | `triangle-alert`, warning: "The update didn't install" / "RenewCMS put the previous version back, so your site is running as before. Nothing was lost." / "What to do next: try again in a few minutes. If it fails again, ask whoever manages your server to check the update."; "Try again"; toast (error, stays) `circle-x` "The update didn't install" / "Your site is back on v2.2.0-beta." |
| Download failed | `circle-x`, error: "The download didn't finish" / "The connection dropped before the file was complete. Nothing was changed and your site is running as before."; "Try again" |
| Not trusted | `triangle-alert`, warning: "We didn't use this update" / "The file didn't pass our safety check, so it was not installed. Nothing was changed. Try downloading it again. If this keeps happening, contact RenewCMS support." Technical detail goes to the server log. |
| Rate limited | `info`: "Too many tries" / "Wait a moment before trying again."; button "Try again in 0:42" counting down Retry-After |
| Not prepared | `info`: "Version 2.3.0 is available" / "This site can't update itself from the browser yet. Whoever manages your server can set it up once, or update RenewCMS for you." and a link "How to update". No buttons, not even Restart. |
| Admin | "Version 2.3.0 is available" / "You have v2.2.0-beta. Only the owner can update RenewCMS. Ask the owner of this site." No buttons. Up to date reads "You're up to date" and "Only the owner can update or restart the site." |
## Dialogs and overlays
Both dialogs use the ConfirmDialog behaviour: focus moves to the first button, Escape and the cancel button close it, and focus returns to the button that opened it. The confirm button is neutral, not red, because nothing is lost.
| Dialog | Title | Description | Cancel / Confirm |
|---|---|---|---|
| Install | "Restart to finish the update?" | "RenewCMS will install version 2.3.0 and restart. Your site will be unavailable for about 10 seconds. This page reloads on its own when the site is back. Save anything you're editing first." | "Restart later" / "Restart now" |
| Plain restart | "Restart the site?" | "Your site will be unavailable for about 10 seconds. This page reloads on its own when the site is back. Save anything you're editing first." | "Cancel" / "Restart site" |
Failure inside the install dialog: "Couldn't start the restart. Nothing was changed and your site is still running. Try again in a moment."
Restart overlay: a full-page `role="status"` live region (`--ui-bg-muted`, 440 px card) that survives the server going away, with a moving bar. Copy: "Installing version 2.3.0" / "Your site is restarting with the new version. This takes about 10 seconds. This page reloads on its own when the site is back." / "Started at 09:51". Announced once as "Installing version 2.3.0. Your site is restarting." After 60 seconds with no answer: "Still restarting" / "This is taking longer than usual. Keep this page open. It reloads on its own when the site is back, or you can reload it now." / "Started at 09:51 · 1 minute ago" and a "Reload page" button. Plain restart: "Restarting your site" / "This takes about 10 seconds. This page reloads on its own when the site is back." After the reload: focus lands on the "Updates" heading and a toast `circle-check` "Site restarted" / "Your site is running again."
## Elsewhere
For the owner only: an **Update** pill on the Settings sidebar item, and a dot on the menu icon on mobile (read as "Update available"). Admins see neither. The Home banner is described in [home](home.md).
## Status to copy
| Status | Where | Copy |
|---|---|---|
| 200 | Check, up to date | "You're up to date" and the last-checked line |
| 200 | Check, newer version | "Version 2.3.0 is available" and its text |
| 202 | Update, Restart | Accepted. The card switches to progress, announced as "Downloading version 2.3.0, 25 percent". |
| 200 | Update finished | "Version 2.3.0 is ready to install" |
| 200 | After restart | Toast "Update installed" or "Site restarted" |
| 400 | Update, nothing to install | Info toast "Nothing to update" / "You already have the latest version." The card refreshes. |
| 401 | any | Global: /login?redirect=/settings&reason=expired. No local copy. |
| 403 | any button, not the owner | Error toast "Only the owner can do this" / "Ask the owner of this site to update RenewCMS." The card reloads as the admin view. An unverified account is handled globally. |
| 409 | Update, Restart | Already running: info toast "An update is already running" / "Another owner started it. Progress shows here." Not prepared: the card shows the "Not prepared" state. |
| 422 | Update, file not trusted | The "Not trusted" card above |
| 429 | Check, Update | The rate-limited card above |
| 500 / network | Check | "Couldn't check for updates" with "Try again" |
| 500 / network | Update | "The download didn't finish" with "Try again" |
| 500 / network | Restart dialog | "Couldn't start the restart. Nothing was changed and your site is still running. Try again in a moment." |
| Site back, old version | after restart | The rolled-back card above |
| No answer, 60 s | restart overlay | "Still restarting" |
| Offline | whole page | Existing banner. Check, Update and Restart are disabled. During a restart the overlay keeps polling and ignores the offline state. |
## Behaviour notes
- The page asks for `GET /v1/system/update` on open and, when a step is running, polls it every second. The server holds the state (idle, downloading, verifying, ready, restarting, succeeded, failed), so another device or owner sees the same card.
- A check runs on the first open after 24 hours and when "Check for updates" is pressed.
- Update takes no confirmation because it changes nothing. Restart always asks.
## States
| State | Trigger and behaviour |
|---|---|
| Up to date | Opened with no newer version. Restart is available but not emphasised. |
| Checking | Check for updates pressed, or the first open after 24 hours. Announced as "Checking for updates". Buttons are disabled. |
| Check failed | Offline, or the update server didn't answer (500, network). The last known result is kept. |
| Update available | A newer version exists. Release notes are collapsed. Update is the one primary button. |
| Update available, notes open | "What's new in 2.3.0" expanded. It is a button with aria-expanded, and the list is plain text. |
| Downloading | Update pressed (202). Progress polls every second. Announced as "Downloading, 25 percent" and so on, never every tick. |
| Verifying | The download finished. No percentage, so the bar is indeterminate. Announced as "Checking the download". |
| Ready to install | The file passed its checks. Restart becomes the primary action. "Restart later" is closing the dialog or leaving the page. |
| Restart: confirm | Restart pressed. Same dialog behaviour as the delete confirm: focus moves to the first button, Escape and "Restart later" close it, and focus returns to Restart. The confirm button is neutral, not red, because nothing is lost. |
| Restart: request failed | 500 or network failure before the restart began. The site is still running. |
| Restarting to install | Full-page overlay, so it survives the server going away. The page polls until the site answers, then reloads. It is a live region announced once as "Installing version 2.3.0. Your site is restarting." |
| Restarting, taking longer | No answer after 60 seconds. The copy changes and a manual reload appears. The overlay stays until the site is back. |
| Update done | The page reloaded on the new version. Focus lands on the "Updates" heading (ring shown), the toast is announced, and the version updates. |
| Update failed, rolled back | The site came back on v2.2.0-beta. The error toast stays until dismissed and the card keeps the explanation. |
| Download failed | A 500, or the connection dropped. Focus moves to the card heading. Try again restarts the download. |
| Verification failed | The downloaded file isn't trusted. The tone is a warning, and the file is thrown away. Technical detail goes to the server log, not the screen. |
| Too many requests (429) | Retry-After counted down in the button. It re-enables at zero. |
| Not prepared | The server can't update from the browser. No buttons, not even Restart. The command is for the person who runs the server and is a single line. The placeholder command is subject to the real one. |
| Not prepared: command copied | Copy pressed. The button reads "Copied" for 2 s and it is announced. |
| Plain restart: confirm | Restart with no update waiting. Nothing is installed. |
| Plain restart: restarting | Same overlay as the update restart with shorter copy. |
| Plain restart: done | The page reloaded. Focus lands on the "Updates" heading. |
| Admin view | Admins see the version and the note, with no buttons. Up to date: "You're up to date" and "Only the owner can update or restart the site." No Home banner or Settings pill. |
| Role changed (403) | An owner was changed to admin while the page was open and pressed a button. The card reloads in the admin view. |
| Update already running (409) | Another owner started it. The card switches to that run's progress. |
+232
View File
@@ -0,0 +1,232 @@
# Users
- **Route:** `/users`
- **API:** GET /v1/user/ · POST /v1/user/invite · DELETE /v1/user/invite/:id (pending) · POST /v1/user/invite/:id/renew (pending)
- **Visual reference:** `source/RenewCMS Screens Back-office.dc.html`, group "Users" (open it in a browser; each state is drawn at desktop and mobile, with a light/dark toggle).
One shared workspace: every user sees the same articles and this same list. The list shows email, display name, role, invite status and created date. A Pending invite can be cancelled and an Expired one renewed; accepted accounts have no row actions, so nobody can be removed or promoted from here. Only the owner can invite, cancel and renew (see "Roles").
An invite is **Pending** until its link is used, **Expired** after 3 days, and **Accepted** once the account is created. The list is sorted by created date, newest first.
## Roles
There are two roles. They are shown as a badge and are not editable.
| Role | Who | Can |
|---|---|---|
| owner | The account that registered first on the workspace. There is exactly one. | Everything an admin can, plus invite users, cancel invites and renew invites. |
| admin | Everyone who joined through an invite. Every invite creates an admin. | Read and write articles, see the Users list, edit their own profile, see Settings. |
The owner is the only difference for now. The role cannot be changed, transferred or removed from the UI.
**Not drawn by the board** (decide in the spec, cover by Vitest and Go tests only, like the 429 on invite):
- What a non-owner sees: the recommendation is to hide "Invite user" (desktop and mobile), hide the row actions, and hide the "Invite someone…" hint on the "Only you" state.
- The API answer when a non-owner calls an owner-only endpoint: the recommendation is 403 with a plain-text body, and no state change.
- The message if the owner's session sees a 403 anyway (role changed under it): the global 403 handling applies.
## The list
| Column | Content |
|---|---|
| Email | The account's or invite's email address, medium weight, highlighted. The current user's row carries a muted mono "you" tag after it. |
| Display name | The display name when set, highlighted; a muted dash `—` when not. An invite has none, so it shows the dash. Your own row follows your saved name. |
| Role | A mono 11 px badge, 20 px high: `owner` (filled, `--ui-primary` with `--ui-bg` text) or `admin` (transparent, toned text, `--ui-border-accented` border). An invite shows the role it will create, `admin`. |
| Invite status | A badge: Accepted (circle-check, success), Pending (mail, warning), Expired (clock-alert, outline, muted). Shown by icon and word as well as color. |
| Created | The date as `27 Sep 2026`, or "Today" for the current day. For an invite it is the day the invite was sent (or last renewed), for a user the day the account was created. |
| (actions) | Right-aligned, no header text. Pending row: "Cancel invite". Expired row: "Renew invite". Accepted row: empty. |
The username is no longer shown in this list.
Desktop is a table: 36 px header, 48 px rows, columns `minmax(0,1.3fr) minmax(0,1fr) 84px 120px 110px 150px` with a 12 px gap. Below md it becomes a card list (68 px minimum row height): the email line (with "you"), the display name below it when there is one, then the role badge, the status badge and "Created {date}" on one line, then the row action, if any, as a 44 px button with 14 px side padding.
The page header is a title "Users" with the subtitle "Everyone who can sign in and work on your articles." and a primary "Invite user" button (user-plus icon) on its right. On mobile the button becomes a full-width 48 px button pinned to the bottom of the screen.
The owner is always listed, so the list is never empty.
### Row actions
| Action | Shown on | Icon | Look |
|---|---|---|---|
| Cancel invite | Pending | user-x | Outline button, text in `--ui-error` |
| Renew invite | Expired | refresh-cw | Outline button, text `--ui-text-highlighted` |
Desktop buttons are 28 px high, 12 px medium text, a 13 px icon, 9 px side padding, `--ui-border-accented` border, `--ui-bg` fill. Mobile buttons are 44 px high and 14 px side padding with a 14 px icon.
- **Cancel invite** asks first with a danger confirmation dialog, since it cannot be undone from here (the address can be invited again).
- **Renew invite** asks nothing, since it only sends an email. While the request runs, that row's button reads "Renewing…" with a loader-circle icon at 50 % opacity and is disabled. Only that row is busy.
## States
### Default
**Trigger:** The list loaded, newest first.
- Breadcrumbs: Users (mobile title "Users")
- Rows:
- `sam.oliveira@renew.example`, no display name, admin, Pending, 27 Sep 2026, "Cancel invite"
- `p.huber@gmail.com`, display name "Paul Huber", admin, Expired, 3 Aug 2026, "Renew invite"
- `ines.duarte@renew.example`, "Inès Duarte", admin, Accepted, 18 Jun 2026
- `jonas@renew.example`, no display name, admin, Accepted, 2 Apr 2026
- `marta@renew.example` (you), no display name, owner, Accepted, 12 Mar 2026
The board gives the Expired invite a display name. A real invite has none, so the SPA renders whatever `display_name` the item carries and the dash when it is empty.
### Loading
**Trigger:** The first load, or a retry. Skeletons appear after 150 ms.
- Breadcrumbs: Users (mobile title "Users")
- Five skeleton rows, one bar per column, plus a role-badge and a status-badge placeholder
### Only you
**Trigger:** Nobody has been invited yet. The owner is always listed.
- Breadcrumbs: Users (mobile title "Users")
- One row: `marta@renew.example` (you), owner, Accepted
- Hint under the list: "Invite someone so they can sign in with their own account instead of sharing yours."
### Error
**Trigger:** A 500 or network failure on the list request.
- Breadcrumbs: Users (mobile title "Users")
- Alert (error): **Couldn't load users** "Check your connection and try again."
- Action "Try again" (rotate-cw)
- No table or cards
### Invite: default
**Trigger:** "Invite user" in the page header, or the bottom button on mobile.
- Breadcrumbs: Users (mobile title "Users")
- Modal: **Invite a user**
- text "We'll email them a link to choose a username and password. The link expires after 3 days."
- field `Email`: placeholder "name@example.com"; focused
- close button
- cancel "Cancel"
- confirm "Send invite"
### Invite: validation
**Trigger:** On submit or blur. Nothing is sent.
- Breadcrumbs: Users (mobile title "Users")
- Modal: **Invite a user** (same text)
- field `Email`: value "sam.oliveira@renew"; **error "Enter a full email address, like name@example.com."**
- cancel "Cancel"
- confirm "Send invite"
### Invite: sending
**Trigger:** Request in flight. The field is disabled and the dialog can't be dismissed.
- Breadcrumbs: Users (mobile title "Users")
- Modal: **Invite a user** (same text)
- field `Email`: value "lea.martin@renew.example"; disabled
- cancel "Cancel"
- confirm "Sending…", loading, not dismissible
### Invite: already a user (409)
**Trigger:** The email belongs to an existing user. For a live pending invite the message reads "There's already a pending invite for this address." An expired invite can be sent again.
- Breadcrumbs: Users (mobile title "Users")
- Modal: **Invite a user** (same text)
- field `Email`: value "jonas@renew.example"; **error "This address already has an account."**
- cancel "Cancel"
- confirm "Send invite"
### Invite: failed
**Trigger:** 500, network failure, or the email couldn't be sent. The address stays in the field.
- Breadcrumbs: Users (mobile title "Users")
- Modal: **Invite a user** (same text)
- field `Email`: value "lea.martin@renew.example"
- Alert: "Couldn't send the invite. Try again in a moment."
- cancel "Cancel"
- confirm "Send invite"
### Invite sent
**Trigger:** 201: the dialog closes, the new invite appears at the top as Pending (highlighted row), and a toast confirms.
- Breadcrumbs: Users (mobile title "Users")
- New first row: `lea.martin@renew.example`, no display name, admin, Pending, created "Today", row background `--ui-bg-elevated`, with "Cancel invite"
- Toast (success, circle-check): **Invite sent** "lea.martin@renew.example has 3 days to accept."
The "Today" label makes this state clock-sensitive, so `task visual:check` skips it.
### Cancel invite: confirm
**Trigger:** "Cancel invite" on a Pending row.
- Breadcrumbs: Users (mobile title "Users")
- Modal (danger): **Cancel this invite?**
- text "The link sent to sam.oliveira@renew.example will stop working. You can invite the address again later."
- cancel "Keep invite"
- confirm "Cancel invite"
### Cancel invite: sending
**Trigger:** Request in flight. Both buttons are disabled and the dialog can't be dismissed.
- Breadcrumbs: Users (mobile title "Users")
- Modal (danger): **Cancel this invite?** (same text)
- cancel "Keep invite", disabled
- confirm "Cancelling…", loading
### Cancel invite: failed
**Trigger:** 500 or network failure. The dialog stays open.
- Breadcrumbs: Users (mobile title "Users")
- Modal (danger): **Cancel this invite?** (same text)
- notice "Couldn't cancel the invite. Try again in a moment."
- cancel "Keep invite"
- confirm "Cancel invite"
### Cancel invite: done
**Trigger:** 204: the row disappears and a toast confirms.
- Breadcrumbs: Users (mobile title "Users")
- The Pending row `sam.oliveira@renew.example` is gone; the other four remain
- Toast (success, circle-check): **Invite cancelled** "sam.oliveira@renew.example can no longer use the link."
### Renew invite: sending
**Trigger:** "Renew invite" on an Expired row. No confirmation, since it only sends an email. The button shows progress and is disabled.
- Breadcrumbs: Users (mobile title "Users")
- The Expired row's button reads "Renewing…" with a loader-circle icon, 50 % opacity, disabled
### Renew invite: done
**Trigger:** 200: the row becomes Pending with today's date, moves to the top, and the old link stops working.
- Breadcrumbs: Users (mobile title "Users")
- First row: `p.huber@gmail.com` Pending, created "Today", row background `--ui-bg-elevated`, now with "Cancel invite"
- Toast (success, circle-check): **Invite renewed** "p.huber@gmail.com has 3 days to accept the new link."
The "Today" label makes this state clock-sensitive, so `task visual:check` skips it.
### Renew invite: failed
**Trigger:** 500 or network failure. The row stays Expired and the button can be pressed again.
- Breadcrumbs: Users (mobile title "Users")
- Toast (error, circle-x): **Couldn't renew the invite** "Try again in a moment."
## Notes for implementation
- Accepted users are now listed by email, display name and role. This reverses the earlier rule that a user is never listed with an email.
- How display names look in this list is the state "Display names in the Users list" of [profile.md](profile.md). The board draws it in the Profile group, and `task visual:check` finds states by group.
- The board's API line marks both new endpoints "(pending)", meaning "not built yet". Cancel applies to a Pending invite. Renew is drawn on an Expired one; the recommendation is that the API also accepts a Pending one (it resets the 3 days and replaces the link) and refuses an Accepted one with 409. The SPA only offers Renew on Expired rows.
- Renewing replaces the code and expiry, resets the created date to now, and sends the invitation email again. The old link stops working. The email is specified in [emails.md](../emails.md).
- A 404 on cancel or renew (the invite was already used or cancelled elsewhere) is not drawn. Decide it in the spec; the recommendation is to drop the row and toast the outcome.
- 429 on the invite request is not drawn. Decide it in the spec before coding.
- The email the invite sends is specified in [emails.md](../emails.md). The screen the link opens is in [accept-invite.md](accept-invite.md).
- The role rules and what is not drawn are in "Roles" above.
+170 -12
View File
@@ -12,19 +12,20 @@
<div style="width:224px;flex-shrink:0;background:var(--ui-bg);border-right:1px solid var(--ui-border);display:flex;flex-direction:column;padding:12px;gap:2px"> <div style="width:224px;flex-shrink:0;background:var(--ui-bg);border-right:1px solid var(--ui-border);display:flex;flex-direction:column;padding:12px;gap:2px">
<div style="display:flex;align-items:center;gap:10px;height:40px;padding:0 6px;margin-bottom:10px"><svg width="26" height="26" viewBox="0 0 16 16" shape-rendering="crispEdges"><rect width="16" height="16" fill="#111"></rect><path fill="#fff" fill-rule="evenodd" d="M4 3h6v1h1v1h1v3h-1v1h-1v1h1v1h1v2h-2v-2h-1v-1H6v3H4zm2 2v3h4V5z"></path></svg><span style="font-weight:600;font-size:14px;color:var(--ui-text-highlighted)">RenewCMS</span></div> <div style="display:flex;align-items:center;gap:10px;height:40px;padding:0 6px;margin-bottom:10px"><svg width="26" height="26" viewBox="0 0 16 16" shape-rendering="crispEdges"><rect width="16" height="16" fill="#111"></rect><path fill="#fff" fill-rule="evenodd" d="M4 3h6v1h1v1h1v3h-1v1h-1v1h1v1h1v2h-2v-2h-1v-1H6v3H4zm2 2v3h4V5z"></path></svg><span style="font-weight:600;font-size:14px;color:var(--ui-text-highlighted)">RenewCMS</span></div>
<sc-for list="{{ nav }}" as="n" hint-placeholder-count="3"> <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 }}</div> <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></div>
</sc-for> </sc-for>
<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="logout" title="Log out" style="display:flex;align-items:center;gap:10px;height:40px;padding:0 6px"><span style="width:26px;height:26px;background:#d4c5b0;color:#111;display:flex;align-items:center;justify-content:center;font:600 11px 'IBM Plex Sans',sans-serif">MA</span><span style="flex:1;color:var(--ui-text-highlighted)">marta</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:#d4c5b0;color:#111;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>
</div> </div>
<sc-if value="{{ deskMenu }}"><div role="menu" aria-label="Account" style="position:absolute;left:12px;bottom:56px;z-index:40;width:224px;background:var(--ui-bg);border:1px solid var(--ui-border);box-shadow:var(--rc-shadow-pop);padding:4px"><div style="padding:8px 8px 10px;display:flex;flex-direction:column;gap:2px;border-bottom:1px solid var(--ui-border);margin-bottom:4px"><span style="font-weight:600;color:var(--ui-text-highlighted);overflow:hidden;text-overflow:ellipsis;white-space:nowrap">{{ who }}</span><span style="font-size:12px;color:var(--ui-text-muted)">marta@renew.example</span></div><div data-act="nav-profile" role="menuitem" style="height:32px;padding:0 8px;display:flex;align-items:center;gap:10px;background:{{ pfItemBg }};color:var(--ui-text-highlighted)"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:16px;height:16px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/circle-user.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/circle-user.svg') center / contain no-repeat"></span>Profile</div><div style="height:1px;background:var(--ui-border);margin:4px 0"></div><sc-for list="{{ themeSeg }}" as="m" hint-placeholder-count="3"><div data-act="{{ m.act }}" role="menuitemradio" aria-checked="{{ m.on }}" style="height:32px;padding:0 8px;display:flex;align-items:center;justify-content:space-between;font-size:14px;color:var(--ui-text-highlighted)">{{ m.t }}<span aria-hidden="true" style="display:inline-block;width:16px;height:16px;background-color:currentColor;opacity:{{ m.op }};-webkit-mask:url('https://api.iconify.design/lucide/check.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/check.svg') center / contain no-repeat"></span></div></sc-for><div style="height:1px;background:var(--ui-border);margin:4px 0"></div><div data-act="logout" role="menuitem" style="height:32px;padding:0 8px;display:flex;align-items:center;gap:10px;color:var(--ui-text-highlighted)"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:16px;height:16px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/log-out.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/log-out.svg') center / contain no-repeat"></span>Log out</div></div></sc-if>
</sc-if> </sc-if>
<div style="flex:1;min-width:0;min-height:0;display:flex;flex-direction:column"> <div style="flex:1;min-width:0;min-height:0;display:flex;flex-direction:column">
<sc-if value="{{ desk }}" hint-placeholder-val="{{ true }}"> <sc-if value="{{ desk }}" hint-placeholder-val="{{ true }}">
<div style="height:48px;flex-shrink:0;border-bottom:1px solid var(--ui-border);background:var(--ui-bg);display:flex;align-items:center;padding:0 24px;gap:8px;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/panel-left-close.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/panel-left-close.svg') center / contain no-repeat"></span><span style="width:1px;height:16px;background:var(--ui-border);margin:0 6px"></span><sc-for list="{{ crumbs }}" as="c" hint-placeholder-count="1"><sc-if value="{{ c.sep }}"><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></sc-if><span style="color:{{ c.fg }};font-weight:{{ c.fw }}">{{ c.t }}</span></sc-for></div> <div style="height:48px;flex-shrink:0;border-bottom:1px solid var(--ui-border);background:var(--ui-bg);display:flex;align-items:center;padding:0 24px;gap:8px;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/panel-left-close.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/panel-left-close.svg') center / contain no-repeat"></span><span style="width:1px;height:16px;background:var(--ui-border);margin:0 6px"></span><sc-for list="{{ crumbs }}" as="c" hint-placeholder-count="1"><sc-if value="{{ c.sep }}"><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></sc-if><span style="color:{{ c.fg }};font-weight:{{ c.fw }}">{{ c.t }}</span></sc-for></div>
</sc-if> </sc-if>
<sc-if value="{{ mob }}"> <sc-if value="{{ mob }}">
<div style="height:56px;flex-shrink:0;border-bottom:1px solid var(--ui-border);background:var(--ui-bg);display:flex;align-items:center;padding:0 6px;gap:4px;color:var(--ui-text-highlighted)"><span data-act="m-lead" style="width:44px;height:44px;display:flex;align-items:center;justify-content:center"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:20px;height:20px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/{{ mLead }}.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/{{ mLead }}.svg') center / contain no-repeat"></span></span><span style="flex:1;min-width:0;font-weight:600;font-size:16px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap">{{ s.mTitle }}</span><sc-if value="{{ s.mAction }}"><span data-act="m-action" style="width:44px;height:44px;display:flex;align-items:center;justify-content:center"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:20px;height:20px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/{{ s.mAction }}.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/{{ s.mAction }}.svg') center / contain no-repeat"></span></span></sc-if></div> <div style="height:56px;flex-shrink:0;border-bottom:1px solid var(--ui-border);background:var(--ui-bg);display:flex;align-items:center;padding:0 6px;gap:4px;color:var(--ui-text-highlighted)"><span data-act="m-lead" style="position:relative;width:44px;height:44px;display:flex;align-items:center;justify-content:center"><sc-if value="{{ s.navBadge }}"><span aria-label="Update available" style="position:absolute;top:9px;right:9px;width:10px;height:10px;background:var(--ui-info);border:2px solid var(--ui-bg)"></span></sc-if><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:20px;height:20px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/{{ mLead }}.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/{{ mLead }}.svg') center / contain no-repeat"></span></span><span style="flex:1;min-width:0;font-weight:600;font-size:16px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap">{{ s.mTitle }}</span><sc-if value="{{ s.mAction }}"><span data-act="m-action" style="width:44px;height:44px;display:flex;align-items:center;justify-content:center"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:20px;height:20px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/{{ s.mAction }}.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/{{ s.mAction }}.svg') center / contain no-repeat"></span></span></sc-if></div>
</sc-if> </sc-if>
<sc-if value="{{ s.offline }}"><div role="status" style="flex-shrink:0;display:flex;align-items:center;gap:10px;padding:10px 16px;background:var(--ui-bg-inverted);color:var(--ui-text-inverted)"><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/wifi-off.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/wifi-off.svg') center / contain no-repeat"></span><span style="flex:1">You're offline. You can keep writing, but saving and publishing will wait until you're back online.</span></div></sc-if> <sc-if value="{{ s.offline }}"><div role="status" style="flex-shrink:0;display:flex;align-items:center;gap:10px;padding:10px 16px;background:var(--ui-bg-inverted);color:var(--ui-text-inverted)"><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/wifi-off.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/wifi-off.svg') center / contain no-repeat"></span><span style="flex:1">You're offline. You can keep writing, but saving and publishing will wait until you're back online.</span></div></sc-if>
@@ -41,7 +42,8 @@
<sc-if value="{{ isHome }}"> <sc-if value="{{ isHome }}">
<div style="padding:{{ pad }};display:flex;flex-direction:column;gap:{{ gap }};max-width:1040px"> <div style="padding:{{ pad }};display:flex;flex-direction:column;gap:{{ gap }};max-width:1040px">
<div style="display:flex;align-items:flex-end;gap:16px;flex-wrap:wrap"><div style="flex:1;min-width:200px;display:flex;flex-direction:column;gap:4px"><span style="font:600 28px/36px 'IBM Plex Sans',sans-serif;color:var(--ui-text-highlighted)">Good morning, marta</span><span style="color:var(--ui-text-muted);font-size:14px">{{ s.home.sub }}</span></div><sc-if value="{{ desk }}"><span data-act="new" style="height:32px;padding:0 12px;display:flex;align-items:center;gap:6px;background:var(--ui-primary);color:var(--ui-bg);font-weight:500"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:16px;height:16px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/plus.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/plus.svg') center / contain no-repeat"></span>New article</span></sc-if></div> <div style="display:flex;align-items:flex-end;gap:16px;flex-wrap:wrap"><div style="flex:1;min-width:200px;display:flex;flex-direction:column;gap:4px"><span style="font:600 28px/36px 'IBM Plex Sans',sans-serif;color:var(--ui-text-highlighted)">Good morning, {{ who }}</span><span style="color:var(--ui-text-muted);font-size:14px">{{ s.home.sub }}</span></div><sc-if value="{{ desk }}"><span data-act="new" style="height:32px;padding:0 12px;display:flex;align-items:center;gap:6px;background:var(--ui-primary);color:var(--ui-bg);font-weight:500"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:16px;height:16px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/plus.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/plus.svg') center / contain no-repeat"></span>New article</span></sc-if></div>
<sc-if value="{{ s.home.banner }}"><div role="region" aria-label="Update available" style="display:flex;flex-direction:{{ upBtnDir }};align-items:{{ upBannerAlign }};gap:12px;padding:12px 14px;background:{{ s.home.banner.bg }};border:1px solid var(--ui-border)"><div style="flex:1;display:flex;gap:10px;min-width:0"><span style="display:flex;padding-top:2px"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:16px;height:16px;background-color:{{ s.home.banner.fg }};-webkit-mask:url('https://api.iconify.design/lucide/{{ s.home.banner.icon }}.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/{{ s.home.banner.icon }}.svg') center / contain no-repeat"></span></span><div style="display:flex;flex-direction:column;gap:2px"><span style="font-weight:600;color:var(--ui-text-highlighted)">{{ s.home.banner.title }}</span><span style="color:var(--ui-text-toned);text-wrap:pretty">{{ s.home.banner.text }}</span></div></div><div style="display:flex;align-items:center;gap:8px"><span style="flex:1;height:{{ btnH }};padding:0 12px;display:flex;align-items:center;justify-content:center;border:1px solid var(--ui-border-accented);background:var(--ui-bg);color:var(--ui-text-highlighted);font-weight:500">{{ s.home.banner.btn }}</span><span role="button" aria-label="Dismiss" style="width:{{ btnH }};height:{{ btnH }};display:flex;align-items:center;justify-content:center;color:var(--ui-text-muted)"><span aria-hidden="true" style="display:inline-block;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></sc-if>
<sc-if value="{{ s.home.error }}"><div role="alert" style="display:flex;gap:10px;padding:12px 14px;background:var(--rc-error-soft);color:var(--ui-error)"><span style="display:flex;padding-top:2px"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:16px;height:16px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/circle-x.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/circle-x.svg') center / contain no-repeat"></span></span><div style="flex:1;display:flex;flex-direction:column;gap:8px"><div style="display:flex;flex-direction:column;gap:2px"><span style="font-weight:600">Couldn't load your articles</span><span style="color:var(--ui-text-toned)">Check your connection and try again.</span></div><span style="align-self:flex-start;height:28px;padding:0 10px;display:flex;align-items:center;gap:6px;border:1px solid var(--ui-border-accented);background:var(--ui-bg);color:var(--ui-text-highlighted);font-weight:500;font-size:12px"><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/rotate-cw.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/rotate-cw.svg') center / contain no-repeat"></span>Try again</span></div></div></sc-if> <sc-if value="{{ s.home.error }}"><div role="alert" style="display:flex;gap:10px;padding:12px 14px;background:var(--rc-error-soft);color:var(--ui-error)"><span style="display:flex;padding-top:2px"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:16px;height:16px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/circle-x.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/circle-x.svg') center / contain no-repeat"></span></span><div style="flex:1;display:flex;flex-direction:column;gap:8px"><div style="display:flex;flex-direction:column;gap:2px"><span style="font-weight:600">Couldn't load your articles</span><span style="color:var(--ui-text-toned)">Check your connection and try again.</span></div><span style="align-self:flex-start;height:28px;padding:0 10px;display:flex;align-items:center;gap:6px;border:1px solid var(--ui-border-accented);background:var(--ui-bg);color:var(--ui-text-highlighted);font-weight:500;font-size:12px"><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/rotate-cw.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/rotate-cw.svg') center / contain no-repeat"></span>Try again</span></div></div></sc-if>
<sc-if value="{{ s.home.stats }}"> <sc-if value="{{ s.home.stats }}">
<div style="display:grid;grid-template-columns:{{ cols3 }};gap:12px"> <div style="display:grid;grid-template-columns:{{ cols3 }};gap:12px">
@@ -128,7 +130,7 @@
<span data-act="preview" style="display:flex;align-items:center;gap:8px;white-space:nowrap;flex-shrink:0;color:var(--ui-text-toned)"><span style="width:32px;height:18px;padding:2px;display:flex;justify-content:{{ pvJust }};background:{{ pvBg }}"><span style="width:14px;height:14px;background:var(--ui-bg)"></span></span>Preview</span> <span data-act="preview" style="display:flex;align-items:center;gap:8px;white-space:nowrap;flex-shrink:0;color:var(--ui-text-toned)"><span style="width:32px;height:18px;padding:2px;display:flex;justify-content:{{ pvJust }};background:{{ pvBg }}"><span style="width:14px;height:14px;background:var(--ui-bg)"></span></span>Preview</span>
<span data-act="save" style="height:32px;padding:0 12px;display:flex;align-items:center;gap:6px;white-space:nowrap;flex-shrink:0;border:1px solid var(--ui-border-accented);color:var(--ui-text-highlighted);font-weight:500;opacity:{{ saveOp }}"><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/save.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/save.svg') center / contain no-repeat"></span>Save</span> <span data-act="save" style="height:32px;padding:0 12px;display:flex;align-items:center;gap:6px;white-space:nowrap;flex-shrink:0;border:1px solid var(--ui-border-accented);color:var(--ui-text-highlighted);font-weight:500;opacity:{{ saveOp }}"><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/save.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/save.svg') center / contain no-repeat"></span>Save</span>
<span data-act="publish" style="height:32px;padding:0 12px;display:flex;align-items:center;gap:6px;white-space:nowrap;flex-shrink:0;font-weight:500;background:{{ pub.bg }};color:{{ pub.fg }};border:1px solid {{ pub.bd }};opacity:{{ pub.op }}"><span aria-hidden="true" style="display:inline-block;width:16px;height:16px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/{{ pub.icon }}.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/{{ pub.icon }}.svg') center / contain no-repeat"></span>{{ pub.t }}</span> <span data-act="publish" style="height:32px;padding:0 12px;display:flex;align-items:center;gap:6px;white-space:nowrap;flex-shrink:0;font-weight:500;background:{{ pub.bg }};color:{{ pub.fg }};border:1px solid {{ pub.bd }};opacity:{{ pub.op }}"><span aria-hidden="true" style="display:inline-block;width:16px;height:16px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/{{ pub.icon }}.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/{{ pub.icon }}.svg') center / contain no-repeat"></span>{{ pub.t }}</span>
<span data-act="overflow" style="width:32px;height:32px;flex-shrink:0;display:flex;align-items:center;justify-content:center;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/ellipsis.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/ellipsis.svg') center / contain no-repeat"></span></span> <span data-act="overflow" role="button" aria-label="Delete article" style="height:32px;padding:0 12px;display:flex;align-items:center;gap:6px;white-space:nowrap;flex-shrink:0;font-weight:500;border:1px solid var(--ui-error);color:var(--ui-error);cursor:pointer"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:16px;height:16px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/trash-2.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/trash-2.svg') center / contain no-repeat"></span>Delete</span>
</sc-if> </sc-if>
</sc-if> </sc-if>
</div> </div>
@@ -195,6 +197,82 @@
</div> </div>
</sc-if> </sc-if>
<sc-if value="{{ isUsers }}">
<div style="padding:{{ pad }};display:flex;flex-direction:column;gap:16px;flex:1;min-height:0">
<div style="display:flex;align-items:flex-end;gap:16px;flex-wrap:wrap"><div style="flex:1;min-width:200px;display:flex;flex-direction:column;gap:2px"><span style="font:600 20px/28px 'IBM Plex Sans',sans-serif;color:var(--ui-text-highlighted)">Users</span><span style="color:var(--ui-text-muted)">Everyone who can sign in and work on your articles.</span></div><sc-if value="{{ desk }}"><span data-act="invite" style="height:32px;padding:0 12px;display:flex;align-items:center;gap:6px;background:var(--ui-primary);color:var(--ui-bg);font-weight:500"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:16px;height:16px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/user-plus.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/user-plus.svg') center / contain no-repeat"></span>Invite user</span></sc-if></div>
<sc-if value="{{ usError }}"><div role="alert" style="display:flex;gap:10px;padding:12px 14px;background:var(--rc-error-soft);color:var(--ui-error)"><span style="display:flex;padding-top:2px"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:16px;height:16px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/circle-x.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/circle-x.svg') center / contain no-repeat"></span></span><div style="flex:1;display:flex;flex-direction:column;gap:8px"><div style="display:flex;flex-direction:column;gap:2px"><span style="font-weight:600">Couldn't load users</span><span style="color:var(--ui-text-toned)">Check your connection and try again.</span></div><span style="align-self:flex-start;height:{{ btnH }};padding:0 10px;display:flex;align-items:center;gap:6px;border:1px solid var(--ui-border-accented);background:var(--ui-bg);color:var(--ui-text-highlighted);font-weight:500;font-size:12px"><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/rotate-cw.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/rotate-cw.svg') center / contain no-repeat"></span>Try again</span></div></div></sc-if>
<sc-if value="{{ usTable }}">
<div style="background:var(--ui-bg);border:1px solid var(--ui-border)">
<div style="display:grid;grid-template-columns:minmax(0,1.3fr) minmax(0,1fr) 84px 120px 110px 150px;gap:12px;height:36px;align-items:center;padding:0 12px;background:var(--ui-bg-elevated);color:var(--ui-text-muted);font-weight:500"><span>Email</span><span>Display name</span><span>Role</span><span>Invite status</span><span style="display:flex;align-items:center;gap:4px;color:var(--ui-text-highlighted)">Created<span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:12px;height:12px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/arrow-down.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/arrow-down.svg') center / contain no-repeat"></span></span><span></span></div>
<sc-for list="{{ usRows }}" as="r" hint-placeholder-count="5">
<div style="display:grid;grid-template-columns:minmax(0,1.3fr) minmax(0,1fr) 84px 120px 110px 150px;gap:12px;height:48px;align-items:center;padding:0 12px;border-top:1px solid var(--ui-border);background:{{ r.bg }}">
<sc-if value="{{ r.skel }}"><span style="height:12px;width:60%;background:var(--ui-bg-accented)"></span><span style="height:12px;width:50%;background:var(--ui-bg-accented)"></span><span style="width:52px;height:20px;background:var(--ui-bg-accented)"></span><span style="width:76px;height:20px;background:var(--ui-bg-accented)"></span><span style="width:80px;height:12px;background:var(--ui-bg-accented)"></span></sc-if>
<sc-if value="{{ r.email }}"><span style="display:flex;align-items:center;gap:8px;min-width:0"><span style="overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-weight:500;color:{{ r.fg }}">{{ r.email }}</span><sc-if value="{{ r.you }}"><span style="flex-shrink:0;font:500 11px 'IBM Plex Mono',monospace;color:var(--ui-text-muted)">you</span></sc-if></span><span style="overflow:hidden;text-overflow:ellipsis;white-space:nowrap;color:{{ r.dfg }}">{{ r.dn }}</span><span><span style="height:20px;padding:0 7px;display:inline-flex;align-items:center;background:{{ r.rl.bg }};color:{{ r.rl.fg }};border:1px solid {{ r.rl.bd }};font:500 11px 'IBM Plex Mono',monospace">{{ r.rl.t }}</span></span><span><span style="height:22px;padding:0 7px;display:inline-flex;align-items:center;gap:4px;background:{{ r.b.bg }};color:{{ r.b.fg }};border:1px solid {{ r.b.bd }};font-size:12px;font-weight:500"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:12px;height:12px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/{{ r.b.icon }}.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/{{ r.b.icon }}.svg') center / contain no-repeat"></span>{{ r.b.t }}</span></span><span style="color:var(--ui-text-muted)">{{ r.c }}</span><span style="display:flex;justify-content:flex-end"><sc-if value="{{ r.act }}"><span data-act="{{ r.act.key }}" style="height:28px;padding:0 9px;white-space:nowrap;flex-shrink:0;display:inline-flex;align-items:center;gap:6px;border:1px solid var(--ui-border-accented);background:var(--ui-bg);color:{{ r.act.fg }};font-weight:500;font-size:12px;opacity:{{ r.act.op }}"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:13px;height:13px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/{{ r.act.icon }}.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/{{ r.act.icon }}.svg') center / contain no-repeat"></span>{{ r.act.t }}</span></sc-if></span></sc-if>
</div>
</sc-for>
</div>
</sc-if>
<sc-if value="{{ usCards }}">
<div style="background:var(--ui-bg);border:1px solid var(--ui-border);margin:0 -16px;border-left:0;border-right:0">
<sc-for list="{{ usRows }}" as="r" hint-placeholder-count="5">
<div style="display:flex;flex-direction:column;justify-content:center;gap:6px;padding:12px 16px;border-bottom:1px solid var(--ui-border);min-height:68px;background:{{ r.bg }}">
<sc-if value="{{ r.skel }}"><span style="width:55%;height:14px;background:var(--ui-bg-accented)"></span><span style="width:40%;height:12px;background:var(--ui-bg-accented)"></span></sc-if>
<sc-if value="{{ r.email }}"><span style="display:flex;align-items:center;gap:8px;min-width:0"><span style="overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-size:15px;line-height:21px;font-weight:500;color:{{ r.fg }}">{{ r.email }}</span><sc-if value="{{ r.you }}"><span style="flex-shrink:0;font:500 11px 'IBM Plex Mono',monospace;color:var(--ui-text-muted)">you</span></sc-if></span><sc-if value="{{ r.display2 }}"><span style="color:var(--ui-text-toned)">{{ r.dn }}</span></sc-if><div style="display:flex;align-items:center;gap:8px;font-size:12px;color:var(--ui-text-muted)"><span style="height:20px;padding:0 7px;display:inline-flex;align-items:center;background:{{ r.rl.bg }};color:{{ r.rl.fg }};border:1px solid {{ r.rl.bd }};font:500 11px 'IBM Plex Mono',monospace">{{ r.rl.t }}</span><span style="height:20px;padding:0 6px;display:inline-flex;align-items:center;gap:4px;background:{{ r.b.bg }};color:{{ r.b.fg }};border:1px solid {{ r.b.bd }};font-weight:500"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:12px;height:12px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/{{ r.b.icon }}.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/{{ r.b.icon }}.svg') center / contain no-repeat"></span>{{ r.b.t }}</span><span>Created {{ r.c }}</span></div><sc-if value="{{ r.act }}"><div style="display:flex;padding-top:4px"><span data-act="{{ r.act.key }}" style="height:44px;padding:0 14px;white-space:nowrap;flex-shrink:0;display:inline-flex;align-items:center;gap:8px;border:1px solid var(--ui-border-accented);background:var(--ui-bg);color:{{ r.act.fg }};font-weight:500;font-size:13px;opacity:{{ r.act.op }}"><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/{{ r.act.icon }}.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/{{ r.act.icon }}.svg') center / contain no-repeat"></span>{{ r.act.t }}</span></div></sc-if></sc-if>
</div>
</sc-for>
</div>
</sc-if>
<sc-if value="{{ usOnly }}"><span style="color:var(--ui-text-muted);text-wrap:pretty">Invite someone so they can sign in with their own account instead of sharing yours.</span></sc-if>
</div>
<sc-if value="{{ mob }}"><sc-if value="{{ listFab }}"><div data-act="invite" style="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)"><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/user-plus.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/user-plus.svg') center / contain no-repeat"></span>Invite user</div></sc-if></sc-if>
</sc-if>
<sc-if value="{{ isSettings }}">
<div style="padding:{{ pad }};display:flex;flex-direction:column;gap:20px;max-width:720px;overflow:hidden">
<div style="display:flex;flex-direction:column;gap:2px"><span style="font:600 20px/28px 'IBM Plex Sans',sans-serif;color:var(--ui-text-highlighted)">Settings</span><span style="color:var(--ui-text-muted)">Workspace information.</span></div>
<div style="background:var(--ui-bg);border:1px solid var(--ui-border);padding:{{ cardPad }};display:flex;align-items:center;justify-content:space-between;gap:16px"><span style="font:600 15px/24px 'IBM Plex Sans',sans-serif;color:var(--ui-text-highlighted)">Version</span><span style="font:400 14px/22px 'IBM Plex Mono',monospace;color:var(--ui-text-toned)">{{ s.upd.v }}</span></div>
<div role="region" aria-labelledby="updates-h" style="background:var(--ui-bg);border:1px solid var(--ui-border);padding:{{ cardPad }};display:flex;flex-direction:column;gap:16px">
<span id="updates-h" tabindex="-1" style="align-self:flex-start;font:600 15px/24px 'IBM Plex Sans',sans-serif;color:var(--ui-text-highlighted);outline:{{ s.upd.focus }};outline-offset:4px">Updates</span>
<div aria-live="polite" style="display:flex;gap:12px;padding:14px;background:{{ s.upd.bg }}"><span style="display:flex;padding-top:2px"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:18px;height:18px;background-color:{{ s.upd.fg }};-webkit-mask:url('https://api.iconify.design/lucide/{{ s.upd.icon }}.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/{{ s.upd.icon }}.svg') center / contain no-repeat"></span></span><div style="flex:1;min-width:0;display:flex;flex-direction:column;gap:4px"><span style="font:600 14px/22px 'IBM Plex Sans',sans-serif;color:var(--ui-text-highlighted)">{{ s.upd.title }}</span><span style="color:var(--ui-text-toned);text-wrap:pretty">{{ s.upd.text }}</span><sc-if value="{{ s.upd.bar }}"><div style="display:flex;flex-direction:column;gap:6px;padding-top:8px"><div role="progressbar" aria-label="{{ s.upd.barLabel }}" aria-valuemin="0" aria-valuemax="100" aria-valuenow="{{ s.upd.pct }}" style="height:6px;background:var(--ui-bg-accented)"><div style="height:6px;width:{{ s.upd.barW }};margin-left:{{ s.upd.barL }};background:var(--ui-primary)"></div></div><span style="font:400 12px/16px 'IBM Plex Mono',monospace;color:var(--ui-text-muted)">{{ s.upd.barText }}</span></div></sc-if><sc-if value="{{ s.upd.meta }}"><span style="font-size:12px;color:var(--ui-text-muted)">{{ s.upd.meta }}</span></sc-if></div></div>
<sc-if value="{{ s.upd.notes }}"><div style="display:flex;flex-direction:column;gap:10px"><span role="button" aria-expanded="{{ s.upd.notes.open }}" style="align-self:flex-start;display:flex;align-items:center;gap:6px;min-height:{{ btnH }};font-weight:500;color:var(--ui-text-highlighted)"><span aria-hidden="true" style="display:inline-block;width:14px;height:14px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/{{ s.upd.notes.chev }}.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/{{ s.upd.notes.chev }}.svg') center / contain no-repeat"></span>What's new in {{ s.upd.notes.ver }}</span><sc-if value="{{ s.upd.notes.open }}"><div style="display:flex;flex-direction:column;gap:8px;padding:0 0 0 20px"><span style="font-size:12px;color:var(--ui-text-muted)">{{ s.upd.notes.date }}</span><sc-for list="{{ s.upd.notes.items }}" as="it" hint-placeholder-count="3"><div style="display:flex;gap:8px"><span aria-hidden="true" style="flex-shrink:0;width:4px;height:4px;margin-top:8px;background:var(--ui-text-muted)"></span><span style="color:var(--ui-text-toned);text-wrap:pretty">{{ it.t }}</span></div></sc-for><span style="align-self:flex-start;color:var(--ui-text-highlighted);text-decoration:underline;text-underline-offset:3px;font-weight:500">Read the full release notes</span></div></sc-if></div></sc-if>
<sc-if value="{{ s.upd.cmd }}"><div style="display:flex;flex-direction:column;gap:8px"><span style="font-weight:500;color:var(--ui-text-highlighted)">For whoever manages the server</span><div style="display:flex;flex-direction:{{ upCmdDir }};align-items:{{ upBtnAlign }};gap:8px"><code style="flex:1;min-width:0;padding:8px 12px;background:var(--ui-bg-elevated);color:var(--ui-text-highlighted);overflow:hidden;text-overflow:ellipsis;white-space:nowrap;line-height:22px">{{ s.upd.cmd.line }}</code><span role="button" style="height:{{ btnH }};padding:0 12px;display:flex;align-items:center;justify-content:center;gap:6px;border:1px solid var(--ui-border-accented);background:var(--ui-bg);color:{{ s.upd.cmd.fg }};font-weight:500"><span aria-hidden="true" style="display:inline-block;width:16px;height:16px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/{{ s.upd.cmd.icon }}.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/{{ s.upd.cmd.icon }}.svg') center / contain no-repeat"></span>{{ s.upd.cmd.t }}</span></div><span style="font-size:12px;color:var(--ui-text-muted)">{{ s.upd.cmd.note }}</span></div></sc-if>
<sc-if value="{{ s.upd.btns }}"><div style="display:flex;flex-direction:{{ upBtnDir }};align-items:{{ upBtnAlign }};gap:8px"><sc-for list="{{ s.upd.btns }}" as="b" hint-placeholder-count="1"><span role="button" style="height:{{ btnH }};padding:0 14px;display:flex;align-items:center;justify-content:center;gap:6px;background:{{ b.bg }};color:{{ b.fg }};border:1px solid {{ b.bd }};opacity:{{ b.op }};font-weight:500"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:16px;height:16px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/{{ b.icon }}.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/{{ b.icon }}.svg') center / contain no-repeat"></span>{{ b.t }}</span></sc-for></div></sc-if>
<sc-if value="{{ s.upd.hint }}"><span style="font-size:12px;color:var(--ui-text-muted);text-wrap:pretty">{{ s.upd.hint }}</span></sc-if>
<sc-if value="{{ s.upd.link }}"><span style="align-self:flex-start;display:flex;align-items:center;gap:6px;color:var(--ui-text-highlighted);text-decoration:underline;text-underline-offset:3px;font-weight:500">{{ s.upd.link }}<span aria-hidden="true" style="display:inline-block;width:14px;height:14px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/external-link.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/external-link.svg') center / contain no-repeat"></span></span></sc-if>
</div>
</div>
</sc-if>
<sc-if value="{{ isProfile }}">
<div style="padding:{{ pad }};display:flex;flex-direction:column;gap:20px;max-width:720px;overflow:hidden">
<div style="display:flex;flex-direction:column;gap:2px"><span style="font:600 20px/28px 'IBM Plex Sans',sans-serif;color:var(--ui-text-highlighted)">Profile</span><span style="color:var(--ui-text-muted)">Your account on this RenewCMS workspace.</span></div>
<sc-if value="{{ pfLoading }}"><div aria-busy="true" style="display:flex;flex-direction:column;gap:16px"><div style="background:var(--ui-bg);border:1px solid var(--ui-border);padding:{{ cardPad }};display:flex;flex-direction:column;gap:12px"><span style="width:120px;height:14px;background:var(--ui-bg-accented)"></span><span style="height:40px;background:var(--ui-bg-accented)"></span></div><div style="background:var(--ui-bg);border:1px solid var(--ui-border);padding:{{ cardPad }};display:flex;flex-direction:column;gap:12px"><span style="width:90px;height:14px;background:var(--ui-bg-accented)"></span><span style="height:40px;background:var(--ui-bg-accented)"></span><span style="height:40px;background:var(--ui-bg-accented)"></span></div><div style="background:var(--ui-bg);border:1px solid var(--ui-border);padding:{{ cardPad }};display:flex;flex-direction:column;gap:12px"><span style="width:100px;height:14px;background:var(--ui-bg-accented)"></span><span style="height:40px;background:var(--ui-bg-accented)"></span></div></div></sc-if>
<sc-if value="{{ pfReady }}">
<div style="background:var(--ui-bg);border:1px solid var(--ui-border)">
<div style="padding:{{ cardPad }};display:flex;flex-direction:column;gap:14px">
<div style="display:flex;flex-direction:column;gap:2px"><span style="font-weight:600;font-size:14px;color:var(--ui-text-highlighted)">Display name</span><span style="color:var(--ui-text-muted);text-wrap:pretty">Shown instead of your username across the back-office and in the emails RenewCMS sends. Leave it empty to use your username.</span></div>
<sc-if value="{{ pf.notice }}"><div role="alert" style="display:flex;gap:8px;padding:10px 12px;background:var(--rc-error-soft);color:var(--ui-error)"><span style="display:flex;padding-top:2px"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:16px;height:16px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/circle-x.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/circle-x.svg') center / contain no-repeat"></span></span><span style="color:var(--ui-text-toned)">{{ pf.notice }}</span></div></sc-if>
<div style="display:flex;flex-direction:column;gap:6px">
<label style="font-weight:500;color:var(--ui-text-highlighted)">Display name <span style="font-weight:400;color:var(--ui-text-muted)">(optional)</span></label>
<div style="height:{{ inH }};padding:0 10px;display:flex;align-items:center;border:1px solid {{ dn.bd }};box-shadow:{{ dn.sh }};background:{{ dn.bg }};color:{{ dn.fg }};font-size:{{ inF }};overflow:hidden;white-space:nowrap"><span style="overflow:hidden;text-overflow:ellipsis">{{ dn.shown }}</span><sc-if value="{{ dn.caret }}"><span style="flex-shrink:0;display:inline-block;width:1px;height:18px;background:var(--ui-text-highlighted);margin-left:1px"></span></sc-if></div>
<div style="display:flex;gap:12px;align-items:flex-start"><span style="flex:1;display:flex;gap:6px;align-items:center;color:var(--ui-error);font-size:12px"><sc-if value="{{ dn.err }}"><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/circle-alert.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/circle-alert.svg') center / contain no-repeat"></span>{{ dn.err }}</sc-if></span><span style="font:400 12px 'IBM Plex Mono',monospace;color:{{ dn.countFg }}">{{ dn.count }}</span></div>
</div>
</div>
<div style="padding:12px {{ cardPadX }};border-top:1px solid var(--ui-border);background:var(--ui-bg-muted);display:flex;align-items:center;gap:12px"><span style="flex:1;min-width:0;color:{{ dn.footFg }};font-size:12px;line-height:18px">{{ dn.foot }}</span><span data-act="pf-save" style="height:{{ btnH }};padding:0 14px;display:flex;align-items:center;gap:6px;flex-shrink:0;background:var(--ui-primary);color:var(--ui-bg);font-weight:500;opacity:{{ dnSave.op }}"><sc-if value="{{ dnSave.loading }}"><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/loader-circle.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/loader-circle.svg') center / contain no-repeat"></span></sc-if>{{ dnSave.t }}</span></div>
</div>
<div style="background:var(--ui-bg);border:1px solid var(--ui-border);padding:{{ cardPad }};display:flex;flex-direction:column;gap:14px">
<div style="display:flex;flex-direction:column;gap:2px"><span style="font-weight:600;font-size:14px;color:var(--ui-text-highlighted)">Account</span><span style="color:var(--ui-text-muted);text-wrap:pretty">Set when your account was created. You log in with your username, even after adding a display name.</span></div>
<div style="display:grid;grid-template-columns:{{ pfCols }};gap:14px"><div style="display:flex;flex-direction:column;gap:6px;min-width:0"><span style="font-weight:500;color:var(--ui-text-highlighted)">Username</span><div aria-disabled="true" style="height:{{ inH }};padding:0 10px;display:flex;align-items:center;gap:8px;border:1px solid var(--ui-border);background:var(--ui-bg-elevated);color:var(--ui-text-toned);font-size:{{ inF }};cursor:not-allowed"><span style="flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap">marta</span><span style="display:flex;color:var(--ui-text-dimmed)"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:14px;height:14px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/lock.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/lock.svg') center / contain no-repeat"></span></span></div></div><div style="display:flex;flex-direction:column;gap:6px;min-width:0"><span style="font-weight:500;color:var(--ui-text-highlighted)">Email</span><div aria-disabled="true" style="height:{{ inH }};padding:0 10px;display:flex;align-items:center;gap:8px;border:1px solid var(--ui-border);background:var(--ui-bg-elevated);color:var(--ui-text-toned);font-size:{{ inF }};cursor:not-allowed"><span style="flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap">marta@renew.example</span><span style="display:flex;color:var(--ui-text-dimmed)"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:14px;height:14px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/lock.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/lock.svg') center / contain no-repeat"></span></span></div></div></div>
</div>
<div style="background:var(--ui-bg);border:1px solid var(--ui-border);padding:{{ cardPad }};display:flex;flex-direction:column;gap:14px">
<div style="display:flex;flex-direction:column;gap:2px"><span style="font-weight:600;font-size:14px;color:var(--ui-text-highlighted)">Password</span><span style="color:var(--ui-text-muted);text-wrap:pretty">To change it, we'll email a reset link to marta@renew.example. The link works once, within 1 hour.</span></div>
<div style="display:flex;flex-direction:{{ pwDir }};align-items:{{ pwAlign }};gap:12px"><div style="flex:1;min-width:0"><div style="display:flex;flex-direction:column;gap:6px;min-width:0"><span style="font-weight:500;color:var(--ui-text-highlighted)">Password</span><div aria-disabled="true" style="height:{{ inH }};padding:0 10px;display:flex;align-items:center;gap:8px;border:1px solid var(--ui-border);background:var(--ui-bg-elevated);color:var(--ui-text-toned);font-size:{{ inF }};cursor:not-allowed"><span style="flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;letter-spacing:0.12em">••••••••••••</span><span style="display:flex;color:var(--ui-text-dimmed)"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:14px;height:14px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/lock.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/lock.svg') center / contain no-repeat"></span></span></div></div></div><span data-act="pf-reset" style="height:{{ inH }};padding:0 14px;display:flex;align-items:center;justify-content:center;gap:6px;flex-shrink:0;border:1px solid var(--ui-border-accented);background:var(--ui-bg);color:var(--ui-text-highlighted);font-weight:500;white-space:nowrap;opacity:{{ rsBtn.op }}"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:16px;height:16px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/{{ rsBtn.icon }}.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/{{ rsBtn.icon }}.svg') center / contain no-repeat"></span>{{ rsBtn.t }}</span></div>
<sc-if value="{{ rsNote }}"><div role="status" style="display:flex;gap:10px;padding:12px 14px;background:{{ rsNote.bg }}"><span style="display:flex;padding-top:2px;color:{{ rsNote.fg }}"><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/{{ rsNote.icon }}.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/{{ rsNote.icon }}.svg') center / contain no-repeat"></span></span><div style="display:flex;flex-direction:column;gap:2px"><span style="font-weight:600;color:{{ rsNote.fg }}">{{ rsNote.title }}</span><span style="color:var(--ui-text-toned);text-wrap:pretty">{{ rsNote.text }}</span></div></div></sc-if>
</div>
</sc-if>
</div>
</sc-if>
<sc-if value="{{ isError }}"> <sc-if value="{{ isError }}">
<div style="padding:{{ errPad }};display:flex;flex-direction:column;gap:14px;max-width:560px"><span style="font:500 13px 'IBM Plex Mono',monospace;color:var(--ui-text-muted)">{{ s.err.code }}</span><span style="font:600 24px/32px 'IBM Plex Sans',sans-serif;color:var(--ui-text-highlighted)">{{ s.err.title }}</span><span style="color:var(--ui-text-toned);font-size:14px;line-height:22px;text-wrap:pretty">{{ s.err.text }}</span><div style="display:flex;gap:8px;flex-wrap:wrap"><span data-act="err-primary" style="height:{{ btnH }};padding:0 12px;display:flex;align-items:center;gap:6px;background:var(--ui-primary);color:var(--ui-bg);font-weight:500">{{ s.err.primary }}</span><sc-if value="{{ s.err.secondary }}"><span style="height:{{ btnH }};padding:0 12px;display:flex;align-items:center;border:1px solid var(--ui-border-accented);color:var(--ui-text-highlighted);font-weight:500">{{ s.err.secondary }}</span></sc-if></div></div> <div style="padding:{{ errPad }};display:flex;flex-direction:column;gap:14px;max-width:560px"><span style="font:500 13px 'IBM Plex Mono',monospace;color:var(--ui-text-muted)">{{ s.err.code }}</span><span style="font:600 24px/32px 'IBM Plex Sans',sans-serif;color:var(--ui-text-highlighted)">{{ s.err.title }}</span><span style="color:var(--ui-text-toned);font-size:14px;line-height:22px;text-wrap:pretty">{{ s.err.text }}</span><div style="display:flex;gap:8px;flex-wrap:wrap"><span data-act="err-primary" style="height:{{ btnH }};padding:0 12px;display:flex;align-items:center;gap:6px;background:var(--ui-primary);color:var(--ui-bg);font-weight:500">{{ s.err.primary }}</span><sc-if value="{{ s.err.secondary }}"><span style="height:{{ btnH }};padding:0 12px;display:flex;align-items:center;border:1px solid var(--ui-border-accented);color:var(--ui-text-highlighted);font-weight:500">{{ s.err.secondary }}</span></sc-if></div></div>
</sc-if> </sc-if>
@@ -202,6 +280,10 @@
</div> </div>
</div> </div>
<sc-if value="{{ mobMenu }}"><div style="position:absolute;inset:0;z-index:50;background:var(--rc-overlay);display:flex;align-items:flex-end"><div role="menu" aria-label="Account" style="width:100%;background:var(--ui-bg);box-shadow:var(--rc-shadow-modal);padding:8px 0 24px"><div style="margin:0 auto 8px;width:36px;height:4px;background:var(--ui-bg-accented)"></div><div style="padding:8px 16px 14px;display:flex;align-items:center;gap:12px;border-bottom:1px solid var(--ui-border);margin-bottom:4px"><span style="width:36px;height:36px;flex-shrink:0;background:#d4c5b0;color:#111;display:flex;align-items:center;justify-content:center;font:600 13px 'IBM Plex Sans',sans-serif">{{ ini }}</span><div style="display:flex;flex-direction:column;min-width:0"><span style="font-weight:600;font-size:15px;color:var(--ui-text-highlighted)">{{ who }}</span><span style="color:var(--ui-text-muted)">marta@renew.example</span></div></div><div data-act="nav-profile" role="menuitem" style="height:48px;padding:0 16px;display:flex;align-items:center;gap:12px;font-size:15px;background:{{ pfItemBg }};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/circle-user.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/circle-user.svg') center / contain no-repeat"></span>Profile</div><div style="height:1px;background:var(--ui-border);margin:4px 0"></div><sc-for list="{{ themeSeg }}" as="m" hint-placeholder-count="3"><div data-act="{{ m.act }}" role="menuitemradio" aria-checked="{{ m.on }}" style="height:48px;padding:0 16px;display:flex;align-items:center;justify-content:space-between;font-size:15px;color:var(--ui-text-highlighted)">{{ m.t }}<span aria-hidden="true" style="display:inline-block;width:18px;height:18px;background-color:currentColor;opacity:{{ m.op }};-webkit-mask:url('https://api.iconify.design/lucide/check.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/check.svg') center / contain no-repeat"></span></div></sc-for><div style="height:1px;background:var(--ui-border);margin:4px 0"></div><div data-act="logout" role="menuitem" style="height:48px;padding:0 16px;display:flex;align-items:center;gap:12px;font-size:15px;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/log-out.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/log-out.svg') center / contain no-repeat"></span>Log out</div></div></div></sc-if>
<sc-if value="{{ s.overlay }}"><div role="status" aria-live="polite" style="position:absolute;inset:0;z-index:70;background:var(--ui-bg-muted);display:flex;align-items:center;justify-content:center;padding:24px"><div style="width:100%;max-width:440px;display:flex;flex-direction:column;gap:16px;align-items:flex-start"><svg width="26" height="26" viewBox="0 0 16 16" shape-rendering="crispEdges" aria-hidden="true"><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><div style="display:flex;flex-direction:column;gap:6px"><span style="font:600 22px/30px 'IBM Plex Sans',sans-serif;color:var(--ui-text-highlighted)">{{ s.overlay.title }}</span><span style="font-size:14px;line-height:22px;color:var(--ui-text-toned);text-wrap:pretty">{{ s.overlay.text }}</span></div><div role="progressbar" aria-label="Restarting" style="width:100%;height:4px;background:var(--ui-bg-accented)"><div style="width:35%;height:4px;margin-left:{{ s.overlay.barL }};background:var(--ui-primary)"></div></div><span style="font-size:12px;color:var(--ui-text-muted)">{{ s.overlay.meta }}</span><sc-if value="{{ s.overlay.btn }}"><span role="button" style="height:{{ btnH }};padding:0 14px;display:flex;align-items:center;gap:6px;border:1px solid var(--ui-border-accented);background:var(--ui-bg);color:var(--ui-text-highlighted);font-weight:500">{{ s.overlay.btn }}</span></sc-if></div></div></sc-if>
<sc-if value="{{ s.modal }}"> <sc-if value="{{ s.modal }}">
<div style="position:absolute;inset:0;z-index:50;background:var(--rc-overlay);display:flex;align-items:{{ modalAlign }};justify-content:center;padding:{{ modalPad }}"> <div style="position:absolute;inset:0;z-index:50;background:var(--rc-overlay);display:flex;align-items:{{ modalAlign }};justify-content:center;padding:{{ modalPad }}">
<div role="dialog" aria-modal="true" style="width:{{ modalW }};background:var(--ui-bg);box-shadow:var(--rc-shadow-modal);display:flex;flex-direction:column"> <div role="dialog" aria-modal="true" style="width:{{ modalW }};background:var(--ui-bg);box-shadow:var(--rc-shadow-modal);display:flex;flex-direction:column">
@@ -214,6 +296,41 @@
<sc-if value="{{ s.modal.upload }}"> <sc-if value="{{ s.modal.upload }}">
<div data-act="upload-pick" style="height:180px;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:8px;padding:16px;text-align:center;border:{{ up.bd }};background:{{ up.bg }};color:{{ up.fg }}"><span aria-hidden="true" style="display:inline-block;width:24px;height:24px;background-color:{{ up.ic }};-webkit-mask:url('https://api.iconify.design/lucide/{{ up.icon }}.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/{{ up.icon }}.svg') center / contain no-repeat"></span><span style="font-weight:500;color:var(--ui-text-highlighted)">{{ up.title }}</span><sc-if value="{{ up.progress }}"><div style="width:80%;height:4px;background:var(--ui-bg-accented)"><div style="width:{{ up.progress }};height:4px;background:var(--ui-primary)"></div></div></sc-if><span style="color:var(--ui-text-toned);font-size:12px;max-width:300px">{{ up.text }}</span></div> <div data-act="upload-pick" style="height:180px;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:8px;padding:16px;text-align:center;border:{{ up.bd }};background:{{ up.bg }};color:{{ up.fg }}"><span aria-hidden="true" style="display:inline-block;width:24px;height:24px;background-color:{{ up.ic }};-webkit-mask:url('https://api.iconify.design/lucide/{{ up.icon }}.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/{{ up.icon }}.svg') center / contain no-repeat"></span><span style="font-weight:500;color:var(--ui-text-highlighted)">{{ up.title }}</span><sc-if value="{{ up.progress }}"><div style="width:80%;height:4px;background:var(--ui-bg-accented)"><div style="width:{{ up.progress }};height:4px;background:var(--ui-primary)"></div></div></sc-if><span style="color:var(--ui-text-toned);font-size:12px;max-width:300px">{{ up.text }}</span></div>
</sc-if> </sc-if>
<sc-if value="{{ s.modal.crop }}">
<div style="display:flex;flex-direction:column;gap:16px">
<div style="height:{{ cr.stageH }};padding:16px;background:var(--ui-bg-elevated);display:flex;align-items:center;justify-content:center">
<div role="img" aria-label="north-wall.jpg, 4032 × 3024 px" style="position:relative;height:100%;max-width:100%;aspect-ratio:4/3;overflow:hidden;background:#d8d0c3">
<div style="position:absolute;left:0;right:0;bottom:0;height:32%;background:#8f8373"></div>
<div style="position:absolute;left:56%;top:14%;width:22%;height:42%;background:#f1ece3;border:6px solid #c4b9a8"></div>
<div tabindex="0" aria-label="Crop area. Arrow keys move it, Shift and arrow keys resize it." style="position:absolute;left:{{ cr.l }};top:{{ cr.t }};width:{{ cr.w }};height:{{ cr.h }};box-shadow:0 0 0 2000px rgb(10 10 10 / 0.55);outline:1px solid #ffffff;cursor:move">
<div style="position:absolute;left:33.333%;top:0;bottom:0;width:1px;background:rgb(255 255 255 / 0.45)"></div>
<div style="position:absolute;left:66.666%;top:0;bottom:0;width:1px;background:rgb(255 255 255 / 0.45)"></div>
<div style="position:absolute;top:33.333%;left:0;right:0;height:1px;background:rgb(255 255 255 / 0.45)"></div>
<div style="position:absolute;top:66.666%;left:0;right:0;height:1px;background:rgb(255 255 255 / 0.45)"></div>
<div style="position:absolute;left:-6px;top:-6px;width:12px;height:12px;background:#ffffff;border:1px solid #111111"></div>
<div style="position:absolute;right:-6px;top:-6px;width:12px;height:12px;background:#ffffff;border:1px solid #111111"></div>
<div style="position:absolute;left:-6px;bottom:-6px;width:12px;height:12px;background:#ffffff;border:1px solid #111111"></div>
<div style="position:absolute;right:-6px;bottom:-6px;width:12px;height:12px;background:#ffffff;border:1px solid #111111"></div>
<span style="position:absolute;left:8px;bottom:8px;padding:1px 6px;background:rgb(17 17 17 / 0.8);color:#ffffff;font:400 11px/18px 'IBM Plex Mono',monospace;white-space:nowrap">{{ cr.dims }}</span>
</div>
</div>
</div>
<div style="display:flex;flex-direction:column;gap:6px">
<div style="display:flex;align-items:center;gap:4px"><span style="flex:1;font-weight:500;color:var(--ui-text-highlighted)">Aspect ratio</span><span data-act="crop-rotate" style="height:{{ btnH }};padding:0 8px;display:flex;align-items:center;gap:6px;color:var(--ui-text-toned);font-weight:500"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:16px;height:16px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/rotate-ccw-square.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/rotate-ccw-square.svg') center / contain no-repeat"></span>Rotate</span><span data-act="crop-reset" style="height:{{ btnH }};padding:0 8px;display:flex;align-items:center;gap:6px;color:var(--ui-text-toned);font-weight:500"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:16px;height:16px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/undo-2.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/undo-2.svg') center / contain no-repeat"></span>Reset</span></div>
<div role="radiogroup" aria-label="Aspect ratio" style="display:flex;border:1px solid var(--ui-border-accented);width:{{ cr.groupW }}">
<sc-for list="{{ cr.ratios }}" as="p" hint-placeholder-count="5"><span role="radio" aria-checked="{{ p.on }}" data-act="{{ p.act }}" style="flex:{{ cr.pillFlex }};height:{{ btnH }};padding:0 12px;display:flex;align-items:center;justify-content:center;font-weight:500;white-space:nowrap;background:{{ p.bg }};color:{{ p.fg }}">{{ p.t }}</span></sc-for>
</div>
</div>
<div style="display:flex;flex-direction:column;gap:6px">
<span style="font-weight:500;color:var(--ui-text-highlighted)">Width</span>
<div role="radiogroup" aria-label="Width" style="display:flex;border:1px solid var(--ui-border-accented);width:{{ cr.groupW }}">
<sc-for list="{{ cr.sizes }}" as="p" hint-placeholder-count="4"><span role="radio" aria-checked="{{ p.on }}" data-act="{{ p.act }}" style="flex:{{ cr.pillFlex }};height:{{ btnH }};padding:0 12px;display:flex;align-items:center;justify-content:center;font-weight:500;white-space:nowrap;background:{{ p.bg }};color:{{ p.fg }}">{{ p.t }}</span></sc-for>
</div>
<span style="font:400 12px/18px 'IBM Plex Mono',monospace;color:var(--ui-text-muted)">{{ cr.out }}</span>
</div>
<sc-if value="{{ cr.note }}"><div role="status" style="display:flex;gap:8px;padding:10px 12px;background:var(--rc-info-soft)"><span style="display:flex;padding-top:2px;color:var(--ui-info)"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:16px;height:16px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/info.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/info.svg') center / contain no-repeat"></span></span><span style="color:var(--ui-text-toned);text-wrap:pretty">{{ cr.note }}</span></div></sc-if>
</div>
</sc-if>
</div> </div>
<div style="padding:20px 24px;display:flex;flex-direction:{{ mBtnDir }};justify-content:flex-end;gap:8px"> <div style="padding:20px 24px;display:flex;flex-direction:{{ mBtnDir }};justify-content:flex-end;gap:8px">
<sc-if value="{{ s.modal.cancel }}"><span data-act="modal-cancel" style="height:{{ btnH }};padding:0 12px;display:flex;align-items:center;justify-content:center;border:1px solid var(--ui-border-accented);color:{{ mCancelFg }};font-weight:500">{{ s.modal.cancel }}</span></sc-if> <sc-if value="{{ s.modal.cancel }}"><span data-act="modal-cancel" style="height:{{ btnH }};padding:0 12px;display:flex;align-items:center;justify-content:center;border:1px solid var(--ui-border-accented);color:{{ mCancelFg }};font-weight:500">{{ s.modal.cancel }}</span></sc-if>
@@ -238,8 +355,8 @@ 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 = [['home', 'house', 'Home'], ['articles', 'file-text', 'Articles'], ['integration', 'plug', 'Integration']] const navItems = [['home', 'house', 'Home'], ['articles', 'file-text', 'Articles'], ['media', 'images', 'Media'], ['users', 'users', 'Users'], ['integration', 'plug', 'Integration'], ['settings', 'settings', 'Settings']]
const nav = navItems.map(([key, icon, t]) => ({ key, icon, t, bg: s.nav === key ? 'var(--rc-sand)' : 'transparent', fg: s.nav === key ? '#111111' : 'var(--ui-text-toned)', fw: s.nav === key ? 500 : 400 })) const nav = navItems.map(([key, icon, t]) => ({ key, icon, t, bg: s.nav === key ? 'var(--rc-sand)' : 'transparent', badge: key === 'settings' && !!s.navBadge, fg: s.nav === key ? '#111111' : 'var(--ui-text-toned)', fw: s.nav === key ? 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]
@@ -264,12 +381,48 @@ class Component extends DCLogic {
const mFields = (md.fields || []).map(f => { const has = f.value; return { ...f, shown: has || f.ph || '', fg: md.loading ? 'var(--ui-text-dimmed)' : has ? 'var(--ui-text-highlighted)' : 'var(--ui-text-muted)', bd: f.err ? 'var(--ui-error)' : f.focus ? 'var(--ui-primary)' : 'var(--ui-border-accented)', sh: f.err ? 'inset 0 0 0 1px var(--ui-error)' : f.focus ? 'inset 0 0 0 1px var(--ui-primary)' : 'none', bg: md.loading ? 'var(--ui-bg-elevated)' : 'var(--ui-bg)', h: f.area ? (m ? '120px' : '96px') : (m ? '44px' : '40px'), p: f.area ? '8px 10px' : '0 10px', ai: f.area ? 'flex-start' : 'center', countFg: f.countErr ? 'var(--ui-error)' : 'var(--ui-text-muted)' } }) const mFields = (md.fields || []).map(f => { const has = f.value; return { ...f, shown: has || f.ph || '', fg: md.loading ? 'var(--ui-text-dimmed)' : has ? 'var(--ui-text-highlighted)' : 'var(--ui-text-muted)', bd: f.err ? 'var(--ui-error)' : f.focus ? 'var(--ui-primary)' : 'var(--ui-border-accented)', sh: f.err ? 'inset 0 0 0 1px var(--ui-error)' : f.focus ? 'inset 0 0 0 1px var(--ui-primary)' : 'none', bg: md.loading ? 'var(--ui-bg-elevated)' : 'var(--ui-bg)', h: f.area ? (m ? '120px' : '96px') : (m ? '44px' : '40px'), p: f.area ? '8px 10px' : '0 10px', ai: f.area ? 'flex-start' : 'center', countFg: f.countErr ? 'var(--ui-error)' : 'var(--ui-text-muted)' } })
const U = md.upload || {} const U = md.upload || {}
const upMap = { const upMap = {
uploading: { icon: 'image-plus', ic: 'var(--ui-text-toned)', title: 'north-wall.jpg', text: 'Uploading 2.4 of 3.9 MB', progress: '62%', bd: '1px solid var(--ui-border)', bg: 'var(--ui-bg)' }, uploading: { icon: 'image-plus', ic: 'var(--ui-text-toned)', title: 'north-wall.jpg', text: 'Uploading 180 of 420 KB', progress: '43%', bd: '1px solid var(--ui-border)', bg: 'var(--ui-bg)' },
rejected: { icon: 'file-x', ic: 'var(--ui-error)', title: 'north-wall.tif is 14.2 MB', text: 'Images can be up to 10 MB. Use a PNG, JPEG, WEBP or SVG image.', bd: '1px solid var(--ui-error)', bg: 'var(--ui-bg)' }, rejected: { icon: 'file-x', ic: 'var(--ui-error)', title: 'north-wall.tif is 14.2 MB', text: 'Images can be up to 10 MB. Use a PNG, JPEG, WEBP or SVG image.', bd: '1px solid var(--ui-error)', bg: 'var(--ui-bg)' },
idle: { icon: 'image-plus', ic: 'var(--ui-text-toned)', title: 'Drop an image here, or choose a file', text: 'PNG, JPEG, WEBP, SVG · max 10 MB', bd: '1px dashed var(--ui-border-accented)', bg: 'var(--ui-bg)' }, idle: { icon: 'image-plus', ic: 'var(--ui-text-toned)', title: 'Drop an image here, or choose a file', text: 'PNG, JPEG, WEBP, SVG · max 10 MB', bd: '1px dashed var(--ui-border-accented)', bg: 'var(--ui-bg)' },
error: { icon: 'circle-x', ic: 'var(--ui-error)', title: 'Upload failed', text: 'The server didn\'t accept the file. Your article hasn\'t changed.', bd: '1px solid var(--ui-error)', bg: 'var(--ui-bg)' } error: { icon: 'circle-x', ic: 'var(--ui-error)', title: 'Upload failed', text: 'The server didn\'t accept the file. Your article hasn\'t changed.', bd: '1px solid var(--ui-error)', bg: 'var(--ui-bg)' }
} }
const up = upMap[U.state || 'idle'] || upMap.idle const up = upMap[U.state || 'idle'] || upMap.idle
let cr = {}
if (md.crop) {
const C = md.crop, IW = 4032, IH = 3024
const ri = C.ratio || 0, si = C.size ?? 1
const presets = [[0, 0, 100, 100], [6, 8, 88, 78], [0, 12.5, 100, 75], [0, 0, 100, 100], [12.5, 0, 75, 100]]
const r = C.rect || presets[ri]
const cw = Math.round(IW * r[2] / 100), ch = Math.round(IH * r[3] / 100)
const target = [cw, 1600, 1200, 800][si]
const ow = Math.min(target, cw), oh = Math.round(ch * ow / cw)
const kb = Math.round(ow * oh * 0.22 / 1000)
const pill = (pre, cur) => (t, i) => ({ t, on: i === cur, act: pre + i, bg: i === cur ? 'var(--ui-primary)' : 'transparent', fg: i === cur ? 'var(--ui-bg)' : 'var(--ui-text-toned)' })
cr = {
l: r[0] + '%', t: r[1] + '%', w: r[2] + '%', h: r[3] + '%', dims: fmt(cw) + ' × ' + fmt(ch),
ratios: ['Original', 'Free', '16:9', '4:3', '1:1'].map(pill('crop-r-', ri)),
sizes: ['Original', '1600 px', '1200 px', '800 px'].map(pill('crop-s-', si)),
out: 'Uploads as ' + fmt(ow) + ' × ' + fmt(oh) + ' px · about ' + (kb >= 1000 ? (kb / 1000).toFixed(1) + ' MB' : kb + ' KB'),
note: target > cw ? 'The crop is ' + cw + ' px wide, so it\'s uploaded at that size. Enlarging it would make it blurry.' : '',
stageH: m ? '240px' : '340px', pillFlex: m ? '1 1 0' : '0 0 auto', groupW: m ? '100%' : 'max-content'
}
}
const US = s.users || {}
const badges = { accepted: { t: 'Accepted', icon: 'circle-check', bg: 'var(--rc-success-soft)', fg: 'var(--ui-success)', bd: 'var(--rc-success-soft)' }, pending: { t: 'Pending', icon: 'mail', bg: 'var(--rc-warning-soft)', fg: 'var(--ui-warning)', bd: 'var(--rc-warning-soft)' }, expired: { t: 'Expired', icon: 'clock-alert', bg: 'transparent', fg: 'var(--ui-text-muted)', bd: 'var(--ui-border-accented)' } }
const roles = { owner: { t: 'owner', bg: 'var(--ui-primary)', fg: 'var(--ui-bg)', bd: 'var(--ui-primary)' }, admin: { t: 'admin', bg: 'transparent', fg: 'var(--ui-text-toned)', bd: 'var(--ui-border-accented)' } }
const acts = { pending: { key: 'cancel-invite', t: 'Cancel invite', icon: 'user-x', fg: 'var(--ui-error)', op: '1' }, expired: { key: 'renew-invite', t: 'Renew invite', icon: 'refresh-cw', fg: 'var(--ui-text-highlighted)', op: '1' } }
const usRows = (US.loading ? Array.from({ length: 5 }, () => ({ skel: true })) : (US.rows || [])).map(r => { if (r.skel) return r; const dn = (r.you && s.display) || r.display || ''; const a0 = acts[r.st]; return { ...r, dn: dn || '—', dfg: dn ? 'var(--ui-text-highlighted)' : 'var(--ui-text-muted)', display2: !!dn, fg: 'var(--ui-text-highlighted)', rl: roles[r.role] || roles.admin, b: badges[r.st] || badges.pending, bg: r.hl ? 'var(--ui-bg-elevated)' : 'transparent', act: a0 && (r.busy ? { ...a0, t: r.busy, icon: 'loader-circle', op: '0.5' } : a0) } })
const who = s.display || 'marta'
const ini = s.display ? s.display.trim().split(/\s+/).slice(0, 2).map(w => w[0]).join('').toUpperCase() : 'MA'
const pf = s.pf || {}
const dnVal = pf.value ?? s.display ?? ''
const dnLen = [...dnVal].length
const dn = { shown: dnVal || (pf.focus ? '' : 'e.g. Marta Alves'), caret: !!pf.focus, fg: pf.saving ? 'var(--ui-text-dimmed)' : dnVal ? 'var(--ui-text-highlighted)' : 'var(--ui-text-muted)', bd: pf.err ? 'var(--ui-error)' : pf.focus ? 'var(--ui-primary)' : 'var(--ui-border-accented)', sh: pf.err ? 'inset 0 0 0 1px var(--ui-error)' : pf.focus ? 'inset 0 0 0 1px var(--ui-primary)' : 'none', bg: pf.saving ? 'var(--ui-bg-elevated)' : 'var(--ui-bg)', count: dnLen + ' / 60', countFg: dnLen > 60 ? 'var(--ui-error)' : 'var(--ui-text-muted)', err: pf.err || '', foot: pf.dirty && !pf.saving ? 'Unsaved changes' : 'You appear as \u201c' + who + '\u201d' + (s.display ? '.' : ', your username.'), footFg: pf.dirty && !pf.saving ? 'var(--ui-warning)' : 'var(--ui-text-muted)' }
const dnSave = { t: pf.saving ? 'Saving…' : 'Save', loading: !!pf.saving, op: pf.saving || (pf.dirty && !pf.err) ? '1' : '0.4' }
const rs = pf.reset || 'idle'
const rsMap = { sent: { bg: 'var(--rc-success-soft)', fg: 'var(--ui-success)', icon: 'mail-check', title: 'Reset link sent', text: 'Check marta@renew.example. The link works once, within 1 hour.' }, limited: { bg: 'var(--rc-warning-soft)', fg: 'var(--ui-warning)', icon: 'clock-alert', title: 'Too many requests', text: 'You\'ve asked for several links recently. Wait a few minutes, then try again.' }, error: { bg: 'var(--rc-error-soft)', fg: 'var(--ui-error)', icon: 'circle-x', title: 'Couldn\'t send the link', text: 'Check your connection and try again.' } }
const rsNote = rsMap[rs] || null
const rsBtn = { t: rs === 'sending' ? 'Sending…' : rs === 'sent' ? 'Send again' : 'Send reset link', icon: rs === 'sending' ? 'loader-circle' : 'mail', op: rs === 'limited' ? '0.4' : '1' }
const toasts = (s.toasts || []).map(t => ({ ...t, fg: 'var(--ui-' + t.tone + ')' })) const toasts = (s.toasts || []).map(t => ({ ...t, fg: 'var(--ui-' + t.tone + ')' }))
const endpoints = [ const endpoints = [
{ path: '/v1/article/', desc: 'Lists every online article.', l1: 'var(--ui-primary)', code: "const res = await fetch('https://cms.renew.example/v1/article/')\nconst articles = await res.json()" }, { path: '/v1/article/', desc: 'Lists every online article.', l1: 'var(--ui-primary)', code: "const res = await fetch('https://cms.renew.example/v1/article/')\nconst articles = await res.json()" },
@@ -281,13 +434,18 @@ class Component extends DCLogic {
const edReady = k === 'editor' && !e.loading && !e.notfound const edReady = k === 'editor' && !e.loading && !e.notfound
const edTitle = e.title || 'How we price a bathroom renovation' const edTitle = e.title || 'How we price a bathroom renovation'
return { return {
s, nav, crumbs, edTitle, edBody: e.body || '', sampleBody: !e.body, tabs, rows, save, counter, pub, mFields, up, toasts, endpoints, toolbar, cr, s, nav, crumbs, who, ini, pf, dn, dnSave, rsNote, rsBtn,
themeSeg: [['system','monitor','System'],['light','sun','Light'],['dark','moon','Dark']].map(([k,icon,tt])=>{const on=(s.mode||'light')===k;return {act:'theme-'+k,icon,t:tt,on,op:on?1:0}}), menuOpen: !!s.userMenu, deskMenu: !m && !!s.userMenu, mobMenu: m && !!s.userMenu, pfItemBg: 'var(--ui-bg-elevated)',
chipBg: s.userMenu || s.nav === 'profile' ? 'var(--rc-sand)' : 'transparent', chipFg: s.userMenu || s.nav === 'profile' ? '#111111' : 'var(--ui-text-highlighted)',
isSettings: k === 'settings', isProfile: k === 'profile', pfLoading: k === 'profile' && !!pf.loading, pfReady: k === 'profile' && !pf.loading,
upBtnDir: m ? 'column' : 'row', upBtnAlign: m ? 'stretch' : 'flex-start', cardPad: m ? '16px' : '20px', 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, 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',
isBoot: !!s.boot, isHome: k === 'home' && !s.boot, isList: k === 'articles', isEditor: k === 'editor', isInteg: k === 'integration', isError: k === 'error', isBoot: !!s.boot, isHome: k === 'home' && !s.boot, isList: k === 'articles', isEditor: k === 'editor', isInteg: k === 'integration', isError: k === 'error', isUsers: k === 'users',
usRows, usError: !!US.error, usOnly: !!US.only && !US.error, usTable: !m && !US.error, usCards: m && !US.error,
pad: m ? '20px 16px 88px' : '32px', gap: m ? '20px' : '28px', cols3: m ? 'repeat(3,minmax(0,1fr))' : 'repeat(3,minmax(0,1fr))', pad: m ? '20px 16px 88px' : '32px', gap: m ? '20px' : '28px', cols3: m ? 'repeat(3,minmax(0,1fr))' : 'repeat(3,minmax(0,1fr))',
btnH: m ? '44px' : '32px', rowH: m ? '52px' : '44px', inF: m ? '16px' : '14px', upBannerAlign: m ? 'stretch' : 'center', upCmdDir: m ? 'column' : 'row', btnH: m ? '44px' : '32px', rowH: m ? '52px' : '44px', inF: m ? '16px' : '14px',
tbDir: m ? 'column' : 'row', tbGap: m ? '12px' : '16px', tbBorder: m ? '0' : '1px solid var(--ui-border)', tabBorder: m ? '1px solid var(--ui-border)' : '0', tabH: m ? '44px' : '36px', tabF: m ? '14px' : '13px', tbDir: m ? 'column' : 'row', tbGap: m ? '12px' : '16px', tbBorder: m ? '0' : '1px solid var(--ui-border)', tabBorder: m ? '1px solid var(--ui-border)' : '0', tabH: m ? '44px' : '36px', tabF: m ? '14px' : '13px',
qText: L.q ? L.q : 'Search by title', qFg: L.q ? 'var(--ui-text-highlighted)' : 'var(--ui-text-muted)', qText: L.q ? L.q : 'Search by title', qFg: L.q ? 'var(--ui-text-highlighted)' : 'var(--ui-text-muted)',
showTable: !m && !L.empty, showCards: m && !L.empty, listFab: !s.modal, showTable: !m && !L.empty, showCards: m && !L.empty, listFab: !s.modal,
@@ -302,7 +460,7 @@ class Component extends DCLogic {
saveOp: (dirty && !blocked) ? '1' : '0.4', imgCount: e.imgs != null ? String(e.imgs) : (e.image ? '4' : '3'), apiNote: online ? 'Live. Your website can read this article.' : 'Returns 404 until the article is online.', saveOp: (dirty && !blocked) ? '1' : '0.4', imgCount: e.imgs != null ? String(e.imgs) : (e.image ? '4' : '3'), apiNote: online ? 'Live. Your website can read this article.' : 'Returns 404 until the article is online.',
copyIcon: s.copied ? 'check' : 'copy', copyText: s.copied ? 'Copied' : 'Copy', copyFg: s.copied ? 'var(--ui-success)' : 'var(--ui-text-highlighted)', copyIcon: s.copied ? 'check' : 'copy', copyText: s.copied ? 'Copied' : 'Copy', copyFg: s.copied ? 'var(--ui-success)' : 'var(--ui-text-highlighted)',
errPad: m ? '40px 20px' : '64px 48px', errPad: m ? '40px 20px' : '64px 48px',
modalAlign: m ? 'flex-end' : 'flex-start', modalPad: m ? '16px' : '140px 16px 16px', modalW: m ? '100%' : (md.wide ? '560px' : '460px'), mBtnDir: m ? 'column-reverse' : 'row', modalAlign: m ? 'flex-end' : 'flex-start', modalPad: m ? '16px' : (md.crop ? '56px 16px 16px' : '140px 16px 16px'), modalW: m ? '100%' : (md.crop ? '640px' : md.wide ? '560px' : '460px'), mBtnDir: m ? 'column-reverse' : 'row',
mConfirmBg: md.tone === 'danger' ? 'var(--ui-error)' : 'var(--ui-primary)', mCancelFg: md.loading ? 'var(--ui-text-dimmed)' : 'var(--ui-text-highlighted)', mConfirmBg: md.tone === 'danger' ? 'var(--ui-error)' : 'var(--ui-primary)', mCancelFg: md.loading ? 'var(--ui-text-dimmed)' : 'var(--ui-text-highlighted)',
hasToasts: toasts.length > 0, tL: m ? '16px' : 'auto', tR: m ? '16px' : '24px', tB: m ? '16px' : '24px', tW: m ? 'auto' : '356px' hasToasts: toasts.length > 0, tL: m ? '16px' : 'auto', tR: m ? '16px' : '24px', tB: m ? '16px' : '24px', tW: m ? 'auto' : '356px'
} }
+276
View File
@@ -0,0 +1,276 @@
<!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>
<div style="display:contents">{{ view }}</div>
</x-dc>
<script type="text/x-dc" data-dc-script data-props="{&quot;$preview&quot;:{&quot;width&quot;:1440,&quot;height&quot;:900},&quot;s&quot;:{&quot;editor&quot;:null,&quot;tsType&quot;:&quot;object&quot;},&quot;mobile&quot;:{&quot;editor&quot;:null,&quot;tsType&quot;:&quot;boolean&quot;}}">
class Component extends DCLogic {
renderVals() {
const s = this.props.s || {}, m = !!this.props.mobile, h = React.createElement
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 D = (t, ...c) => h('div', { style: P(t) }, ...c)
const S = (t, ...c) => h('span', { style: P(t) }, ...c)
const I = (n, z = 16, t = '') => h('span', { 'aria-hidden': 'true', style: { display: 'inline-block', flexShrink: 0, width: z, height: z, backgroundColor: 'currentColor', WebkitMask: 'url(https://api.iconify.design/lucide/' + n + '.svg) center / contain no-repeat', mask: 'url(https://api.iconify.design/lucide/' + n + '.svg) center / contain no-repeat', ...(t ? P(t) : {}) } })
const bh = m ? 44 : 32
const B = (label, o = {}) => {
const k = o.k || 'outline'
const bg = k === 'primary' ? 'var(--ui-primary)' : k === 'danger' ? 'var(--ui-error)' : k === 'inv' ? 'transparent' : 'var(--ui-bg)'
const fg = k === 'primary' || k === 'danger' ? 'var(--ui-bg)' : k === 'del' ? 'var(--ui-error)' : k === 'inv' ? 'var(--ui-text-inverted)' : 'var(--ui-text-highlighted)'
const bd = k === 'primary' || k === 'danger' ? bg : k === 'inv' ? 'var(--ui-text-inverted)' : 'var(--ui-border-accented)'
return S('height:' + (o.h || bh) + 'px;padding:0 ' + (o.px || 12) + 'px;display:flex;align-items:center;justify-content:center;gap:6px;background:' + bg + ';color:' + fg + ';border:1px solid ' + bd + ';font-weight:500;font-size:' + (o.fs || 13) + 'px;white-space:nowrap;opacity:' + (o.dis ? 0.4 : 1) + ';' + (o.full ? 'flex:1;' : '') + (o.ring ? 'outline:2px solid var(--ui-primary);outline-offset:2px;' : ''), o.icon && I(o.icon, o.z || 16), label)
}
const CHECK = 'conic-gradient(var(--ui-bg-accented) 25%, var(--ui-bg) 0 50%, var(--ui-bg-accented) 0 75%, var(--ui-bg) 0) 0 0/16px 16px'
const TONES = ['var(--rc-sand)', 'var(--ui-bg-accented)', 'color-mix(in srgb, var(--ui-border-accented) 35%, var(--ui-bg))', 'var(--ui-bg-elevated)']
const mark = h('svg', { width: 28, height: 28, viewBox: '0 0 16 16', shapeRendering: 'crispEdges' }, h('rect', { width: 16, height: 16, fill: '#111' }), h('path', { fill: '#fff', fillRule: 'evenodd', d: 'M4 3h6v1h1v1h1v3h-1v1h-1v1h1v1h1v2h-2v-2h-1v-1H6v3H4zm2 2v3h4V5z' }))
const Th = (im, t = '', z = 24) => D('position:relative;overflow:hidden;display:flex;align-items:center;justify-content:center;color:var(--ui-text-muted);background:' + (im.alpha ? CHECK : 'repeating-linear-gradient(135deg, rgb(128 128 128 / 0.12) 0 1px, transparent 1px 12px), ' + TONES[im.tone % 4]) + ';' + t, im.svg ? mark : I('image', z, 'opacity:0.55'))
const BADGE = { unused: ['background:var(--rc-warning-soft);color:var(--ui-warning)', 'unlink'], dup: ['background:var(--rc-info-soft);color:var(--ui-info)', 'copy'], used: ['border:1px solid var(--ui-border-accented);color:var(--ui-text-toned)'], on: ['background:var(--ui-bg-inverted);color:var(--ui-text-inverted)', 'globe'], draft: ['border:1px solid var(--ui-border-accented);color:var(--ui-text-toned)', 'pencil-line'] }
const Bd = (t, k, sz = 20) => S('height:' + sz + 'px;padding:0 6px;display:inline-flex;align-items:center;gap:4px;font-size:12px;font-weight:500;white-space:nowrap;' + BADGE[k][0], BADGE[k][1] && I(BADGE[k][1], 12), t)
const Cb = (on, z = 20, ind) => S('width:' + z + 'px;height:' + z + 'px;flex-shrink:0;display:flex;align-items:center;justify-content:center;border:1px solid ' + (on || ind ? 'var(--ui-primary)' : 'var(--ui-border-accented)') + ';background:' + (on || ind ? 'var(--ui-primary)' : 'var(--ui-bg)') + ';color:var(--ui-bg)', (on || ind) && I(ind ? 'minus' : 'check', z - 6))
const Alert = (tone, icon, title, text, action, actionEl) => 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), S('color:var(--ui-text-toned)', text)), action && B(action, { icon: 'rotate-cw', h: m ? 44 : 28, fs: 12, z: 14, ...(actionEl || {}) })))
const Empty = (icon, title, text, action, primary, pad = 56) => D('background:var(--ui-bg);border:1px solid var(--ui-border);padding:' + pad + 'px 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:320px', text), action && B(action, { k: primary ? 'primary' : 'outline', icon: primary ? 'upload' : null, px: 16 }))
const Note = t => 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);font:500 11px \'IBM Plex Mono\',monospace', t)
const IM = [
{ id: 1, n: 'north-wall.jpg', sz: '3.9 MB', dim: '4032 × 3024', ty: 'JPEG', used: 2, by: 'Marta Alves', d: '12 Sep 2026', tone: 0 },
{ id: 2, n: 'kitchen-after.webp', sz: '1.2 MB', dim: '2400 × 1600', ty: 'WEBP', used: 3, by: 'Inès Duarte', d: '8 Sep 2026', tone: 1 },
{ id: 3, n: 'kitchen-before.webp', sz: '1.1 MB', dim: '2400 × 1600', ty: 'WEBP', used: 1, by: 'Inès Duarte', d: '8 Sep 2026', tone: 2 },
{ id: 4, n: 'logo-renew.svg', sz: '8 KB', dim: 'Vector', ty: 'SVG', used: 5, by: 'jonas', d: '5 Sep 2026', alpha: true, svg: true, tone: 3 },
{ id: 5, n: 'floorboards-copy.jpg', sz: '2.4 MB', dim: '3600 × 2400', ty: 'JPEG', used: 3, by: 'Marta Alves', d: '2 Sep 2026', dup: true, tone: 0 },
{ id: 6, n: 'IMG_2208.jpg', sz: '2.4 MB', dim: '3600 × 2400', ty: 'JPEG', used: 2, by: 'jonas', d: '30 Aug 2026', dup: true, tone: 0 },
{ id: 7, n: 'IMG_4471.jpg', sz: '3.1 MB', dim: '3600 × 2400', ty: 'JPEG', used: 2, by: 'Marta Alves', d: '29 Aug 2026', dup: true, tone: 2 },
{ id: 8, n: 'window-frame.jpg', sz: '1.8 MB', dim: '3000 × 2000', ty: 'JPEG', used: 0, by: 'Inès Duarte', d: '28 Aug 2026', tone: 3 },
{ id: 9, n: 'stone-wall-detail.jpg', sz: '3.1 MB', dim: '3600 × 2400', ty: 'JPEG', used: 1, by: 'jonas', d: '21 Aug 2026', dup: true, tone: 2 },
{ id: 10, n: 'bathroom-tiles.png', sz: '860 KB', dim: '1800 × 1200', ty: 'PNG', used: 0, by: 'Marta Alves', d: '4 Aug 2026', alpha: true, tone: 1 },
{ id: 11, n: 'lime-plaster.jpg', sz: '2.1 MB', dim: '3200 × 2133', ty: 'JPEG', used: 2, by: 'Inès Duarte', d: '19 Jul 2026', tone: 1 },
{ id: 12, n: 'floorboards.jpg', sz: '2.4 MB', dim: '3600 × 2400', ty: 'JPEG', used: 4, by: 'Inès Duarte', d: '14 Jun 2026', dup: true, tone: 0 }
]
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 usedList = n => AR.slice(0, Math.min(n, 5))
const ids = s.ids || IM.map(x => x.id)
const imgs = ids.map(byId)
const sel = s.sel || []
const pl = n => n + (n === 1 ? ' article' : ' articles')
const label = im => im.n + ', ' + im.sz + ', ' + (im.used ? 'used in ' + pl(im.used) : 'unused')
const usedBadge = im => im.used ? Bd('Used in ' + im.used, 'used') : Bd('Unused', 'unused')
// ---------- Media page pieces
const Card = im => {
const on = sel.includes(im.id), hov = s.hover === im.id, foc = s.focus === im.id
const showCb = m || on || hov || foc || sel.length > 0
return D('position:relative;display:flex;flex-direction:column;background:' + (on ? 'var(--rc-sand)' : 'var(--ui-bg)') + ';color:' + (on ? '#111111' : 'var(--ui-text)') + ';border:1px solid ' + (on ? 'var(--ui-primary)' : hov ? 'var(--ui-border-accented)' : 'var(--ui-border)') + ';' + (on ? 'box-shadow:inset 0 0 0 1px var(--ui-primary);' : hov ? 'box-shadow:var(--rc-shadow-pop);' : '') + (foc ? 'outline:2px solid var(--ui-primary);outline-offset:2px;' : ''),
Th(im, 'aspect-ratio:4/3;border-bottom:1px solid ' + (on ? 'var(--ui-primary)' : 'var(--ui-border)')),
showCb && S('position:absolute;top:0;left:0;width:' + (m ? 44 : 36) + 'px;height:' + (m ? 44 : 36) + 'px;display:flex;align-items:center;justify-content:center', Cb(on, m ? 22 : 20)),
D('padding:10px 12px;display:flex;flex-direction:column;gap:6px;min-width:0', D('display:flex;flex-direction:column;gap:2px;min-width:0', S('font-weight:500;color:' + (on ? '#111111' : 'var(--ui-text-highlighted)') + ';overflow:hidden;text-overflow:ellipsis;white-space:nowrap', im.n), S('font-size:12px;color:' + (on ? '#444444' : 'var(--ui-text-muted)') + ';white-space:nowrap;overflow:hidden;text-overflow:ellipsis', im.sz + ' · ' + im.dim)),
D('display:flex;flex-wrap:wrap;gap:4px', im.dup && Bd('Duplicate', 'dup'), usedBadge(im))))
}
const Grid = () => D('display:grid;grid-template-columns:repeat(' + (m ? 2 : 5) + ',minmax(0,1fr));gap:' + (m ? 10 : 16) + 'px', ...imgs.map(Card))
const Skel = () => D('display:grid;grid-template-columns:repeat(' + (m ? 2 : 5) + ',minmax(0,1fr));gap:' + (m ? 10 : 16) + 'px', ...Array.from({ length: m ? 6 : 10 }, () => D('background:var(--ui-bg);border:1px solid var(--ui-border)', S('display:block;aspect-ratio:4/3;background:var(--ui-bg-accented)'), D('padding:10px 12px;display:flex;flex-direction:column;gap:8px', S('display:block;width:70%;height:13px;background:var(--ui-bg-accented)'), S('display:block;width:45%;height:11px;background:var(--ui-bg-accented)'), S('display:block;width:60px;height:20px;background:var(--ui-bg-accented)')))))
const usedLink = im => im.used ? S('text-decoration:underline;text-underline-offset:3px;color:var(--ui-text-highlighted)', pl(im.used)) : Bd('Unused', 'unused')
const Table = () => {
const cols = '36px minmax(0,1.7fr) 110px 76px 64px 120px 130px 100px'
const hd = D('display:grid;grid-template-columns:' + cols + ';height:36px;align-items:center;padding:0 12px 0 0;background:var(--ui-bg-elevated);color:var(--ui-text-muted);font-weight:500', S('display:flex;justify-content:center', Cb(false, 18, sel.length > 0 && sel.length < imgs.length)), S('', 'Filename'), S('', 'Dimensions'), S('', 'Size'), S('', 'Type'), S('', 'Used in'), S('', 'Uploaded by'), S('display:flex;align-items:center;gap:4px;color:var(--ui-text-highlighted)', 'Uploaded', I('arrow-down', 12)))
return D('background:var(--ui-bg);border:1px solid var(--ui-border)', hd, ...imgs.map(im => {
const on = sel.includes(im.id), hov = s.hover === im.id
return D('display:grid;grid-template-columns:' + cols + ';height:56px;align-items:center;padding:0 12px 0 0;border-top:1px solid var(--ui-border);background:' + (on ? 'var(--rc-sand)' : hov ? 'var(--ui-bg-elevated)' : 'var(--ui-bg)') + ';color:' + (on ? '#111111' : 'var(--ui-text-muted)'),
S('display:flex;justify-content:center', Cb(on, 18)),
D('display:flex;align-items:center;gap:12px;min-width:0;padding-right:12px', Th(im, 'width:40px;height:40px;flex-shrink:0;border:1px solid var(--ui-border)', 16), S('font-weight:500;color:' + (on ? '#111111' : 'var(--ui-text-highlighted)') + ';overflow:hidden;text-overflow:ellipsis;white-space:nowrap', im.n), im.dup && Bd('Duplicate', 'dup')),
S('', im.dim), S('', im.sz), S('', im.ty), S('', usedLink(im)), S('overflow:hidden;text-overflow:ellipsis;white-space:nowrap;padding-right:8px', im.by), S('', im.d))
}))
}
const Cards = () => D('background:var(--ui-bg);border:1px solid var(--ui-border);margin:0 -16px;border-left:0;border-right:0', ...imgs.map(im => {
const on = sel.includes(im.id)
return D('display:flex;align-items:center;gap:0;min-height:80px;padding:8px 12px 8px 0;border-bottom:1px solid var(--ui-border);background:' + (on ? 'var(--rc-sand)' : 'var(--ui-bg)') + ';color:' + (on ? '#444444' : 'var(--ui-text-muted)'),
S('width:44px;height:44px;flex-shrink:0;display:flex;align-items:center;justify-content:center', Cb(on, 22)),
Th(im, 'width:56px;height:56px;flex-shrink:0;border:1px solid var(--ui-border)', 20),
D('flex:1;min-width:0;display:flex;flex-direction:column;gap:3px;padding-left:12px', S('font-weight:500;font-size:15px;color:' + (on ? '#111111' : 'var(--ui-text-highlighted)') + ';overflow:hidden;text-overflow:ellipsis;white-space:nowrap', im.n), S('font-size:12px', im.sz + ' · ' + im.dim + ' · ' + im.ty), D('display:flex;flex-wrap:wrap;gap:4px;align-items:center;font-size:12px', im.dup && Bd('Duplicate', 'dup'), usedBadge(im), S('', im.by + ' · ' + im.d))),
I('chevron-right', 16, 'margin-left:8px'))
}))
const dg = s.dupEmpty ? 0 : s.dupGroups ?? 2
const tabs = [['all', 'All', String(imgs.length)], ['unused', 'Unused', String(imgs.filter(x => !x.used).length)], ['dups', 'Duplicates', String(dg)]]
const tab = s.tab || 'all'
const TabRow = () => D('display:flex;gap:20px;flex:1;' + (m ? 'border-bottom:1px solid var(--ui-border)' : ''), ...tabs.map(([k, t, n]) => S('height:' + (m ? 44 : 36) + 'px;display:flex;align-items:center;gap:6px;border-bottom:2px solid ' + (tab === k ? 'var(--ui-primary)' : 'transparent') + ';margin-bottom:-1px;font-weight:' + (tab === k ? 500 : 400) + ';color:' + (tab === k ? 'var(--ui-text-highlighted)' : 'var(--ui-text-toned)') + ';font-size:' + (m ? 15 : 13) + 'px', t, k === 'dups' ? (dg > 0 && S('height:18px;min-width:18px;padding:0 5px;display:inline-flex;align-items:center;justify-content:center;background:var(--rc-info-soft);color:var(--ui-info);font:500 11px \'IBM Plex Mono\',monospace', n)) : S('font:500 11px \'IBM Plex Mono\',monospace;color:var(--ui-text-muted)', n))))
const Search = () => D('height:' + (m ? 44 : 32) + 'px;' + (m ? '' : 'width:240px;margin-bottom:0;') + 'padding:0 4px 0 10px;display:flex;align-items:center;gap:8px;border:1px solid var(--ui-border-accented);background:var(--ui-bg);color:' + (s.q ? 'var(--ui-text-highlighted)' : 'var(--ui-text-muted)') + (m ? ';font-size:16px' : ''), I('search', 14), S('flex:1', s.q || 'Search by filename'), s.q && S('width:' + (m ? 36 : 24) + 'px;height:' + (m ? 36 : 24) + 'px;display:flex;align-items:center;justify-content:center;color:var(--ui-text-muted)', I('x', 14)))
const Sort = () => D('height:' + (m ? 44 : 32) + 'px;padding:0 10px;display:flex;align-items:center;gap:8px;border:1px solid var(--ui-border-accented);background:var(--ui-bg);color:var(--ui-text-highlighted);' + (m ? 'flex:1;' : 'width:128px;'), S('flex:1', s.sort || 'Newest'), I('chevron-down', 14, 'color:var(--ui-text-muted)'))
const view = s.view || 'grid'
const Toggle = () => D('display:flex;border:1px solid var(--ui-border-accented);flex-shrink:0', ...[['grid', 'layout-grid'], ['list', 'list']].map(([k, ic]) => S('width:' + (m ? 44 : 32) + 'px;height:' + (m ? 42 : 30) + 'px;display:flex;align-items:center;justify-content:center;background:' + (view === k ? 'var(--rc-sand)' : 'var(--ui-bg)') + ';color:' + (view === k ? '#111111' : 'var(--ui-text-toned)'), I(ic))))
const SelectAll = () => D('display:flex;align-items:center;gap:10px;color:var(--ui-text-muted)', m ? S('width:44px;height:44px;margin-left:-11px;display:flex;align-items:center;justify-content:center', Cb(false, 22, sel.length > 0)) : Cb(false, 18, sel.length > 0), S('color:var(--ui-text-highlighted);font-weight:500', 'Select all'), S('', imgs.length + ' images'))
const UP = s.upload
const upRow = r => {
const sc = { err: 'var(--ui-error)', dup: 'var(--ui-info)' }[r.st] || 'var(--ui-text-muted)'
const body = {
prog: [S('', 'Uploading ' + r.p), D('width:100%;height:4px;background:var(--ui-bg-accented)', D('width:' + r.pct + ';height:4px;background:var(--ui-primary)'))],
wait: [S('color:var(--ui-text-muted)', 'Waiting')],
ok: [S('display:flex;align-items:center;gap:6px;color:var(--ui-success)', I('circle-check', 14), 'Added to your library')],
dup: [S('font-weight:600;color:var(--ui-text-highlighted)', 'Already in your library'), S('color:var(--ui-text-toned);font-size:12px', r.msg), D('display:flex;gap:8px;flex-wrap:wrap', B('Use existing', { h: m ? 44 : 28, fs: 12, px: 10, full: m }), B('Upload anyway', { h: m ? 44 : 28, fs: 12, px: 10, full: m }))],
rej: [S('display:flex;gap:6px;align-items:center;font-weight:600;color:var(--ui-error)', I('file-x', 14), r.title), S('color:var(--ui-text-toned);font-size:12px', r.msg)],
fail: [S('display:flex;gap:6px;align-items:center;font-weight:600;color:var(--ui-error)', I('circle-x', 14), 'Upload failed'), S('color:var(--ui-text-toned);font-size:12px', 'The server didn\'t accept the file. Nothing was added to your library.'), D('display:flex', B('Try again', { icon: 'rotate-cw', z: 14, h: m ? 44 : 28, fs: 12, px: 10, full: m }))]
}[r.st]
return D('display:flex;gap:12px;align-items:flex-start;padding:12px 14px;border-top:1px solid var(--ui-border-muted)', Th(byId(r.im || 8), 'width:40px;height:40px;flex-shrink:0;border:1px solid var(--ui-border)', 16), D('flex:1;min-width:0;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);overflow:hidden;text-overflow:ellipsis;white-space:nowrap', r.n), S('color:var(--ui-text-muted);white-space:nowrap', r.sz)), ...body), r.st === 'prog' && S('width:24px;height:24px;display:flex;align-items:center;justify-content:center;color:var(--ui-text-muted)', I('x', 14)))
}
const UpPanel = () => D('background:var(--ui-bg);border:1px solid var(--ui-border);display:flex;flex-direction:column', D('display:flex;align-items:center;gap:12px;padding:12px 14px', D('flex:1;display:flex;flex-direction:column;gap:2px', S('font-weight:600;color:var(--ui-text-highlighted)', UP.title), S('color:var(--ui-text-muted)', UP.sub)), UP.done ? B('Dismiss', { h: m ? 44 : 28, fs: 12 }) : B('Cancel all', { h: m ? 44 : 28, fs: 12 })), ...UP.rows.map(upRow), UP.summary && D('padding:12px 14px;border-top:1px solid var(--ui-border);background:var(--ui-bg-elevated);color:var(--ui-text-toned);font-weight:500', UP.summary))
const Groups = () => {
const G = [
{ n: 'floorboards.jpg', sub: '3 identical images · 2.4 MB each · 3600 × 2400', c: [12, 5, 6], keep: 12 },
{ n: 'IMG_4471.jpg', sub: '2 identical images · 3.1 MB each · 3600 × 2400', c: [7, 9], keep: 7 }
]
return D('display:flex;flex-direction:column;gap:16px', ...G.slice(2 - dg).map((g, gi) => D('background:var(--ui-bg);border:1px solid var(--ui-border)', D('padding:12px 14px;border-bottom:1px solid var(--ui-border);display:flex;flex-direction:column;gap:2px', S('font-weight:600;color:var(--ui-text-highlighted)', 'Group ' + (gi + 1)), S('color:var(--ui-text-muted)', g.sub)),
D('display:grid;grid-template-columns:' + (m ? 'minmax(0,1fr)' : 'repeat(' + g.c.length + ',minmax(0,1fr))') + ';gap:' + (m ? 0 : 16) + 'px;padding:' + (m ? 0 : 16) + 'px', ...g.c.map(id => {
const im = byId(id), k = id === g.keep
const others = g.c.filter(x => x !== id).length
return D('display:flex;' + (m ? 'flex-direction:column;gap:12px;padding:14px;border-bottom:1px solid var(--ui-border-muted)' : 'flex-direction:column;gap:12px;padding:12px;border:1px solid ' + (k ? 'var(--ui-primary)' : 'var(--ui-border)')) + ';background:' + (k ? 'var(--rc-sand)' : 'var(--ui-bg)') + ';color:' + (k ? '#111111' : 'var(--ui-text)'),
D('display:flex;gap:12px;' + (m ? 'align-items:flex-start' : 'flex-direction:column'), Th(im, (m ? 'width:96px;height:72px;flex-shrink:0' : 'aspect-ratio:4/3') + ';border:1px solid var(--ui-border)'),
D('display:flex;flex-direction:column;gap:4px;min-width:0', D('display:flex;gap:6px;align-items:center;flex-wrap:wrap', S('font-weight:500;color:' + (k ? '#111111' : 'var(--ui-text-highlighted)') + ';overflow:hidden;text-overflow:ellipsis;white-space:nowrap', im.n), k && S('height:20px;padding:0 6px;display:inline-flex;align-items:center;background:var(--ui-primary);color:var(--ui-bg);font-size:12px;font-weight:500', 'Suggested')),
S('font-size:12px;color:' + (k ? '#444444' : 'var(--ui-text-muted)'), 'Uploaded ' + im.d + ' by ' + im.by),
S('font-weight:500;text-decoration:underline;text-underline-offset:3px', 'Used in ' + pl(im.used)))),
B('Merge into this one', { k: k ? 'primary' : 'outline', full: false, icon: 'merge', h: bh }))
})),
D('padding:10px 14px;border-top:1px solid var(--ui-border);color:var(--ui-text-muted);font-size:12px', 'Suggested: the most used copy, then the oldest. Choosing another copy switches articles to it.'))))
}
const Header = () => D('display:flex;align-items:flex-end;gap:16px;flex-wrap:wrap', D('flex:1;min-width:200px;display:flex;flex-direction:column;gap:2px', S('font:600 20px/28px \'IBM Plex Sans\',sans-serif;color:var(--ui-text-highlighted)', 'Media'), S('color:var(--ui-text-muted)', 'Every image you\'ve uploaded, ready to use in any article.')), !m && (s.limited ? B('Try again in 0:42', { k: 'primary', icon: 'timer', dis: true }) : B('Upload', { k: 'primary', icon: 'upload', dis: s.offline })))
const pageBody = () => {
const parts = []
if (s.empty === 'first') { parts.push(Empty('images', 'No images yet', 'Upload your first image. You can use it in any article.', 'Upload an image', true), S('align-self:center;color:var(--ui-text-muted);font-size:12px', 'PNG, JPEG, WEBP, SVG · max 10 MB each')); return parts }
if (s.limited) parts.push(Alert('info', 'timer', 'Too many uploads', 'For your security, wait a moment before uploading again.'))
if (s.error) parts.push(Alert('error', 'circle-x', 'Couldn\'t load your images', 'Check your connection and try again.', 'Try again'))
const tb = m
? D('display:flex;flex-direction:column;gap:12px', Search(), TabRow(), D('display:flex;gap:8px', Sort(), Toggle()))
: D('display:flex;align-items:flex-end;gap:12px;border-bottom:1px solid var(--ui-border)', TabRow(), S('display:flex;padding-bottom:6px;gap:8px', Search(), Sort(), Toggle()))
parts.push(tb)
if (UP) parts.push(UpPanel())
if (s.loading) parts.push(Skel())
else if (s.error) { }
else if (s.empty === 'search') parts.push(Empty('search', 'No images match "wall"', 'Nothing matches in Unused. Check the spelling, or clear the filters.', 'Clear filters', false))
else if (tab === 'dups') parts.push(s.dupEmpty ? Empty('copy', 'No duplicates', 'Every image in your library is different.', 'Back to all images', false) : Groups())
else {
if (view === 'grid') parts.push(SelectAll(), Grid()); else parts.push(m ? Cards() : Table())
}
return parts
}
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
const Panel = () => {
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 w = m ? '100%' : '460px'
return D('position:absolute;inset:0;z-index:40;display:flex;justify-content:flex-end;background:' + (m ? 'var(--ui-bg)' : 'var(--rc-overlay)'),
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('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),
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' }),
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'),
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.'),
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))))
}
// ---------- modal
const Field = (lab, val, o = {}) => D('display:flex;flex-direction:column;gap:6px', D('display:flex;justify-content:space-between', S('font-weight:500;color:var(--ui-text-highlighted)', lab), o.count && S('font:400 12px \'IBM Plex Mono\',monospace;color:var(--ui-text-muted)', o.count)), D('display:flex;align-items:center;min-height:' + (o.area ? 72 : m ? 44 : 40) + 'px;border:1px solid ' + (o.err ? 'var(--ui-error)' : o.focus ? 'var(--ui-primary)' : 'var(--ui-border-accented)') + ';' + (o.focus ? 'box-shadow:0 0 0 1px var(--ui-primary);' : '') + 'background:var(--ui-bg);font-size:' + (m ? 16 : 13) + 'px;' + (o.area ? 'align-items:flex-start;' : ''), S('flex:1;min-width:0;padding:' + (o.area ? '10px' : '0') + ' 12px;color:' + (o.val ? 'var(--ui-text-highlighted)' : 'var(--ui-text-muted)') + (o.dis ? ';opacity:.6' : ''), val), o.suffix && S('padding:0 12px;color:var(--ui-text-muted);font:400 13px \'IBM Plex Mono\',monospace', o.suffix)), o.err && S('display:flex;gap:6px;align-items:center;color:var(--ui-error);font-size:12px', I('circle-alert', 14), o.err), o.help && S('color:var(--ui-text-muted);font-size:12px', o.help))
const ArtBox = (list, more) => D('border:1px solid var(--ui-border)', ...list.map(([t, on], 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;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;color:var(--ui-text-highlighted)', t), on ? Bd('Online', 'on') : Bd('Draft', 'draft'))), more && D('padding:8px 12px;border-top:1px solid var(--ui-border-muted);color:var(--ui-text-muted)', more))
const modalCfg = () => {
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 === '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 === '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 === '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 === 'remove') return { title: 'Remove this image from the article?', desc: 'It\'s removed from this article only. The file stays in your library and in any other article that uses it.', body: [D('display:flex;gap:12px;align-items:center;border:1px solid var(--ui-border);padding:10px 12px', Th(byId(1), '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)', 'north-wall.jpg'), S('font-size:12px;color:var(--ui-text-muted)', 'Stays in the library · 3.9 MB')))], cancel: 'Cancel', confirm: 'Remove image' }
}
const Shell = (o, body) => D('position:absolute;inset:0;z-index:50;background:var(--rc-overlay);display:flex;align-items:' + (m ? 'flex-end' : 'flex-start') + ';justify-content:center;padding:' + (m ? 16 : 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',
D('padding:20px 24px 0;display:flex;align-items:flex-start;gap:12px', D('flex:1;display:flex;flex-direction:column;gap:4px', S('font:600 16px/24px \'IBM Plex Sans\',sans-serif;color:var(--ui-text-highlighted)', o.title), o.desc && S('color:var(--ui-text-muted);text-wrap:pretty', o.desc)), o.close && S('width:28px;height:28px;display:flex;align-items:center;justify-content:center;color:var(--ui-text-muted)', I('x'))),
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;opacity:' + (o.cdis ? 0.4 : 1), o.loading && I('loader-circle'), o.confirm))))
const Modal = () => {
const md = s.modal, c = modalCfg()
return Shell(c, D('padding:20px 24px 0;display:flex;flex-direction:column;gap:16px;min-height:0;overflow:hidden', md.notice && D('display:flex;gap:8px;padding:10px 12px;background:var(--rc-error-soft);color:var(--ui-error)', S('display:flex;padding-top:2px', I('circle-x')), S('color:var(--ui-text-toned)', md.notice)), ...(c.body || [])))
}
const Toasts = () => D('position:absolute;z-index:60;display:flex;flex-direction:column;gap:8px;' + (m ? 'left:16px;right:16px;bottom:' + (s.sel && s.sel.length ? 80 : 16) + 'px' : 'right:24px;bottom:24px;width:356px'), ...s.toasts.map(t => D('display:flex;gap:10px;padding:12px 14px;background:var(--ui-bg);border:1px solid var(--ui-border);box-shadow:var(--rc-shadow-pop)', S('margin-top:2px;display:flex;color:var(--ui-' + t[0] + ')', I(t[1])), D('flex:1;display:flex;flex-direction:column;gap:6px', D('display:flex;flex-direction:column;gap:2px', S('font-weight:600;color:var(--ui-text-highlighted)', t[2]), S('color:var(--ui-text-muted)', t[3])), t[4] && B(t[4], { icon: 'rotate-cw', z: 14, h: m ? 44 : 28, fs: 12, px: 10 })), I('x'))))
// ---------- picker (editor + dialog)
const Editor = () => 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)', 'How we price a bathroom renovation'), !m && B('Save', { dis: true }), !m && B('Publish', { k: 'primary' })),
D('flex:1;overflow:hidden;padding:' + (m ? '20px 16px' : '32px 0') + ';display:flex;justify-content:center', D('width:100%;max-width:680px;display:flex;flex-direction:column;gap:16px;font-family:\'Source Serif 4\',serif;font-size:' + (m ? 16 : 18) + 'px;line-height:1.66;color:var(--ui-text-toned)',
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('display:block', 'We don\'t add a margin on materials you choose yourself.'))))
const PT = s.pk || {}
const pImgs = (PT.ids || [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]).map(byId)
const inArt = [1, 4]
const cols = m ? 3 : 4
const PTile = im => {
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),
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:#111111;font-size:11px;font-weight:500', '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))),
S('font-size:12px;color:var(--ui-text-toned);overflow:hidden;text-overflow:ellipsis;white-space:nowrap', im.n))
}
const PGrid = () => D('display:grid;grid-template-columns:repeat(' + cols + ',minmax(0,1fr));gap:12px ' + (m ? 8 : 12) + 'px', ...pImgs.map(PTile), ...(PT.more ? Array.from({ length: cols }, () => D('display:flex;flex-direction:column;gap:6px', S('display:block;aspect-ratio:1/1;background:var(--ui-bg-accented)'), S('display:block;width:70%;height:10px;background:var(--ui-bg-accented)'))) : []))
const PSkel = () => D('display:grid;grid-template-columns:repeat(' + cols + ',minmax(0,1fr));gap:12px ' + (m ? 8 : 12) + 'px', ...Array.from({ length: m ? 9 : 8 }, () => D('display:flex;flex-direction:column;gap:6px', S('display:block;aspect-ratio:1/1;background:var(--ui-bg-accented)'), S('display:block;width:70%;height:10px;background:var(--ui-bg-accented)'))))
const PTabs = () => D('display:flex;gap:20px;border-bottom:1px solid var(--ui-border);padding:0 24px;margin-top:16px', ...['Upload', 'Library'].map(t => S('height:' + (m ? 44 : 36) + 'px;display:flex;align-items:center;gap:6px;border-bottom:2px solid ' + (PT.tab === t ? 'var(--ui-primary)' : 'transparent') + ';margin-bottom:-1px;font-weight:' + (PT.tab === t ? 500 : 400) + ';color:' + (PT.tab === t ? 'var(--ui-text-highlighted)' : 'var(--ui-text-toned)'), I(t === 'Upload' ? 'upload' : 'images', 14), t)))
const drop = (icon, title, text, bd, ic) => D('height:180px;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:8px;padding:16px;text-align:center;border:' + bd + ';background:var(--ui-bg)', I(icon, 24, 'color:' + (ic || 'var(--ui-text-toned)')), S('font-weight:500;color:var(--ui-text-highlighted)', title), S('color:var(--ui-text-toned);font-size:12px;max-width:300px', text))
const PBody = () => {
if (PT.tab === 'Upload') {
if (PT.dup) return D('display:flex;flex-direction:column;gap:12px;padding:16px;border:1px solid var(--ui-info);background:var(--ui-bg)', D('display:flex;gap:12px;align-items:center', Th(byId(1), 'width:72px;height:54px;flex-shrink:0;border:1px solid var(--ui-border)', 16), D('display:flex;flex-direction:column;gap:2px;min-width:0', S('font-weight:600;color:var(--ui-text-highlighted)', 'Already in your library'), S('color:var(--ui-text-toned);font-size:12px', 'north-wall.jpg matches an image uploaded on 12 Sep 2026 by Marta Alves.'))), D('display:flex;gap:8px;' + (m ? 'flex-direction:column' : ''), B('Use existing', { k: 'primary', full: m }), B('Upload anyway', { full: m })))
return drop('image-plus', 'Drop an image here, or choose a file', 'PNG, JPEG, WEBP, SVG · max 10 MB', '1px dashed var(--ui-border-accented)')
}
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))))
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 === '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 {
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) { 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.' }))) }
return D('display:flex;flex-direction:column;gap:12px', ...kids)
}
const Picker = () => {
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())))
}
// ---------- shell
const nav = [['home', 'house', 'Home'], ['articles', 'file-text', 'Articles'], ['media', 'images', 'Media'], ['users', 'users', 'Users'], ['integration', 'plug', 'Integration'], ['settings', 'settings', 'Settings']]
const isPicker = s.kind === 'picker'
const navKey = isPicker ? 'articles' : 'media'
const crumbs = isPicker ? ['Articles', 'How we price a bathroom renovation'] : ['Media']
const side = D('width:224px;flex-shrink:0;background:var(--ui-bg);border-right:1px solid var(--ui-border);display:flex;flex-direction:column;padding:12px;gap:2px',
D('display:flex;align-items:center;gap:10px;height:40px;padding:0 6px;margin-bottom:10px', h('svg', { width: 26, height: 26, viewBox: '0 0 16 16', shapeRendering: 'crispEdges' }, h('rect', { width: 16, height: 16, fill: '#111' }), h('path', { fill: '#fff', fillRule: 'evenodd', d: 'M4 3h6v1h1v1h1v3h-1v1h-1v1h1v1h1v2h-2v-2h-1v-1H6v3H4zm2 2v3h4V5z' })), S('font-weight:600;font-size:14px;color:var(--ui-text-highlighted)', 'RenewCMS')),
...nav.map(([k, ic, t]) => D('display:flex;align-items:center;gap:10px;height:32px;padding:0 10px;background:' + (k === navKey ? 'var(--rc-sand)' : 'transparent') + ';color:' + (k === navKey ? '#111111' : 'var(--ui-text-toned)') + ';font-weight:' + (k === navKey ? 500 : 400), I(ic), t)),
D('flex:1'), D('display:flex;align-items:center;gap:10px;height:40px;padding:0 6px;color:var(--ui-text-highlighted)', S('width:26px;height:26px;flex-shrink:0;background:#d4c5b0;color:#111;display:flex;align-items:center;justify-content:center;font:600 11px \'IBM Plex Sans\',sans-serif', 'MA'), S('flex:1;font-weight:500', 'Marta Alves'), I('chevrons-up-down', 14)))
const topbar = m
? D('height:56px;flex-shrink:0;border-bottom:1px solid var(--ui-border);background:var(--ui-bg);display:flex;align-items:center;padding:0 6px;gap:4px;color:var(--ui-text-highlighted)', S('width:44px;height:44px;display:flex;align-items:center;justify-content:center', I(isPicker ? 'arrow-left' : 'menu', 20)), S('flex:1;font-weight:600;font-size:16px', isPicker ? 'Edit article' : 'Media'), isPicker && S('width:44px;height:44px;display:flex;align-items:center;justify-content:center', I('ellipsis', 20)))
: D('height:48px;flex-shrink:0;border-bottom:1px solid var(--ui-border);background:var(--ui-bg);display:flex;align-items:center;padding:0 24px;gap:8px;color:var(--ui-text-muted)', I('panel-left-close'), S('width:1px;height:16px;background:var(--ui-border);margin:0 6px'), ...crumbs.flatMap((c, i) => [i > 0 && I('chevron-right', 14), S('color:' + (i === crumbs.length - 1 ? 'var(--ui-text-highlighted)' : 'var(--ui-text-muted)') + ';font-weight:' + (i === crumbs.length - 1 ? 500 : 400), c)]))
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 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 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:#111111;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:#444444', '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 ann = s.ann && D('position:absolute;z-index:20;' + (m ? 'left:16px;bottom:24px' : 'left:248px;bottom:20px'), Note(s.ann))
const root = D('width:' + (m ? 390 : 1440) + 'px;height:' + (m ? 844 : 900) + 'px;position:relative;display:flex;flex-direction:' + (m ? 'column' : 'row') + ';background:var(--ui-bg-muted);color:var(--ui-text);font-family:\'IBM Plex Sans\',sans-serif;font-size:13px;line-height:20px;overflow:hidden',
!m && side, D('flex:1;min-width:0;min-height:0;display:flex;flex-direction:column', topbar, offline, content),
dragOv, fab, ann, sel.length > 0 && !s.panel && !s.modal && BulkBar(), s.panel && Panel(), isPicker && s.picker && Picker(), s.modal && Modal(), s.toasts && Toasts())
return { view: root }
}
}
</script>
</body>
</html>
@@ -216,7 +216,7 @@
<span aria-live="polite" style="display:flex;align-items:center;gap:6px;color:var(--ui-warning)"><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/circle-dot.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/circle-dot.svg') center / contain no-repeat"></span>Unsaved changes</span> <span aria-live="polite" style="display:flex;align-items:center;gap:6px;color:var(--ui-warning)"><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/circle-dot.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/circle-dot.svg') center / contain no-repeat"></span>Unsaved changes</span>
<span style="height:32px;padding:0 12px;display:flex;align-items:center;gap:6px;border:1px solid var(--ui-border-accented);color:var(--ui-text-highlighted);font-weight:500"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:16px;height:16px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/save.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/save.svg') center / contain no-repeat"></span>Save</span> <span style="height:32px;padding:0 12px;display:flex;align-items:center;gap:6px;border:1px solid var(--ui-border-accented);color:var(--ui-text-highlighted);font-weight:500"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:16px;height:16px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/save.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/save.svg') center / contain no-repeat"></span>Save</span>
<span style="height:32px;padding:0 12px;display:flex;align-items:center;gap:6px;background:var(--ui-primary);color:var(--ui-bg);font-weight:500"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:16px;height:16px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/globe.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/globe.svg') center / contain no-repeat"></span>Save and publish</span> <span style="height:32px;padding:0 12px;display:flex;align-items:center;gap:6px;background:var(--ui-primary);color:var(--ui-bg);font-weight:500"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:16px;height:16px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/globe.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/globe.svg') center / contain no-repeat"></span>Save and publish</span>
<span style="width:32px;height:32px;display:flex;align-items:center;justify-content:center;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/ellipsis.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/ellipsis.svg') center / contain no-repeat"></span></span> <span role="button" aria-label="Delete article" style="height:32px;padding:0 12px;display:flex;align-items:center;gap:6px;border:1px solid var(--ui-error);color:var(--ui-error);font-weight:500;cursor:pointer"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:16px;height:16px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/trash-2.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/trash-2.svg') center / contain no-repeat"></span>Delete</span>
</div> </div>
<div role="toolbar" aria-label="Formatting" style="padding:6px 16px;display:flex;align-items:center;gap:2px;border-bottom:1px solid var(--ui-border);overflow-x:auto;background:var(--ui-bg)"> <div role="toolbar" aria-label="Formatting" style="padding:6px 16px;display:flex;align-items:center;gap:2px;border-bottom:1px solid var(--ui-border);overflow-x:auto;background:var(--ui-bg)">
<sc-for list="{{ toolbar }}" as="t" hint-placeholder-count="24"> <sc-for list="{{ toolbar }}" as="t" hint-placeholder-count="24">
+7 -5
View File
@@ -16,8 +16,8 @@
<div data-screen-label="Emails" style="padding:64px;display:flex;flex-direction:column;gap:56px;width:max-content;min-width:100%"> <div data-screen-label="Emails" style="padding:64px;display:flex;flex-direction:column;gap:56px;width:max-content;min-width:100%">
<div style="display:flex;flex-direction:column;gap:10px;max-width:900px"> <div style="display:flex;flex-direction:column;gap:10px;max-width:900px">
<h1 style="margin:0;font:600 36px/44px 'IBM Plex Sans',sans-serif;letter-spacing:-0.02em;color:#111">Transactional emails</h1> <h1 style="margin:0;font:600 36px/44px 'IBM Plex Sans',sans-serif;letter-spacing:-0.02em;color:#111">Transactional emails</h1>
<p style="margin:0;font-size:16px;line-height:26px;color:#444;text-wrap:pretty">Two Go <code>html/template</code> files: <a href="emails/verification.html">emails/verification.html</a> and <a href="emails/password-reset.html">emails/password-reset.html</a>. They use a table layout with inline CSS and a 600 px maximum width. The button is bulletproof: a colored table cell plus a padded link, so it survives Outlook. Each has a plain-URL fallback, a hidden preheader, and <code>prefers-color-scheme</code> overrides for clients that support them. The mark is live text in a black cell rather than an image, so it shows even when images are blocked. Previews below use example values.</p> <p style="margin:0;font-size:16px;line-height:26px;color:#444;text-wrap:pretty">Three Go <code>html/template</code> files: <a href="emails/verification.html">emails/verification.html</a>, <a href="emails/password-reset.html">emails/password-reset.html</a> and <a href="emails/invitation.html">emails/invitation.html</a>. They use a table layout with inline CSS and a 600 px maximum width. The button is bulletproof: a colored table cell plus a padded link, so it survives Outlook. Each has a plain-URL fallback, a hidden preheader, and <code>prefers-color-scheme</code> overrides for clients that support them. The mark is live text in a black cell rather than an image, so it shows even when images are blocked. Previews below use example values.</p>
<p style="margin:0;font-size:14px;line-height:22px;color:#666;text-wrap:pretty">Suggested subjects are "Verify your RenewCMS account" and "Reset your RenewCMS password". <code>html/template</code> escapes the <code>.Email</code> value for the query string in the reset link (the @ becomes %40), and the confirm route reads it back decoded.</p> <p style="margin:0;font-size:14px;line-height:22px;color:#666;text-wrap:pretty">Suggested subjects are "Verify your RenewCMS account", "Reset your RenewCMS password" and "&lt;username&gt; invited you to RenewCMS", using <code>.InvitedBy</code>. <code>html/template</code> escapes the <code>.Email</code> value for the query string in the reset link (the @ becomes %40), and the confirm route reads it back decoded.</p>
</div> </div>
<sc-for list="{{ rows }}" as="r" hint-placeholder-count="2"> <sc-for list="{{ rows }}" as="r" hint-placeholder-count="2">
<section style="display:flex;flex-direction:column;gap:20px"> <section style="display:flex;flex-direction:column;gap:20px">
@@ -33,13 +33,14 @@
</x-dc> </x-dc>
<script type="text/x-dc" data-dc-script> <script type="text/x-dc" data-dc-script>
class Component extends DCLogic { class Component extends DCLogic {
state = { v: '', r: '' } state = { v: '', r: '', i: '' }
componentDidMount() { componentDidMount() {
fetch('emails/verification.html').then(x => x.text()).then(v => this.setState({ v })) fetch('emails/verification.html').then(x => x.text()).then(v => this.setState({ v }))
fetch('emails/password-reset.html').then(x => x.text()).then(r => this.setState({ r })) fetch('emails/password-reset.html').then(x => x.text()).then(r => this.setState({ r }))
fetch('emails/invitation.html').then(x => x.text()).then(i => this.setState({ i }))
} }
fill(t) { fill(t) {
return t.split('{{.Host}}').join('https://cms.renew.example').split('{{.VerificationCode}}').join('7f3c9a2e4b1d').split('{{.Email}}').join('marta%40renew.example').replace('uses marta%40renew.example', 'uses marta@renew.example') return t.split('{{.InvitedBy}}').join('marta').split('{{.Email}} It').join('lea.martin@renew.example. It').split('sent to {{.Email}}').join('sent to lea.martin@renew.example').split('{{.Host}}').join('https://cms.renew.example').split('{{.VerificationCode}}').join('7f3c9a2e4b1d').split('{{.Email}}').join('marta%40renew.example').replace('uses marta%40renew.example', 'uses marta@renew.example')
} }
frames(t) { frames(t) {
if (!t) return [] if (!t) return []
@@ -50,7 +51,8 @@ class Component extends DCLogic {
renderVals() { renderVals() {
return { rows: [ return { rows: [
{ title: 'Verification email', vars: '{{.Host}} · {{.VerificationCode}} → /register/validate?c=', frames: this.frames(this.state.v) }, { title: 'Verification email', vars: '{{.Host}} · {{.VerificationCode}} → /register/validate?c=', frames: this.frames(this.state.v) },
{ title: 'Password reset email', vars: '{{.Host}} · {{.VerificationCode}} · {{.Email}} → /register/reset/validate?c=&email=', frames: this.frames(this.state.r) } { title: 'Password reset email', vars: '{{.Host}} · {{.VerificationCode}} · {{.Email}} → /register/reset/validate?c=&email=', frames: this.frames(this.state.r) },
{ title: 'Invitation email', vars: '{{.Host}} · {{.VerificationCode}} · {{.Email}} · {{.InvitedBy}} → /invite/accept?c=', frames: this.frames(this.state.i) }
] } ] }
} }
} }
+12 -5
View File
@@ -79,13 +79,14 @@ class Component extends DCLogic {
{ t: 'Foundations', d: 'Tokens, contrast, type, motion, icons', href: 'RenewCMS Foundations.dc.html' }, { t: 'Foundations', d: 'Tokens, contrast, type, motion, icons', href: 'RenewCMS Foundations.dc.html' },
{ t: 'Primitives', d: 'Themed Nuxt UI components', href: 'RenewCMS Components Primitives.dc.html' }, { t: 'Primitives', d: 'Themed Nuxt UI components', href: 'RenewCMS Components Primitives.dc.html' },
{ t: 'Product components', d: '17 RenewCMS components', href: 'RenewCMS Components Product.dc.html' }, { t: 'Product components', d: '17 RenewCMS components', href: 'RenewCMS Components Product.dc.html' },
{ t: 'Auth screens', d: 'Six public routes, every state', href: 'RenewCMS Screens Auth.dc.html' }, { t: 'Auth screens', d: 'Seven public routes, every state', href: 'RenewCMS Screens Auth.dc.html' },
{ t: 'Back-office screens', d: 'Verified routes and global states', href: 'RenewCMS Screens Back-office.dc.html' }, { t: 'Back-office screens', d: 'Verified routes and global states', href: 'RenewCMS Screens Back-office.dc.html' },
{ t: 'Emails', d: 'Previews of both templates', href: 'RenewCMS Emails.dc.html' }, { t: 'Emails', d: 'Previews of the three templates', href: 'RenewCMS Emails.dc.html' },
{ t: 'tokens/renewcms.css', d: '@theme, :root, .dark, .article-content', href: 'tokens/renewcms.css' }, { t: 'tokens/renewcms.css', d: '@theme, :root, .dark, .article-content', href: 'tokens/renewcms.css' },
{ t: 'tokens/ui.config.ts', d: 'Nuxt UI colors, icons, overrides', href: 'tokens/ui.config.ts' }, { t: 'tokens/ui.config.ts', d: 'Nuxt UI colors, icons, overrides', href: 'tokens/ui.config.ts' },
{ t: 'tokens/vite.config.ts', d: 'Vite plugin setup', href: 'tokens/vite.config.ts' }, { t: 'tokens/vite.config.ts', d: 'Vite plugin setup', href: 'tokens/vite.config.ts' },
{ t: 'emails/verification.html', d: 'Go html/template', href: 'emails/verification.html' }, { t: 'emails/verification.html', d: 'Go html/template', href: 'emails/verification.html' },
{ t: 'emails/invitation.html', d: 'Go html/template', href: 'emails/invitation.html' },
{ t: 'emails/password-reset.html', d: 'Go html/template', href: 'emails/password-reset.html' }, { t: 'emails/password-reset.html', d: 'Go html/template', href: 'emails/password-reset.html' },
{ t: 'brand/favicon.svg', d: '16 px grid mark, dark-aware', href: 'brand/favicon.svg' } { t: 'brand/favicon.svg', d: '16 px grid mark, dark-aware', href: 'brand/favicon.svg' }
] ]
@@ -95,6 +96,7 @@ class Component extends DCLogic {
['/register', 'AuthShell', 'public', 'RegisterPage', 'POST /v1/auth/register'], ['/register', 'AuthShell', 'public', 'RegisterPage', 'POST /v1/auth/register'],
['/register/pending', 'AuthShell', 'session', 'PendingPage', 'DELETE /v1/auth/register · POST /v1/auth/logout'], ['/register/pending', 'AuthShell', 'session', 'PendingPage', 'DELETE /v1/auth/register · POST /v1/auth/logout'],
['/register/validate', 'AuthShell', 'public', 'VerifyPage', 'POST /v1/auth/verify (+ POST /login inline on 401)'], ['/register/validate', 'AuthShell', 'public', 'VerifyPage', 'POST /v1/auth/verify (+ POST /login inline on 401)'],
['/invite/accept', 'AuthShell', 'public', 'AcceptInvitePage', 'GET /v1/auth/invite?c=* · POST /v1/auth/invite/accept*'],
['/register/reset/request', 'AuthShell', 'public', 'ResetRequestPage', 'POST /v1/auth/password-reset'], ['/register/reset/request', 'AuthShell', 'public', 'ResetRequestPage', 'POST /v1/auth/password-reset'],
['/register/reset/validate', 'AuthShell', 'public', 'ResetConfirmPage', 'POST /v1/auth/password-reset/confirm'], ['/register/reset/validate', 'AuthShell', 'public', 'ResetConfirmPage', 'POST /v1/auth/password-reset/confirm'],
['/home', 'DashboardShell', 'verified', 'HomePage', 'GET /v1/article/'], ['/home', 'DashboardShell', 'verified', 'HomePage', 'GET /v1/article/'],
@@ -120,9 +122,9 @@ class Component extends DCLogic {
['SaveStatus', 'custom (span + UButton)', "state: 'clean'|'dirty'|'saving'|'saved'|'error'|'offline', savedAt?: Date", 'retry', 'none', 'Editor'], ['SaveStatus', 'custom (span + UButton)', "state: 'clean'|'dirty'|'saving'|'saved'|'error'|'offline', savedAt?: Date", 'retry', 'none', 'Editor'],
['PublishControl', 'UButton', 'online: boolean, dirty: boolean, pending?: string, disabled?', 'publish, unpublish', 'none', 'Editor'], ['PublishControl', 'UButton', 'online: boolean, dirty: boolean, pending?: string, disabled?', 'publish, unpublish', 'none', 'Editor'],
['ArticleDetails', 'UCard (desktop) / USlideover (mobile)', 'article: Article', 'copy-url', 'none', 'Editor'], ['ArticleDetails', 'UCard (desktop) / USlideover (mobile)', 'article: Article', 'copy-url', 'none', 'Editor'],
['CharacterCounter', 'custom', 'value: number, max: number, min?: number, warnAt?: number', 'none', 'none', 'NewArticleModal, Editor, Register'], ['CharacterCounter', 'custom', 'value: number, max: number, min?: number, warnAt?: number', 'none', 'none', 'NewArticleModal, Editor, Register, Accept invite'],
['PasswordStrengthHint', 'custom (in UFormField #help)', 'rules: { label, met }[], showErrors: boolean', 'none', 'none', 'Register, Reset'], ['PasswordStrengthHint', 'custom (in UFormField #help)', 'rules: { label, met }[], showErrors: boolean', 'none', 'none', 'Register, Reset, Accept invite'],
['ResultPanel', 'custom + UButton', "tone: 'success'|'error'|'info', icon, title, description, actions: ButtonProps[]", 'none', 'default', 'Pending, Verify, Reset request, Reset, Register (403)'], ['ResultPanel', 'custom + UButton', "tone: 'success'|'error'|'info', icon, title, description, actions: ButtonProps[]", 'none', 'default', 'Pending, Verify, Reset request, Reset, Accept invite, Register (403)'],
['CodeBlock', 'custom (shiki) + UButton', 'code: string, lang: string, label?', 'none', 'none', 'Integration'], ['CodeBlock', 'custom (shiki) + UButton', 'code: string, lang: string, label?', 'none', 'none', 'Integration'],
['EndpointCard', 'UCard, UBadge, UTabs', "method: 'GET', path, description, examples: { fetch, curl, response }", 'none', 'none', 'Integration'], ['EndpointCard', 'UCard, UBadge, UTabs', "method: 'GET', path, description, examples: { fetch, curl, response }", 'none', 'none', 'Integration'],
['ErrorView', 'custom + UButton', "kind: 'not-found'|'error'", 'retry', 'none', 'Not found, error boundary'], ['ErrorView', 'custom + UButton', "kind: 'not-found'|'error'", 'retry', 'none', 'Not found, error boundary'],
@@ -136,6 +138,7 @@ class Component extends DCLogic {
M('Register', '/register', [['Default', 'Open instance'], ['Validation errors', 'Client rules fail'], ['Submitting', 'In flight'], ['Registration closed', '403'], ['Server error', '500 or network']]), M('Register', '/register', [['Default', 'Open instance'], ['Validation errors', 'Client rules fail'], ['Submitting', 'In flight'], ['Registration closed', '403'], ['Server error', '500 or network']]),
M('Pending', '/register/pending', [['Default', 'After registering (email known)'], ['Email unknown', 'After logging in unverified'], ['Confirm cancel', 'Cancel registration clicked'], ['Cancelling', 'DELETE in flight'], ['Cancelled', '200: /register with toast'], ['Already verified', '403: /home with toast']]), M('Pending', '/register/pending', [['Default', 'After registering (email known)'], ['Email unknown', 'After logging in unverified'], ['Confirm cancel', 'Cancel registration clicked'], ['Cancelling', 'DELETE in flight'], ['Cancelled', '200: /register with toast'], ['Already verified', '403: /home with toast']]),
M('Verify', '/register/validate?c=', [['Verifying', 'On load'], ['Success', '200: /home with toast'], ['Invalid or expired', '403'], ['No session', '401: inline log in, then retry'], ['Missing code', 'No c parameter']]), M('Verify', '/register/validate?c=', [['Verifying', 'On load'], ['Success', '200: /home with toast'], ['Invalid or expired', '403'], ['No session', '401: inline log in, then retry'], ['Missing code', 'No c parameter']]),
M('Accept invite', '/invite/accept?c=', [['Checking the link', 'On load: GET invite*'], ['Default', 'Valid, unused code; email read-only'], ['Validation errors', 'Register rules fail'], ['Submitting', 'In flight'], ['Username taken', '409'], ['Invalid or used', '404 or no c parameter'], ['Expired', '410: ask the person who invited you'], ['Server error', '500 or network'], ['Success', '200: logged in, /home with toast']]),
M('Forgot password', '/register/reset/request', [['Default', 'Page load'], ['Validation', 'Invalid email'], ['Submitting', 'In flight'], ['Sent', 'Any 200 (neutral copy)'], ['Too many attempts', '429*'], ['Server error', '500 or network']]), M('Forgot password', '/register/reset/request', [['Default', 'Page load'], ['Validation', 'Invalid email'], ['Submitting', 'In flight'], ['Sent', 'Any 200 (neutral copy)'], ['Too many attempts', '429*'], ['Server error', '500 or network']]),
M('Reset password', '/register/reset/validate', [['Default', 'c and email present'], ['Too short', 'Under 8 characters'], ['Mismatch', 'Confirm field differs'], ['Submitting', 'In flight'], ['Success', '200: /login?reason=password-changed'], ['Invalid or expired', '403'], ['Missing parameters', 'No c or no email']]), M('Reset password', '/register/reset/validate', [['Default', 'c and email present'], ['Too short', 'Under 8 characters'], ['Mismatch', 'Confirm field differs'], ['Submitting', 'In flight'], ['Success', '200: /login?reason=password-changed'], ['Invalid or expired', '403'], ['Missing parameters', 'No c or no email']]),
M('Home', '/home', [['Loading', 'List in flight (after 150 ms)'], ['Default', 'List loaded'], ['Empty', 'Zero articles'], ['Error', '500 or network']]), M('Home', '/home', [['Loading', 'List in flight (after 150 ms)'], ['Default', 'List loaded'], ['Empty', 'Zero articles'], ['Error', '500 or network']]),
@@ -153,6 +156,9 @@ class Component extends DCLogic {
['403', 'Any back-office call', 'Unverified: goes to /register/pending', 'Redirect'], ['403', 'Any back-office call', 'Unverified: goes to /register/pending', 'Redirect'],
['403', 'Verify', '"This verification link doesn\'t work." Offers Cancel registration and start over', 'ResultPanel'], ['403', 'Verify', '"This verification link doesn\'t work." Offers Cancel registration and start over', 'ResultPanel'],
['403', 'Cancel registration', '"Your account is already verified." Goes to /home', 'Toast'], ['403', 'Cancel registration', '"Your account is already verified." Goes to /home', 'Toast'],
['404', 'Accept invite', '"This invite link doesn\'t work." Offers Go to log in', 'ResultPanel'],
['409', 'Accept invite', '"That username is taken. Try another."', 'Field'],
['410', 'Accept invite', '"This invite has expired. Ask the person who invited you to send a new one."', 'ResultPanel'],
['403', 'Reset confirm', '"This reset link has expired." Offers Request a new link', 'ResultPanel'], ['403', 'Reset confirm', '"This reset link has expired." Offers Request a new link', 'ResultPanel'],
['404', 'Editor load', '"This article doesn\'t exist." Offers All articles', 'ErrorView'], ['404', 'Editor load', '"This article doesn\'t exist." Offers All articles', 'ErrorView'],
['404', 'Row or editor action', '"That article no longer exists." The row is removed', 'Toast'], ['404', 'Row or editor action', '"That article no longer exists." The row is removed', 'Toast'],
@@ -167,6 +173,7 @@ class Component extends DCLogic {
const pending = [ const pending = [
{ a: 'GET /v1/auth/me → User | 401', d: 'The session check at boot. The HttpOnly cookie can\'t be read from JS. Until this exists, the guard can call GET /v1/article/ and infer: 401 means logged out, but verified and unverified users can\'t be told apart.' }, { a: 'GET /v1/auth/me → User | 401', d: 'The session check at boot. The HttpOnly cookie can\'t be read from JS. Until this exists, the guard can call GET /v1/article/ and infer: 401 means logged out, but verified and unverified users can\'t be told apart.' },
{ a: 'GET /v1/auth/registration → { open }', d: 'Shows "Create the owner account" on /login. Without it, the link is hidden and /register is reachable by URL only.' }, { a: 'GET /v1/auth/registration → { open }', d: 'Shows "Create the owner account" on /login. Without it, the link is hidden and /register is reachable by URL only.' },
{ a: 'GET /v1/auth/invite?c=CODE → { email } | 404 | 410', d: 'Looks up the invite on load so the email can be shown and dead links are caught before the form. POST /v1/auth/invite/accept { code, username, password } returns 200 with the session cookie, 409 for a taken username, 404 or 410 as above. Neither exists yet.' },
{ a: '429 + Retry-After on /login, /password-reset', d: 'Drives the countdown state. The UI falls back to 60 s if the header is missing.' }, { a: '429 + Retry-After on /login, /password-reset', d: 'Drives the countdown state. The UI falls back to 60 s if the header is missing.' },
{ a: 'Serving /static/uploadedImages/*', d: 'The editor and preview are designed as if images load. Until they do, img tags show a broken image.' }, { a: 'Serving /static/uploadedImages/*', d: 'The editor and preview are designed as if images load. Until they do, img tags show a broken image.' },
{ a: 'Not supported (disabled or omitted)', d: 'Renaming a title (shown read-only, with an explanation in Details), resending the verification email (the pending page explains how to start over), changing the password while logged in, editing the profile or email, listing or deleting individual images, multiple users.' } { a: 'Not supported (disabled or omitted)', d: 'Renaming a title (shown read-only, with an explanation in Details), resending the verification email (the pending page explains how to start over), changing the password while logged in, editing the profile or email, listing or deleting individual images, multiple users.' }
+48 -5
View File
@@ -86,20 +86,32 @@ class Component extends DCLogic {
{ id: 6, t: 'Our first passive-house retrofit', on: true, c: '3 Apr 2026', u: '2 Jul 2026', imgs: 0 } { id: 6, t: 'Our first passive-house retrofit', on: true, c: '3 Apr 2026', u: '2 Jul 2026', imgs: 0 }
] ]
} }
people() {
return [
{ email: 'sam.oliveira@renew.example', st: 'pending', c: '27 Sep 2026' },
{ email: 'p.huber@gmail.com', st: 'expired', c: '3 Aug 2026' },
{ u: 'ines', st: 'accepted', c: '18 Jun 2026' },
{ u: 'jonas', st: 'accepted', c: '2 Apr 2026' },
{ u: 'marta', st: 'accepted', c: '12 Mar 2026', you: true }
]
}
flowDefs = [ flowDefs = [
{ key: 'first', name: 'First run', desc: 'Register, verify by email, write and publish.', steps: [['register', 'Create the owner account'], ['pending', 'Check your email'], ['verified', 'Verify from the email'], ['firstArticle', 'Write the first article'], ['published', 'Publish it']], hints: { register: 'Click "Create account".', pending: 'Use "Open the verification email" below.', verified: 'Click "Verify my account" in the email.', firstArticle: 'Click "New article", then "Create draft".', published: 'Click "Publish" in the editor header.' } }, { key: 'first', name: 'First run', desc: 'Register, verify by email, write and publish.', steps: [['register', 'Create the owner account'], ['pending', 'Check your email'], ['verified', 'Verify from the email'], ['firstArticle', 'Write the first article'], ['published', 'Publish it']], hints: { register: 'Click "Create account".', pending: 'Use "Open the verification email" below.', verified: 'Click "Verify my account" in the email.', firstArticle: 'Click "New article", then "Create draft".', published: 'Click "Publish" in the editor header.' } },
{ key: 'edit', name: 'Edit an article', desc: 'Log in, upload an image, save, unpublish.', steps: [['login', 'Log in'], ['openArticle', 'Open an article'], ['upload', 'Upload an image'], ['saved', 'Save'], ['unpublished', 'Unpublish']], hints: { login: 'Click "Log in".', openArticle: 'Go to Articles and click an online article.', upload: 'Click the image button at the end of the toolbar, then the drop area.', saved: 'Click "Save".', unpublished: 'Click "Unpublish".' } }, { key: 'edit', name: 'Edit an article', desc: 'Log in, upload an image, save, unpublish.', steps: [['login', 'Log in'], ['openArticle', 'Open an article'], ['upload', 'Upload an image'], ['saved', 'Save'], ['unpublished', 'Unpublish']], hints: { login: 'Click "Log in".', openArticle: 'Go to Articles and click an online article.', upload: 'Click the image button at the end of the toolbar, then the drop area.', saved: 'Click "Save".', unpublished: 'Click "Unpublish".' } },
{ key: 'reset', name: 'Forgot password', desc: 'Request a link, reset, log in.', steps: [['forgot', 'Ask for a reset link'], ['email', 'Open the email'], ['changed', 'Choose a new password'], ['login', 'Log in']], hints: { forgot: 'Click "Forgot password?", then "Send reset link".', email: 'Use "Open the reset email" below, then click its button.', changed: 'Click "Change password".', login: 'Click "Log in".' } }, { key: 'reset', name: 'Forgot password', desc: 'Request a link, reset, log in.', steps: [['forgot', 'Ask for a reset link'], ['email', 'Open the email'], ['changed', 'Choose a new password'], ['login', 'Log in']], hints: { forgot: 'Click "Forgot password?", then "Send reset link".', email: 'Use "Open the reset email" below, then click its button.', changed: 'Click "Change password".', login: 'Click "Log in".' } },
{ key: 'delete', name: 'Delete an article', desc: 'From the row menu, with confirmation.', steps: [['menu', 'Open the row menu'], ['confirm', 'Confirm the delete'], ['deleted', 'Article deleted']], hints: { menu: 'Click the ••• button on any row. On mobile, tap ⋮.', confirm: 'Choose "Delete…", then "Delete article".', deleted: '' } }, { key: 'delete', name: 'Delete an article', desc: 'From the row menu, with confirmation.', steps: [['menu', 'Open the row menu'], ['confirm', 'Confirm the delete'], ['deleted', 'Article deleted']], hints: { menu: 'Click the ••• button on any row. On mobile, tap ⋮.', confirm: 'Choose "Delete…", then "Delete article".', deleted: '' } },
{ key: 'invite', name: 'Invite a user', desc: 'Give someone their own login instead of sharing yours.', steps: [['users', 'Go to Users'], ['form', 'Open the invite form'], ['taken', 'Try an address that\'s taken'], ['sent', 'Send the invite']], hints: { users: 'Click "Users" in the sidebar. On mobile, open the menu first.', form: 'Click "Invite user".', taken: 'Click "Send invite". The form fills with an address that already has an account.', sent: 'Click "Send invite" again. This time it uses a new address.' } },
{ key: 'expiry', name: 'Session expiry mid-edit', desc: 'Your unsaved work survives a new login.', steps: [['edited', 'Make a change'], ['expire', 'Session expires'], ['relogin', 'Log in again'], ['restored', 'Back in the editor, changes kept']], hints: { edited: 'Click the article text to make a change.', expire: 'Use "Simulate session expiry" below.', relogin: 'Click "Log in".', restored: '' } } { key: 'expiry', name: 'Session expiry mid-edit', desc: 'Your unsaved work survives a new login.', steps: [['edited', 'Make a change'], ['expire', 'Session expires'], ['relogin', 'Log in again'], ['restored', 'Back in the editor, changes kept']], hints: { edited: 'Click the article text to make a change.', expire: 'Use "Simulate session expiry" below.', relogin: 'Click "Log in".', restored: '' } }
] ]
start(key) { start(key) {
const articles = this.base() const articles = this.base()
const common = { flow: key, done: [], modal: null, menu: null, busy: null, toasts: [], auth: {}, mnav: false, expired: false, copied: false, email: null, ed: null, cur: null } const users = key === 'first' ? this.people().slice(-1) : this.people()
const common = { users, flow: key, done: [], modal: null, menu: null, busy: null, toasts: [], auth: {}, mnav: false, expired: false, copied: false, email: null, ed: null, cur: null }
if (key === 'first') return { ...common, route: 'register', regOpen: true, articles: [] } if (key === 'first') return { ...common, route: 'register', regOpen: true, articles: [] }
if (key === 'edit') return { ...common, route: 'login', regOpen: false, articles } if (key === 'edit') return { ...common, route: 'login', regOpen: false, articles }
if (key === 'reset') return { ...common, route: 'login', regOpen: false, articles } if (key === 'reset') return { ...common, route: 'login', regOpen: false, articles }
if (key === 'delete') return { ...common, route: 'articles', regOpen: false, articles } if (key === 'delete') return { ...common, route: 'articles', regOpen: false, articles }
if (key === 'invite') return { ...common, route: 'home', regOpen: false, articles }
return { ...common, route: 'editor', regOpen: false, articles, cur: 1, ed: { status: 'online', save: 'saved', image: false, preview: false } } return { ...common, route: 'editor', regOpen: false, articles, cur: 1, ed: { status: 'online', save: 'saved', image: false, preview: false } }
} }
state = { device: 'desktop', mode: this.props.theme ?? 'light', hs: false, zoom: 1, emails: {}, ...this.start('first') } state = { device: 'desktop', mode: this.props.theme ?? 'light', hs: false, zoom: 1, emails: {}, ...this.start('first') }
@@ -174,8 +186,12 @@ class Component extends DCLogic {
} }
act(a) { act(a) {
const s = this.state const s = this.state
if (a === 'usermenu') return this.setState({ userMenu: !s.userMenu })
if (a && a.startsWith('theme-')) return this.setState({ mode: a.slice(6) })
if (s.userMenu) this.setState({ userMenu: false })
if (a === 'pf-reset') return this.setState({ pfReset: 'sent' })
if (a === 'mnav-close') return this.setState({ mnav: false }) if (a === 'mnav-close') return this.setState({ mnav: false })
if (a.startsWith('nav-')) return this.go(a.slice(4)) if (a.startsWith('nav-')) { const to = a.slice(4); if (to === 'users') this.mark('users'); return this.go(to) }
if (a === 'logout') { this.clearTimers(); this.setState({ route: 'login', auth: {}, mnav: false, menu: null, modal: null }); return this.toast('info', 'info', 'You\'re logged out', 'Log in again to keep working.') } if (a === 'logout') { this.clearTimers(); this.setState({ route: 'login', auth: {}, mnav: false, menu: null, modal: null }); return this.toast('info', 'info', 'You\'re logged out', 'Log in again to keep working.') }
if (s.modal) return this.modalAct(a) if (s.modal) return this.modalAct(a)
const r = s.route const r = s.route
@@ -221,6 +237,7 @@ class Component extends DCLogic {
} }
return return
} }
if (a === 'invite') { this.mark('form'); return this.setState({ modal: { type: 'invite', tries: 0 }, menu: null }) }
if (a === 'new' || a === 'empty' || (a === 'm-action' && r === 'home')) return this.setState({ modal: { type: 'new' }, menu: null }) if (a === 'new' || a === 'empty' || (a === 'm-action' && r === 'home')) return this.setState({ modal: { type: 'new' }, menu: null })
if (a === 'm-lead' && r !== 'editor') return this.setState({ mnav: true }) if (a === 'm-lead' && r !== 'editor') return this.setState({ mnav: true })
if (a.startsWith('open-')) return this.openEditor(Number(a.slice(5))) if (a.startsWith('open-')) return this.openEditor(Number(a.slice(5)))
@@ -279,6 +296,21 @@ class Component extends DCLogic {
} }
return return
} }
if (m.type === 'invite') {
if (a === 'modal-cancel' || a === 'modal-close') return close()
if (a === 'modal-confirm') {
const taken = !m.tries
const email = taken ? 'jonas@renew.example' : 'lea.martin@renew.example'
this.setState({ modal: { ...m, email, err: null, loading: true } })
this.later(() => {
if (taken) { this.setState({ modal: { ...m, email, tries: 1, loading: false, err: 'This address already has an account.' } }); return this.mark('taken') }
this.setState(st => ({ modal: null, users: [{ email, st: 'pending', c: 'Today', hl: true }, ...st.users.map(u => ({ ...u, hl: false }))] }))
this.mark('sent')
this.toast('success', 'circle-check', 'Invite sent', email + ' has 3 days to accept.')
}, 900)
}
return
}
if (m.type === 'delete') { if (m.type === 'delete') {
if (a === 'modal-cancel' || a === 'modal-close') return close() if (a === 'modal-cancel' || a === 'modal-close') return close()
if (a === 'modal-confirm') { if (a === 'modal-confirm') {
@@ -294,7 +326,14 @@ class Component extends DCLogic {
return return
} }
if (m.type === 'upload') { if (m.type === 'upload') {
if (m.state === 'crop' && typeof a === 'string') {
if (a === 'modal-cancel') return this.setState({ modal: { ...m, state: 'idle' } })
if (a.startsWith('crop-r-')) return this.setState({ modal: { ...m, ratio: +a.slice(7) } })
if (a.startsWith('crop-s-')) return this.setState({ modal: { ...m, size: +a.slice(7) } })
if (a === 'crop-reset') return this.setState({ modal: { ...m, ratio: 0, size: 1 } })
}
if (a === 'modal-cancel' || a === 'modal-close') return close() if (a === 'modal-cancel' || a === 'modal-close') return close()
if (a === 'upload-pick' && m.state === 'idle') return this.setState({ modal: { ...m, state: 'crop', ratio: 0, size: 1 } })
if ((a === 'upload-pick' || a === 'modal-confirm') && m.state !== 'uploading') { if ((a === 'upload-pick' || a === 'modal-confirm') && m.state !== 'uploading') {
this.setState({ modal: { ...m, state: 'uploading' } }) this.setState({ modal: { ...m, state: 'uploading' } })
this.later(() => { this.later(() => {
@@ -331,10 +370,12 @@ class Component extends DCLogic {
const T = (name, crumb) => ({ nav: name, crumbs: crumb }) const T = (name, crumb) => ({ nav: name, crumbs: crumb })
if (s.route === 'home') return { kind: 'home', ...T('home', ['Home']), mTitle: 'Home', mAction: 'plus', home: arts.length ? { sub: 'Here\'s where things stand on your site.', stats: [{ n: String(counts[0]), l: 'articles' }, { n: String(counts[1]), l: 'online' }, { n: String(counts[2]), l: 'drafts' }], recent: arts.slice(0, 5).map(a => ({ ...a, draft: !a.on })) } : { sub: 'Welcome to RenewCMS.', empty: true }, modal: this.modalS() } if (s.route === 'home') return { kind: 'home', ...T('home', ['Home']), mTitle: 'Home', mAction: 'plus', home: arts.length ? { sub: 'Here\'s where things stand on your site.', stats: [{ n: String(counts[0]), l: 'articles' }, { n: String(counts[1]), l: 'online' }, { n: String(counts[2]), l: 'drafts' }], recent: arts.slice(0, 5).map(a => ({ ...a, draft: !a.on })) } : { sub: 'Welcome to RenewCMS.', empty: true }, modal: this.modalS() }
if (s.route === 'articles') return { kind: 'articles', ...T('articles', ['Articles']), mTitle: 'Articles', list: { counts, rows: arts.map(a => ({ ...a, menu: s.menu === a.id, busy: s.busy === a.id ? (a.on ? 'Unpublishing…' : 'Publishing…') : null })), empty: arts.length ? null : { icon: 'file-text', title: 'No articles yet', text: 'Write your first one. It stays a draft until you publish it.', action: 'New article', primary: true } }, modal: this.modalS() } if (s.route === 'articles') return { kind: 'articles', ...T('articles', ['Articles']), mTitle: 'Articles', list: { counts, rows: arts.map(a => ({ ...a, menu: s.menu === a.id, busy: s.busy === a.id ? (a.on ? 'Unpublishing…' : 'Publishing…') : null })), empty: arts.length ? null : { icon: 'file-text', title: 'No articles yet', text: 'Write your first one. It stays a draft until you publish it.', action: 'New article', primary: true } }, modal: this.modalS() }
if (s.route === 'users') return { kind: 'users', ...T('users', ['Users']), mTitle: 'Users', users: { rows: s.users, only: s.users.length === 1 }, modal: this.modalS() }
if (s.route === 'profile') return { kind: 'profile', ...T('profile', ['Profile']), mTitle: 'Profile', pf: { reset: s.pfReset } }
if (s.route === 'integration') return { kind: 'integration', ...T('integration', ['Integration']), mTitle: 'Integration', copied: s.copied } if (s.route === 'integration') return { kind: 'integration', ...T('integration', ['Integration']), mTitle: 'Integration', copied: s.copied }
if (s.route === 'editor') { if (s.route === 'editor') {
const a = this.art(s.cur) || {}, e = s.ed || {} const a = this.art(s.cur) || {}, e = s.ed || {}
return { kind: 'editor', ...T('articles', ['Articles', a.t]), mTitle: 'Edit article', mLead: 'arrow-left', mAction: 'ellipsis', ed: { ...e, title: a.t, imgs: (a.imgs || 0) + (e.image ? 1 : 0) }, modal: this.modalS() } return { kind: 'editor', ...T('articles', ['Articles', a.t]), mTitle: 'Edit article', mLead: 'arrow-left', mAction: 'trash-2', ed: { ...e, title: a.t, imgs: (a.imgs || 0) + (e.image ? 1 : 0) }, modal: this.modalS() }
} }
return { kind: 'home', home: { sub: '' } } return { kind: 'home', home: { sub: '' } }
} }
@@ -342,11 +383,13 @@ class Component extends DCLogic {
const m = this.state.modal const m = this.state.modal
if (!m) return null if (!m) return null
if (m.type === 'new') return { title: 'New article', desc: 'It\'s saved as a draft. Titles can\'t be changed later, so check it now.', close: true, cancel: 'Cancel', confirm: m.loading ? 'Creating…' : 'Create draft', loading: m.loading, wide: true, fields: [{ label: 'Title', value: 'Choosing tiles for a small bathroom', count: '35 / 200', help: '3 to 200 characters.' }, { label: 'First paragraph', value: 'Small rooms show every grout line, so we start with the floor and work up.', area: true, help: 'You can format it and add images in the editor.' }] } if (m.type === 'new') return { title: 'New article', desc: 'It\'s saved as a draft. Titles can\'t be changed later, so check it now.', close: true, cancel: 'Cancel', confirm: m.loading ? 'Creating…' : 'Create draft', loading: m.loading, wide: true, fields: [{ label: 'Title', value: 'Choosing tiles for a small bathroom', count: '35 / 200', help: '3 to 200 characters.' }, { label: 'First paragraph', value: 'Small rooms show every grout line, so we start with the floor and work up.', area: true, help: 'You can format it and add images in the editor.' }] }
if (m.type === 'invite') return { title: 'Invite a user', desc: 'We\'ll email them a link to choose a username and password. The link expires after 3 days.', close: true, cancel: 'Cancel', confirm: m.loading ? 'Sending…' : 'Send invite', loading: m.loading, fields: [m.email ? { label: 'Email', value: m.email, err: m.err } : { label: 'Email', ph: 'name@example.com', focus: true }] }
if (m.type === 'delete') { if (m.type === 'delete') {
const a = this.art(m.id) || { t: '', imgs: 0 } const a = this.art(m.id) || { t: '', imgs: 0 }
const imgs = a.imgs === 0 ? '' : a.imgs === 1 ? ' and its image' : ' and its ' + a.imgs + ' images' const imgs = a.imgs === 0 ? '' : a.imgs === 1 ? ' and its image' : ' and its ' + a.imgs + ' images'
return { title: 'Delete this article?', desc: '"' + a.t + '"' + imgs + ' will be deleted. This can\'t be undone.', cancel: 'Cancel', confirm: m.loading ? 'Deleting…' : 'Delete article', tone: 'danger', loading: m.loading } return { title: 'Delete this article?', desc: '"' + a.t + '"' + imgs + ' will be deleted. This can\'t be undone.', cancel: 'Cancel', confirm: m.loading ? 'Deleting…' : 'Delete article', tone: 'danger', loading: m.loading }
} }
if (m.type === 'upload' && m.state === 'crop') return { title: 'Crop and resize', desc: 'north-wall.jpg · 3.9 MB', close: true, crop: { ratio: m.ratio, size: m.size }, cancel: 'Choose another file', confirm: 'Upload image' }
if (m.type === 'upload') return { title: 'Add an image', close: true, upload: { state: m.state }, cancel: m.state === 'uploading' ? 'Cancel upload' : 'Cancel' } if (m.type === 'upload') return { title: 'Add an image', close: true, upload: { state: m.state }, cancel: m.state === 'uploading' ? 'Cancel upload' : 'Cancel' }
if (m.type === 'leave') { const a = this.art(this.state.cur) || {}; return { title: 'Leave without saving?', desc: 'Your changes to "' + a.t + '" haven\'t been saved.', cancel: 'Discard changes', confirm: 'Keep editing' } } if (m.type === 'leave') { const a = this.art(this.state.cur) || {}; return { title: 'Leave without saving?', desc: 'Your changes to "' + a.t + '" haven\'t been saved.', cancel: 'Discard changes', confirm: 'Keep editing' } }
return null return null
@@ -379,14 +422,14 @@ class Component extends DCLogic {
const modes = [['system', 'System'], ['light', 'Light'], ['dark', 'Dark']].map(([k, label]) => { const on = s.mode === k; return { label, on, bg: on ? 'var(--ui-primary)' : 'transparent', fg: on ? 'var(--ui-bg)' : 'var(--ui-text-toned)', pick: () => this.setState({ mode: k }) } }) const modes = [['system', 'System'], ['light', 'Light'], ['dark', 'Dark']].map(([k, label]) => { const on = s.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 [dw, dh] = mobile ? [390, 844] : [1440, 900] const [dw, dh] = mobile ? [390, 844] : [1440, 900]
const navKey = s.route === 'editor' ? 'articles' : s.route const navKey = s.route === 'editor' ? 'articles' : s.route
const mnavItems = [['nav-home', 'house', 'Home', 'home'], ['nav-articles', 'file-text', 'Articles', 'articles'], ['nav-integration', 'plug', 'Integration', 'integration'], ['logout', 'log-out', 'Log out', '']].map(([act, icon, t, k]) => ({ act, icon, t, bg: k && k === navKey ? 'var(--rc-sand)' : 'transparent', fg: k && k === navKey ? '#111111' : 'var(--ui-text-toned)' })) const mnavItems = [['nav-home', 'house', 'Home', 'home'], ['nav-articles', 'file-text', 'Articles', 'articles'], ['nav-users', 'users', 'Users', 'users'], ['nav-integration', 'plug', 'Integration', 'integration'], ['logout', 'log-out', 'Log out', '']].map(([act, icon, t, k]) => ({ act, icon, t, bg: k && k === navKey ? 'var(--rc-sand)' : 'transparent', fg: k && k === navKey ? '#111111' : 'var(--ui-text-toned)' }))
const toasts = s.toasts.map(t => ({ ...t, fg: 'var(--ui-' + t.tone + ')' })) const toasts = s.toasts.map(t => ({ ...t, fg: 'var(--ui-' + t.tone + ')' }))
return { return {
rootRef: this.rootRef, stageRef: this.stageRef, rootRef: this.rootRef, stageRef: this.stageRef,
devices: devs, modes, flows, hint, tools, devices: devs, modes, flows, hint, tools,
hs: s.hs, hsClass: s.hs ? 'hs' : '', hsJust: s.hs ? 'flex-end' : 'flex-start', hsBg: s.hs ? 'var(--ui-primary)' : 'var(--ui-bg-accented)', toggleHs: () => this.setState({ hs: !s.hs }), hs: s.hs, hsClass: s.hs ? 'hs' : '', hsJust: s.hs ? 'flex-end' : 'flex-start', hsBg: s.hs ? 'var(--ui-primary)' : 'var(--ui-bg-accented)', toggleHs: () => this.setState({ hs: !s.hs }),
mobile, isAuth, isApp, isEmail, mobile, isAuth, isApp, isEmail,
authS: isAuth ? this.authS() : {}, appS: isApp ? this.appS() : {}, authS: isAuth ? this.authS() : {}, appS: isApp ? { ...this.appS(), userMenu: s.userMenu, mode: s.mode } : {},
authBg: mobile ? 'var(--ui-bg)' : 'var(--ui-bg-muted)', authTop: mobile ? '40px' : '108px', authBg: mobile ? 'var(--ui-bg)' : 'var(--ui-bg-muted)', authTop: mobile ? '40px' : '108px',
emailHtml: isEmail ? this.emailHtml() : '', emailSubject: s.email === 'reset' ? 'Reset your RenewCMS password' : 'Verify your RenewCMS account', emailHtml: isEmail ? this.emailHtml() : '', emailSubject: s.email === 'reset' ? 'Reset your RenewCMS password' : 'Verify your RenewCMS account',
devW: dw + 'px', devH: dh + 'px', zoom: s.zoom, boxW: Math.round(dw * s.zoom) + 'px', boxH: Math.round(dh * s.zoom) + 'px', devW: dw + 'px', devH: dh + 'px', zoom: s.zoom, boxW: Math.round(dw * s.zoom) + 'px', boxH: Math.round(dh * s.zoom) + 'px',
@@ -18,7 +18,7 @@
<div style="display:flex;align-items:flex-end;gap:32px;max-width:1400px"> <div style="display:flex;align-items:flex-end;gap:32px;max-width:1400px">
<div style="flex:1;display:flex;flex-direction:column;gap:10px"> <div style="flex:1;display:flex;flex-direction:column;gap:10px">
<h1 style="margin:0;font:600 36px/44px 'IBM Plex Sans',sans-serif;letter-spacing:-0.02em;color:var(--ui-text-highlighted)">Screens: public and auth</h1> <h1 style="margin:0;font:600 36px/44px 'IBM Plex Sans',sans-serif;letter-spacing:-0.02em;color:var(--ui-text-highlighted)">Screens: public and auth</h1>
<p style="margin:0;max-width:880px;font-size:16px;line-height:26px;color:var(--ui-text-toned);text-wrap:pretty">Every state of the six public routes, at 1440 px (shown at 50%) and 390 px (shown at 75%). Use the switch on the right to see all of them in dark mode. Final copy is written into each state. The back-office screens and global states are on <a href="RenewCMS Screens Back-office.dc.html">the back-office board</a>, and the emails are on <a href="RenewCMS Emails.dc.html">the email board</a>.</p> <p style="margin:0;max-width:880px;font-size:16px;line-height:26px;color:var(--ui-text-toned);text-wrap:pretty">Every state of the seven public routes, at 1440 px (shown at 50%) and 390 px (shown at 75%). Use the switch on the right to see all of them in dark mode. Final copy is written into each state. The back-office screens and global states are on <a href="RenewCMS Screens Back-office.dc.html">the back-office board</a>, and the emails are on <a href="RenewCMS Emails.dc.html">the email board</a>.</p>
</div> </div>
<div role="radiogroup" aria-label="Theme" style="display:flex;border:1px solid var(--ui-border-accented);background:var(--ui-bg)"> <div role="radiogroup" aria-label="Theme" style="display:flex;border:1px solid var(--ui-border-accented);background:var(--ui-bg)">
<sc-for list="{{ modes }}" as="m" hint-placeholder-count="3"> <sc-for list="{{ modes }}" as="m" hint-placeholder-count="3">
@@ -112,6 +112,8 @@ class Component extends DCLogic {
const loginF = (u, p) => [U(u), P({ link: 'Forgot password?', ...p })] const loginF = (u, p) => [U(u), P({ link: 'Forgot password?', ...p })]
const reg = { title: 'Create the owner account', desc: 'This creates the single admin account for this site. Once it\'s verified, registration closes.', submit: { t: 'Create account' }, footer: { pre: 'Already set up?', link: 'Log in' } } const reg = { title: 'Create the owner account', desc: 'This creates the single admin account for this site. Once it\'s verified, registration closes.', submit: { t: 'Create account' }, footer: { pre: 'Already set up?', link: 'Log in' } }
const regF = (u, e, p) => [U({ ph: 'e.g. marta', count: ((u && u.value) || '').length + ' / 20', help: 'Letters and numbers, 3 to 20 characters. You\'ll use it to log in.', ...u }), E({ help: 'We\'ll send a verification link here.', ...e }), P({ hints: pwHint('unmet'), ...p })] const regF = (u, e, p) => [U({ ph: 'e.g. marta', count: ((u && u.value) || '').length + ' / 20', help: 'Letters and numbers, 3 to 20 characters. You\'ll use it to log in.', ...u }), E({ help: 'We\'ll send a verification link here.', ...e }), P({ hints: pwHint('unmet'), ...p })]
const inv = { title: 'Accept your invite', desc: 'Choose a username and password to finish setting up your account.', submit: { t: 'Accept invite' }, footer: { pre: 'Already have an account?', link: 'Log in' } }
const invF = (u, p) => [E({ value: 'lea.martin@renew.example', ro: true, help: 'From your invitation.' }), U({ ph: 'e.g. lea', count: ((u && u.value) || '').length + ' / 20', help: 'Letters and numbers, 3 to 20 characters. You\'ll use it to log in.', ...u }), P({ hints: pwHint('unmet'), ...p })]
const pendingResult = email => ({ tone: 'success', icon: 'mail-check', title: 'Check your email', text: email ? 'We sent a verification link to ' + email + '. It expires in 2 hours.' : 'We sent a verification link to the email you registered with. It expires in 2 hours.', note: 'Opened it on another device? That works too; 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.', actions: [{ t: 'Log out', secondary: true }, { t: 'Cancel registration', secondary: true }] }) const pendingResult = email => ({ tone: 'success', icon: 'mail-check', title: 'Check your email', text: email ? 'We sent a verification link to ' + email + '. It expires in 2 hours.' : 'We sent a verification link to the email you registered with. It expires in 2 hours.', note: 'Opened it on another device? That works too; 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.', actions: [{ t: 'Log out', secondary: true }, { t: 'Cancel registration', secondary: true }] })
const cancelDialog = (loading) => ({ title: 'Cancel your registration?', text: 'Your account will be deleted. You can register again with the same or a different email.', confirm: loading ? 'Cancelling…' : 'Cancel registration', cancel: 'Keep my account' }) const cancelDialog = (loading) => ({ title: 'Cancel your registration?', text: 'Your account will be deleted. You can register again with the same or a different email.', confirm: loading ? 'Cancelling…' : 'Cancel registration', cancel: 'Keep my account' })
const reqBase = { title: 'Reset your password', desc: 'Enter the email for your account and we\'ll send you a link to choose a new password.', submit: { t: 'Send reset link' }, below: 'Back to log in' } const reqBase = { title: 'Reset your password', desc: 'Enter the email for your account and we\'ll send you a link to choose a new password.', submit: { t: 'Send reset link' }, below: 'Back to log in' }
@@ -154,6 +156,18 @@ class Component extends DCLogic {
{ name: 'No session, retrying', trigger: 'Logged in inline. Now verifying.', spinner: 'Verifying your account…' }, { name: 'No session, retrying', trigger: 'Logged in inline. Now verifying.', spinner: 'Verifying your account…' },
{ name: 'Missing code', trigger: 'The link has no ?c= parameter. No request is made.', result: { tone: 'error', icon: 'link-2-off', title: 'This link is incomplete', text: 'The verification code is missing. Open the link from your email again, or copy the full address into your browser.', actions: [{ t: 'Go to log in', secondary: true }] } } { name: 'Missing code', trigger: 'The link has no ?c= parameter. No request is made.', result: { tone: 'error', icon: 'link-2-off', title: 'This link is incomplete', text: 'The verification code is missing. Open the link from your email again, or copy the full address into your browser.', actions: [{ t: 'Go to log in', secondary: true }] } }
] }, ] },
{ label: 'Accept invite', title: 'Accept invite', route: '/invite/accept?c=CODE', api: 'GET /v1/auth/invite?c= (pending) · POST /v1/auth/invite/accept (pending)', note: 'Opened from the invitation email. The link carries only the code, so the invited email is looked up on load and shown read-only. Username and password follow the Register rules, including PasswordStrengthHint. On success the person is logged in and sent to /home with a toast; they are already verified because the invite went to their email.', states: [
{ name: 'Checking the link', trigger: 'On load, while the invite is looked up.', spinner: 'Checking your invite…' },
{ ...inv, name: 'Default', trigger: 'The code is valid and unused.', fields: invF({}, {}) },
{ ...inv, name: 'Validation errors', trigger: 'Checked on blur and on submit, using the same rules as Register. Nothing is sent.', fields: invF({ value: 'ma', err: 'Use 3 to 20 characters.', countErr: true, help: '' }, { value: 'lime', hints: pwHint('err') }) },
{ ...inv, name: 'Filled, valid', trigger: 'Every rule is met and the checklist item turns green.', fields: invF({ value: 'lea' }, { value: 'limewash2026', shown: true, hints: pwHint('met') }) },
{ ...inv, name: 'Submitting', trigger: 'Fields and button are disabled.', fields: invF({ value: 'lea' }, { value: 'limewash2026', hints: pwHint('met') }), submit: { t: 'Creating account…', loading: true } },
{ ...inv, name: 'Username taken (409)', trigger: 'Another user has that username. The value is kept and the field gets focus.', fields: invF({ value: 'marta', err: 'That username is taken. Try another.', focus: true, help: '' }, { value: 'limewash2026', hints: pwHint('met') }) },
{ name: 'Invalid or used link (404)', trigger: 'The code is wrong, was already accepted, or is missing from the URL. No form is shown.', result: { tone: 'error', icon: 'link-2-off', title: 'This invite link doesn\'t work', text: 'It may be incomplete, or it may already have been used. If you already set up your account, log in instead.', note: 'Open the link from your email again, or copy the full address into your browser.', actions: [{ t: 'Go to log in' }] } },
{ name: 'Expired link (410)', trigger: 'The invite is older than 3 days.', result: { tone: 'error', icon: 'clock', title: 'This invite has expired', text: 'Invites work once, for 3 days. Ask the person who invited you to send a new one.', actions: [{ t: 'Go to log in', secondary: true }] } },
{ ...inv, name: 'Server error', trigger: 'A 500 or no response. The values are kept.', notice: { tone: 'error', icon: 'circle-x', title: 'Couldn\'t create the account', text: 'Something went wrong on the server. Try again in a moment.' }, fields: invF({ value: 'lea' }, { value: 'limewash2026', hints: pwHint('met') }) },
{ name: 'Success', trigger: '200 sets the session cookie → /home after 800 ms, with a toast. No verification step.', result: { tone: 'success', icon: 'circle-check', title: 'Your account is ready', text: 'Taking you to your dashboard…', actions: [] }, toast: toast('success', 'circle-check', 'Welcome to RenewCMS', 'You\'re logged in as lea.') }
] },
{ label: 'Forgot password', title: 'Forgot password', route: '/register/reset/request', api: 'POST /v1/auth/password-reset', note: 'The sent state reads the same whether or not the email exists, so the page doesn\'t reveal which emails have accounts.', states: [ { label: 'Forgot password', title: 'Forgot password', route: '/register/reset/request', api: 'POST /v1/auth/password-reset', note: 'The sent state reads the same whether or not the email exists, so the page doesn\'t reveal which emails have accounts.', states: [
{ ...reqBase, name: 'Default', trigger: 'From "Forgot password?" on log in.', fields: [E()] }, { ...reqBase, name: 'Default', trigger: 'From "Forgot password?" on log in.', fields: [E()] },
{ ...reqBase, name: 'Validation error', trigger: 'Invalid email on submit. Nothing is sent.', fields: [E({ value: 'marta@renew', err: 'Enter a full email address, like name@example.com.' })] }, { ...reqBase, name: 'Validation error', trigger: 'Invalid email on submit. Nothing is sent.', fields: [E({ value: 'marta@renew', err: 'Enter a full email address, like name@example.com.' })] },
@@ -39,12 +39,13 @@
<div style="display:flex;flex-direction:column;gap:12px"> <div style="display:flex;flex-direction:column;gap:12px">
<div style="display:flex;flex-direction:column;gap:2px;max-width:1040px"><span style="font:600 16px/24px 'IBM Plex Sans',sans-serif;color:var(--ui-text-highlighted)">{{ st.name }}</span><span style="font-size:13px;color:var(--ui-text-muted)">{{ st.trigger }}</span></div> <div style="display:flex;flex-direction:column;gap:2px;max-width:1040px"><span style="font:600 16px/24px 'IBM Plex Sans',sans-serif;color:var(--ui-text-highlighted)">{{ st.name }}</span><span style="font-size:13px;color:var(--ui-text-muted)">{{ st.trigger }}</span></div>
<div style="display:flex;gap:24px;align-items:flex-start"> <div style="display:flex;gap:24px;align-items:flex-start">
<div style="width:720px;height:450px;overflow:hidden;border:1px solid var(--ui-border);flex-shrink:0"><div style="width:1440px;height:900px;zoom:0.5"><dc-import name="AppFrame" s="{{ st }}" mobile="{{ false }}" hint-size="1440px,900px"></dc-import></div></div> <div style="width:720px;height:450px;overflow:hidden;border:1px solid var(--ui-border);flex-shrink:0"><div style="width:1440px;height:900px;zoom:0.5"><sc-if value="{{ st.notMedia }}"><dc-import name="AppFrame" s="{{ st }}" mobile="{{ false }}" hint-size="1440px,900px"></dc-import></sc-if><sc-if value="{{ st.isMedia }}"><dc-import name="MediaFrame" s="{{ st }}" mobile="{{ false }}" hint-size="1440px,900px"></dc-import></sc-if></div></div>
<div style="width:293px;height:633px;overflow:hidden;border:1px solid var(--ui-border);flex-shrink:0"><div style="width:390px;height:844px;zoom:0.75"><dc-import name="AppFrame" s="{{ st.m }}" mobile="{{ true }}" hint-size="390px,844px"></dc-import></div></div> <div style="width:293px;height:633px;overflow:hidden;border:1px solid var(--ui-border);flex-shrink:0"><div style="width:390px;height:844px;zoom:0.75"><sc-if value="{{ st.notMedia }}"><dc-import name="AppFrame" s="{{ st.m }}" mobile="{{ true }}" hint-size="390px,844px"></dc-import></sc-if><sc-if value="{{ st.isMedia }}"><dc-import name="MediaFrame" s="{{ st.m }}" mobile="{{ true }}" hint-size="390px,844px"></dc-import></sc-if></div></div>
</div> </div>
</div> </div>
</sc-for> </sc-for>
</div> </div>
<sc-if value="{{ g.table }}"><div style="display:flex;flex-direction:column;gap:8px;max-width:1240px"><span style="font:600 16px/24px 'IBM Plex Sans',sans-serif;color:var(--ui-text-highlighted)">{{ g.tableTitle }}</span><div style="background:var(--ui-bg);border:1px solid var(--ui-border)"><div style="display:grid;grid-template-columns:90px 240px minmax(0,1fr);padding:8px 12px;background:var(--ui-bg-elevated);color:var(--ui-text-muted);font-weight:500"><span>Status</span><span>Where</span><span>Copy</span></div><sc-for list="{{ g.table }}" as="r" hint-placeholder-count="3"><div style="display:grid;grid-template-columns:90px 240px minmax(0,1fr);gap:0;padding:10px 12px;border-top:1px solid var(--ui-border);line-height:20px"><span style="font:500 13px 'IBM Plex Mono',monospace;color:var(--ui-text-highlighted)">{{ r.a }}</span><span style="color:var(--ui-text-toned);padding-right:16px">{{ r.b }}</span><span style="color:var(--ui-text-highlighted);text-wrap:pretty">{{ r.c }}</span></div></sc-for></div></div></sc-if>
</section> </section>
</sc-for> </sc-for>
@@ -93,8 +94,43 @@ class Component extends DCLogic {
const nf = (title, body, extra = {}) => [{ label: 'Title', value: title, count: [...title].length + ' / 200', ...(extra.t || {}) }, { label: 'First paragraph', value: body, area: true, ...(extra.b || {}) }] const nf = (title, body, extra = {}) => [{ label: 'Title', value: title, count: [...title].length + ' / 200', ...(extra.t || {}) }, { label: 'First paragraph', value: body, area: true, ...(extra.b || {}) }]
const ed = { kind: 'editor', nav: 'articles', crumbs: ['Articles', 'How we price a bathroom renovation'], mTitle: 'Edit article', mLead: 'arrow-left', mAction: 'ellipsis' } const ed = { kind: 'editor', nav: 'articles', crumbs: ['Articles', 'How we price a bathroom renovation'], mTitle: 'Edit article', mLead: 'arrow-left', mAction: 'ellipsis' }
const E = (o = {}, extra = {}) => withM({ ...ed, ...extra, ed: { status: 'draft', save: 'saved', ...o } }) const E = (o = {}, extra = {}) => withM({ ...ed, ...extra, ed: { status: 'draft', save: 'saved', ...o } })
const cropM = crop => ({ title: 'Crop and resize', desc: 'north-wall.jpg · 3.9 MB', close: true, crop, cancel: 'Choose another file', confirm: 'Upload image' })
const del = (loading, err) => ({ title: 'Delete this article?', desc: '"Winter checklist for timber windows" and its 3 images will be deleted. This can\'t be undone.', cancel: 'Cancel', confirm: loading ? 'Deleting…' : 'Delete article', tone: 'danger', loading, notice: err }) const del = (loading, err) => ({ title: 'Delete this article?', desc: '"Winter checklist for timber windows" and its 3 images will be deleted. This can\'t be undone.', cancel: 'Cancel', confirm: loading ? 'Deleting…' : 'Delete article', tone: 'danger', loading, notice: err })
return [ const people = [
{ email: 'sam.oliveira@renew.example', role: 'admin', st: 'pending', c: '27 Sep 2026' },
{ email: 'p.huber@gmail.com', display: 'Paul Huber', role: 'admin', st: 'expired', c: '3 Aug 2026' },
{ email: 'ines.duarte@renew.example', display: 'Inès Duarte', role: 'admin', st: 'accepted', c: '18 Jun 2026' },
{ email: 'jonas@renew.example', role: 'admin', st: 'accepted', c: '2 Apr 2026' },
{ email: 'marta@renew.example', role: 'owner', st: 'accepted', c: '12 Mar 2026', you: true }
]
const U = (o = {}) => ({ kind: 'users', nav: 'users', crumbs: ['Users'], mTitle: 'Users', ...o, users: { rows: people, ...(o.users || {}) } })
const inv = (o = {}) => ({ title: 'Invite a user', desc: 'We\'ll email them a link to choose a username and password. The link expires after 3 days.', close: true, cancel: 'Cancel', confirm: 'Send invite', ...o, fields: o.fields || [{ label: 'Email', ph: 'name@example.com', focus: true }] })
const invF = (value, extra = {}) => [{ label: 'Email', value, ...extra }]
const P = (pf = {}, o = {}) => withM({ kind: 'profile', nav: 'profile', crumbs: ['Profile'], mTitle: 'Profile', ...o, pf })
const dname = 'Marta Alves'
const MS = (o) => ({ frame: 'MediaFrame', isMedia: true, ...o, m: { frame: 'MediaFrame', isMedia: true, ...o } })
const Mp = (o) => MS({ kind: 'page', ...o })
const TT = (tone, icon, title, text, action) => [tone, icon, title, text, action]
const upT = (rows, o = {}) => ({ title: 'Uploading 6 images', sub: '2 of 6 done', rows, ...o })
const rowOk = (n, sz, im) => ({ n, sz, st: 'ok', im })
const rowDup = { n: 'floorboards-2.jpg', sz: '2.4 MB', st: 'dup', im: 12, msg: 'Same as "floorboards.jpg", uploaded 14 Jun 2026 by Inès Duarte.' }
const rowRej = { n: 'scan.tif', sz: '14.2 MB', st: 'rej', title: 'scan.tif is 14.2 MB', msg: 'Images can be up to 10 MB. Use a PNG, JPEG, WEBP or SVG image.' }
const rowFail = { n: 'roof.png', sz: '1.4 MB', st: 'fail', im: 10 }
const gone = [1, 2, 3, 4, 5, 6, 7, 9, 10, 11, 12]
const pk = (o = {}, x = {}) => MS({ kind: 'picker', picker: true, pk: { tab: 'Library', ...o }, ...x })
const TB = { neutral: 'var(--ui-bg-muted)', success: 'var(--rc-success-soft)', info: 'var(--rc-info-soft)', warning: 'var(--rc-warning-soft)', error: 'var(--rc-error-soft)' }
const B = (t, kind, icon, dis) => ({ t, icon, bg: kind === 'primary' ? 'var(--ui-primary)' : 'var(--ui-bg)', fg: kind === 'primary' ? 'var(--ui-bg)' : 'var(--ui-text-highlighted)', bd: kind === 'primary' ? 'var(--ui-primary)' : 'var(--ui-border-accented)', op: dis ? '0.4' : '1' })
const UPD = (o) => { const tone = o.tone || 'neutral'; return { v: 'v2.2.0-beta', focus: 'none', ...o, fg: tone === 'neutral' ? 'var(--ui-text-toned)' : 'var(--ui-' + tone + ')', bg: TB[tone], bar: o.pct !== undefined || !!o.indet, barW: o.indet ? '35%' : (o.pct || 0) + '%', barL: o.indet ? '30%' : '0', pct: o.indet ? undefined : o.pct } }
const NOTES = (open) => ({ open, chev: open ? 'chevron-down' : 'chevron-right', ver: '2.3.0', date: 'Released 24 Sep 2026', items: [{ t: 'Images upload faster, and large images no longer stall.' }, { t: 'Fixed a problem where a draft could show an old title after saving.' }, { t: 'Small improvements to the Users page.' }] })
const SU = (o, extra) => withM({ kind: 'settings', nav: 'settings', crumbs: ['Settings'], mTitle: 'Settings', ...extra, upd: UPD(o) })
const LAST = 'Last checked today at 09:41'
const RESTART_FOOT = 'Restart takes about 10 seconds. Your site is unavailable while it restarts.'
const bn = (icon, title, text) => ({ icon, title, text, btn: 'Go to Settings', fg: 'var(--ui-info)', bg: 'var(--rc-info-soft)' })
const cmdLine = 'renewcms enable-browser-updates'
const notPrep = (copied) => ({ icon: 'info', tone: 'info', title: 'Version 2.3.0 is available', text: 'This site can\'t update itself from the browser yet. Whoever manages your server can set it up once, or update RenewCMS for you.', meta: LAST, cmd: { line: cmdLine, t: copied ? 'Copied' : 'Copy', icon: copied ? 'check' : 'copy', fg: copied ? 'var(--ui-success)' : 'var(--ui-text-highlighted)', note: 'They run this once on the server. After that, Update and Restart appear here.' }, link: 'How to update' })
const restartModal = (o) => ({ title: 'Restart the site?', desc: 'Your site will be unavailable for about 10 seconds. This page reloads on its own when the site is back. Save anything you\'re editing first.', cancel: 'Cancel', confirm: 'Restart site', ...o })
const installModal = (o) => ({ title: 'Restart to finish the update?', desc: 'RenewCMS will install version 2.3.0 and restart. Your site will be unavailable for about 10 seconds. This page reloads on its own when the site is back. Save anything you\'re editing first.', cancel: 'Restart later', confirm: 'Restart now', ...o })
return this.finish([
{ label: 'Boot', title: 'App boot', route: 'any route, first load', api: 'GET /v1/auth/me (pending)', note: 'While the session is checked, the shell renders with skeletons, never a spinner. The possible outcomes are: 200 with a verified user, which renders the route; 200 with an unverified user, which goes to /register/pending; and 401, which goes to /login?redirect=<path>. Public routes skip this check.', states: [ { label: 'Boot', title: 'App boot', route: 'any route, first load', api: 'GET /v1/auth/me (pending)', note: 'While the session is checked, the shell renders with skeletons, never a spinner. The possible outcomes are: 200 with a verified user, which renders the route; 200 with an unverified user, which goes to /register/pending; and 401, which goes to /login?redirect=<path>. Public routes skip this check.', states: [
withM({ ...home, name: 'Checking session', trigger: 'The first paint on any back-office URL, and usually visible for well under a second.', boot: true }) withM({ ...home, name: 'Checking session', trigger: 'The first paint on any back-office URL, and usually visible for well under a second.', boot: true })
] }, ] },
@@ -102,7 +138,9 @@ class Component extends DCLogic {
withM({ ...home, name: 'Default', trigger: 'The articles loaded.', home: { sub: 'Here\'s where things stand on your site.', stats, recent } }), withM({ ...home, name: 'Default', trigger: 'The articles loaded.', home: { sub: 'Here\'s where things stand on your site.', stats, recent } }),
withM({ ...home, name: 'Loading', trigger: 'The list request is in flight. Skeletons appear after 150 ms.', home: { sub: 'Here\'s where things stand on your site.', stats: stats.map(() => ({ skel: true })), recent: Array.from({ length: 5 }, () => ({ skel: true })) } }), withM({ ...home, name: 'Loading', trigger: 'The list request is in flight. Skeletons appear after 150 ms.', home: { sub: 'Here\'s where things stand on your site.', stats: stats.map(() => ({ skel: true })), recent: Array.from({ length: 5 }, () => ({ skel: true })) } }),
withM({ ...home, name: 'Empty, first run', trigger: 'Zero articles: a single call to action, and no stats.', home: { sub: 'Welcome to RenewCMS.', empty: true } }), withM({ ...home, name: 'Empty, first run', trigger: 'Zero articles: a single call to action, and no stats.', home: { sub: 'Welcome to RenewCMS.', empty: true } }),
withM({ ...home, name: 'Error', trigger: 'A 500 or network failure on the list request.', home: { sub: 'Here\'s where things stand on your site.', error: true } }) withM({ ...home, name: 'Error', trigger: 'A 500 or network failure on the list request.', home: { sub: 'Here\'s where things stand on your site.', error: true } }),
withM({ ...home, navBadge: true, name: 'Update available (owner)', trigger: 'The owner only. A quiet banner above the content, and an "Update" pill on the Settings item (a dot on the menu icon on mobile, read as "Update available"). Dismissing hides the banner until the next version; the pill stays. Admins see neither.', home: { sub: 'Here\'s where things stand on your site.', stats, recent, banner: bn('circle-arrow-up', 'Version 2.3.0 is available', 'Update it from Settings. It takes about 2 minutes and the site stays online.') } }),
withM({ ...home, navBadge: true, name: 'Update ready to install (owner)', trigger: 'The download is checked. The same banner changes its copy, and a dismiss comes back on the next visit because the update is waiting.', home: { sub: 'Here\'s where things stand on your site.', stats, recent, banner: bn('circle-check', 'Version 2.3.0 is ready to install', 'Restart from Settings to finish. The site is unavailable for about 10 seconds.') } })
] }, ] },
{ label: 'Articles', title: 'Articles', route: '/article', api: 'GET /v1/article/ · PATCH …/publish · PATCH …/unpublish · DELETE /v1/article/{id}', note: 'Rows update when the server responds, not optimistically. Search, tab and sort are stored in the query string.', states: [ { label: 'Articles', title: 'Articles', route: '/article', api: 'GET /v1/article/ · PATCH …/publish · PATCH …/unpublish · DELETE /v1/article/{id}', note: 'Rows update when the server responds, not optimistically. Search, tab and sort are stored in the query string.', states: [
withM({ ...L(), name: 'Default', trigger: 'The list loaded, sorted by last updated.' }), withM({ ...L(), name: 'Default', trigger: 'The list loaded, sorted by last updated.' }),
@@ -137,7 +175,10 @@ class Component extends DCLogic {
E({ save: 'dirty', len: 10214 }, { name: 'Too long', trigger: 'Over 10 000. Save and Publish are disabled until it\'s shorter.' }), E({ save: 'dirty', len: 10214 }, { name: 'Too long', trigger: 'Over 10 000. Save and Publish are disabled until it\'s shorter.' }),
E({ preview: true }, { name: 'Preview', trigger: 'The Preview switch. Shows the title and body in the content scale, the way a public site might.' }), E({ preview: true }, { name: 'Preview', trigger: 'The Preview switch. Shows the title and body in the content scale, the way a public site might.' }),
E({ save: 'dirty' }, { name: 'Upload: choose', trigger: 'The image button in the toolbar, or a file dropped on the editor.', modal: { title: 'Add an image', close: true, upload: { state: 'idle' }, cancel: 'Cancel' } }), E({ save: 'dirty' }, { name: 'Upload: choose', trigger: 'The image button in the toolbar, or a file dropped on the editor.', modal: { title: 'Add an image', close: true, upload: { state: 'idle' }, cancel: 'Cancel' } }),
E({ save: 'dirty' }, { name: 'Upload: in progress', trigger: 'A valid file is uploading. Closing the dialog cancels the upload.', modal: { title: 'Add an image', close: true, upload: { state: 'uploading' }, cancel: 'Cancel upload' } }), E({ save: 'dirty' }, { name: 'Upload: crop and resize', trigger: 'A JPEG, PNG or WEBP passed the checks, and nothing is sent yet. The crop starts as the whole image and the width defaults to 1600 px. SVGs skip this step.', modal: cropM({ ratio: 0, size: 1 }) }),
E({ save: 'dirty' }, { name: 'Upload: crop to a ratio', trigger: '16:9 chosen. The frame keeps the ratio while it\'s dragged or resized. Arrow keys move it; Shift and arrow keys resize it.', modal: cropM({ ratio: 2, size: 1 }) }),
E({ save: 'dirty' }, { name: 'Upload: crop narrower than the width', trigger: 'The crop is smaller than the chosen width, so it keeps its own size.', modal: cropM({ ratio: 4, size: 1, rect: [42, 34, 15.873, 21.164] }) }),
E({ save: 'dirty' }, { name: 'Upload: in progress', trigger: 'Upload image was pressed. The cropped, resized file is uploading. Closing the dialog cancels the upload.', modal: { title: 'Add an image', close: true, upload: { state: 'uploading' }, cancel: 'Cancel upload' } }),
E({ save: 'dirty' }, { name: 'Upload: rejected', trigger: 'Checked in the browser, so nothing is sent.', modal: { title: 'Add an image', close: true, upload: { state: 'rejected' }, cancel: 'Cancel', confirm: 'Choose another file' } }), E({ save: 'dirty' }, { name: 'Upload: rejected', trigger: 'Checked in the browser, so nothing is sent.', modal: { title: 'Add an image', close: true, upload: { state: 'rejected' }, cancel: 'Cancel', confirm: 'Choose another file' } }),
E({ save: 'dirty', image: true }, { name: 'Upload: inserted', trigger: '201: the image goes in at the cursor, and the article now has unsaved changes.', toasts: [T('success', 'circle-check', 'Image added', 'Save to keep it in the article.')] }), E({ save: 'dirty', image: true }, { name: 'Upload: inserted', trigger: '201: the image goes in at the cursor, and the article now has unsaved changes.', toasts: [T('success', 'circle-check', 'Image added', 'Save to keep it in the article.')] }),
E({ save: 'saving', pending: 'Saving and publishing…' }, { name: 'Publishing', trigger: '"Save and publish": the PATCH body, then the publish request.' }), E({ save: 'saving', pending: 'Saving and publishing…' }, { name: 'Publishing', trigger: '"Save and publish": the PATCH body, then the publish request.' }),
@@ -148,18 +189,174 @@ class Component extends DCLogic {
E({ save: 'offline' }, { name: 'Offline', trigger: 'The connection dropped. Writing continues, and Save and Publish wait.', offline: true }), E({ save: 'offline' }, { name: 'Offline', trigger: 'The connection dropped. Writing continues, and Save and Publish wait.', offline: true }),
E({ notfound: true }, { name: 'Not found (404)', trigger: 'Unknown id, or the article was deleted elsewhere.' }) E({ notfound: true }, { name: 'Not found (404)', trigger: 'Unknown id, or the article was deleted elsewhere.' })
] }, ] },
{ label: 'Media', title: 'Media', route: '/media', api: 'GET /v1/media/ · POST /v1/media/ · PATCH /v1/media/{id} · DELETE /v1/media/{id} · POST /v1/media/merge · GET /v1/media/{id}/usage', note: 'New route for verified users, in the sidebar between Articles and Users with the images icon. Images belong to the library, not to an article: one image can be used in many articles, and deleting an article never deletes images. Uploads from this page are not cropped or resized, and the file is stored as chosen. "Used in" is read from article bodies each time the list loads. Duplicates are images with identical content, whatever their filenames. Alt text is not stored on the image; it is set when inserting into an article. Search, filter, sort and view are stored in the query string. Keyboard: grid items are buttons in one tab stop each; Enter opens the detail panel, Space toggles selection, and Escape closes the panel or clears the selection. Selection changes are announced ("north-wall.jpg selected, 1 selected").', states: [
Mp({ name: 'Grid, many images', trigger: 'Default view. 12 images, newest first. Each item is a button labelled like "north-wall.jpg, 3.9 MB, used in 2 articles". Badges: "Unused" (warm), "Duplicate" (info), "Used in N" (outline). The Duplicates tab carries a count of groups only while duplicates exist.' }),
Mp({ ids: [1, 4, 8], name: 'Grid, few images', trigger: 'Three images. Cards keep their size instead of stretching. Checkerboard shows behind the SVG.' }),
Mp({ view: 'list', name: 'List view', trigger: 'The list icon in the toggle. A table from md up (Filename, Dimensions, Size, Type, Used in, Uploaded by, Uploaded) and a card list below md. The "Used in" count opens the article list in the detail panel.' }),
Mp({ loading: true, name: 'Loading', trigger: 'The first load, a retry, or a change of search or filter. Skeleton cards appear after 150 ms.' }),
Mp({ empty: 'first', name: 'Empty library, first run', trigger: 'Zero images. Toolbar and tabs are hidden; one call to action. Copy: "No images yet" / "Upload your first image. You can use it in any article." / "Upload an image".' }),
Mp({ tab: 'unused', q: 'wall', empty: 'search', name: 'No results', trigger: 'Search or filter matched nothing. "Clear filters" resets the search and goes back to All.' }),
Mp({ hover: 2, focus: 3, ann: 'aria-label: kitchen-before.webp, 1.1 MB, used in 1 article', name: 'Hover, focus and keyboard', trigger: 'Hover (second item) darkens the border, adds the pop shadow and reveals the checkbox. Keyboard focus (third item) shows the 2 px primary ring with a 2 px offset and reveals the checkbox. Tab moves between items, Enter opens the detail panel, Space toggles selection, and arrow keys move focus across the grid.' }),
Mp({ sel: [1, 2, 8], name: 'Selection and bulk bar', trigger: 'Checkbox on any item, or Space. Selected items take the sand fill with a primary outline, and Select all shows a partial state. The bar is sticky at the bottom (above the bottom edge on mobile, replacing the Upload button). Announced: "3 selected". Escape or Clear empties it.' }),
Mp({ sel: [1, 2, 8], modal: { k: 'bulk' }, name: 'Bulk delete: confirm', trigger: 'Delete in the bulk bar. The dialog says how many of the selection are in use and lists them. The confirm button carries the count.' }),
Mp({ sel: [1, 2, 8], modal: { k: 'bulk', loading: true }, name: 'Bulk delete: in progress', trigger: 'Requests in flight. The dialog can\'t be dismissed.' }),
Mp({ ids: [3, 4, 5, 6, 7, 8, 9, 10, 11, 12], sel: [8], toasts: [TT('error', 'circle-x', 'Couldn\'t delete 1 image', '2 images were deleted. window-frame.jpg is still in your library. Try again.', 'Retry')], name: 'Bulk delete: partly failed', trigger: 'Some requests failed. Deleted images leave the grid, failed ones stay selected, and the toast stays until retried or dismissed.' }),
Mp({ ids: [3, 4, 5, 6, 7, 9, 10, 11, 12], toasts: [TT('success', 'circle-check', '3 images deleted', 'They\'re gone from your library.')], name: 'Bulk delete: done', trigger: '204 for all. Focus moves to the next item.' }),
Mp({ panel: { id: 1 }, name: 'Detail panel: in use', trigger: 'Click or Enter on an item. Right-hand slideover on desktop, full screen on mobile with a back arrow. Actions: Copy URL, Rename, Delete. "Used in 2 articles" lists title, Online or Draft, and links to the editor. Focus returns to the item on close.' }),
Mp({ panel: { id: 8 }, name: 'Detail panel: unused', trigger: 'Used in nothing. The section reads "Not used in any article" and says the image is safe to delete.' }),
Mp({ panel: { id: 12 }, name: 'Detail panel: duplicate', trigger: 'The image has identical copies. An info alert links to the duplicates view.' }),
Mp({ panel: { id: 1 }, toasts: [TT('success', 'circle-check', 'URL copied', 'Paste it wherever you need the image address.')], name: 'Copy URL', trigger: 'Copy URL. Clipboard write succeeded. Success toasts last 5 s.' }),
Mp({ panel: { id: 1 }, modal: { k: 'rename', val: 'north-wall' }, name: 'Rename: dialog', trigger: 'Rename in the panel. The field holds the name without its extension, and the .jpg ending is fixed. The description says the URL stays the same.' }),
Mp({ panel: { id: 1 }, modal: { k: 'rename', val: 'north-wall-01', loading: true }, name: 'Rename: saving', trigger: 'PATCH in flight. Field and buttons disabled, dialog can\'t be dismissed.' }),
Mp({ panel: { id: 1 }, modal: { k: 'rename', err: 'Enter a filename.' }, name: 'Rename: validation', trigger: 'Empty or only symbols, on submit or blur. Nothing is sent.' }),
Mp({ panel: { id: 1 }, modal: { k: 'rename', val: 'north-wall-01', notice: 'Couldn\'t rename the image. Your text is still here. Try again in a moment.' }, name: 'Rename: failed', trigger: '500 or network failure. The error shows inside the dialog.' }),
Mp({ panel: { id: 1 }, toasts: [TT('success', 'circle-check', 'Image renamed', 'It\'s now "north-wall-01.jpg". The URL is the same.')], name: 'Rename: done', trigger: '200: the panel title and list update in place.' }),
Mp({ panel: { id: 8 }, modal: { k: 'del' }, name: 'Delete: unused image', trigger: 'Delete in the panel. Plain confirm. Says what happens and that it can\'t be undone.' }),
Mp({ panel: { id: 1 }, modal: { k: 'delUsed' }, name: 'Delete: image in use', trigger: 'Stronger confirm. Lists the affected articles and states that they will show a broken image.' }),
Mp({ panel: { id: 1 }, modal: { k: 'delUsed', loading: true }, name: 'Delete: in progress', trigger: 'DELETE in flight. The dialog can\'t be dismissed.' }),
Mp({ panel: { id: 8 }, modal: { k: 'del', notice: 'Couldn\'t delete the image, so it\'s still there. Try again in a moment.' }, name: 'Delete: failed', trigger: '500 or network failure. The error shows inside the dialog, as in the article delete.' }),
Mp({ ids: gone, toasts: [TT('success', 'circle-check', 'Image deleted', '"window-frame.jpg" is gone from your library.')], name: 'Delete: done', trigger: '204: the panel closes, the item leaves the grid and focus moves to the next item.' }),
Mp({ ids: gone, toasts: [TT('info', 'info', 'That image no longer exists', 'It was deleted somewhere else, so we removed it from the library.')], name: 'Image already gone (404)', trigger: 'Any action on an image that was deleted elsewhere. The panel closes and the item leaves the list.' }),
Mp({ drag: true, name: 'Upload: drag over the page', trigger: 'Files dragged onto the page. A dashed drop area covers the content. Dropping starts the upload straight away; there is no crop step on this page.' }),
Mp({ upload: upT([rowOk('kitchen-roof.jpg', '2.2 MB', 2), { n: 'porch-steps.jpg', sz: '2.6 MB', st: 'prog', p: '1.1 of 2.6 MB', pct: '42%', im: 11 }, rowDup, rowRej, rowFail, { n: 'attic.jpg', sz: '1.9 MB', st: 'wait', im: 3 }]), name: 'Upload: several files, mixed', trigger: 'Upload button or drop, several files. Each file has its own row and progress. Files upload two at a time. A row can end as added, "Already in your library", rejected in the browser, or failed. Rejected and failed rows stay until dismissed.' }),
Mp({ upload: upT([rowOk('kitchen-roof.jpg', '2.2 MB', 2), rowOk('porch-steps.jpg', '2.6 MB', 11), rowDup, rowRej, rowFail], { title: 'Upload finished', sub: '5 images', done: true, summary: '2 uploaded · 1 already in your library · 2 need attention' }), name: 'Upload: summary', trigger: 'All rows settled. The summary counts each outcome. "Use existing" selects the existing image and drops the row; "Upload anyway" stores a second copy, which then appears under Duplicates. "Try again" retries one file. Announced when it finishes.' }),
Mp({ upload: upT([rowRej, { n: 'notes.pdf', sz: '210 KB', st: 'rej', title: 'notes.pdf isn\'t an image', msg: 'Images can be up to 10 MB. Use a PNG, JPEG, WEBP or SVG image.' }, { n: 'broken.png', sz: '3.0 MB', st: 'rej', title: 'broken.png couldn\'t be read', msg: 'The server couldn\'t read this image. Save it again as a PNG or JPEG, then try again.' }], { title: 'Nothing was uploaded', sub: '3 files were rejected', done: true }), name: 'Upload: rejected files (413, 400)', trigger: 'Type and size are checked in the browser first, so nothing is sent. A server 413 or 400 for a file that got through shows the same row with its own message.' }),
Mp({ limited: true, name: 'Upload: too many requests (429)', trigger: 'Rate limited. Retry-After is counted down in the button. It re-enables at zero. Already-added files are kept.' }),
Mp({ tab: 'dups', name: 'Duplicates: groups', trigger: 'The Duplicates tab. Groups of identical images side by side, each with its uploader, upload date and "Used in N articles". The suggested copy to keep is the most used, then the oldest.' }),
Mp({ tab: 'dups', dupEmpty: true, name: 'Duplicates: empty', trigger: 'No groups. The Duplicates tab loses its count badge.' }),
Mp({ tab: 'dups', modal: { k: 'merge' }, name: 'Merge: confirm', trigger: '"Merge into this one" on floorboards.jpg. The dialog says articles using the other copies will switch to this image and the other copies will be deleted, with the article count.' }),
Mp({ tab: 'dups', modal: { k: 'merge', loading: true }, name: 'Merge: in progress', trigger: 'Request in flight. The dialog can\'t be dismissed.' }),
Mp({ tab: 'dups', modal: { k: 'merge', notice: 'Couldn\'t merge the copies. Nothing was changed. Try again in a moment.' }, name: 'Merge: failed', trigger: '500 or network failure. Nothing is switched or deleted.' }),
Mp({ tab: 'dups', modal: { k: 'merge', notice: 'One of these images changed, so nothing was merged. The list is up to date now. Check it and try again.' }, name: 'Merge: conflict (409)', trigger: 'A copy was deleted, or a new copy appeared, since the page loaded.' }),
Mp({ tab: 'dups', dupGroups: 1, ids: [1, 2, 3, 4, 7, 8, 9, 10, 11, 12], toasts: [TT('success', 'circle-check', 'Copies merged', '2 copies merged. 5 articles updated.')], name: 'Merge: done', trigger: '200: the group leaves the list. When it was the last one, "No duplicates" shows.' }),
Mp({ error: true, name: 'List failed to load', trigger: 'A 500 or network failure on the list request. The alert replaces the images; Try again repeats the request.' }),
Mp({ offline: true, name: 'Offline', trigger: 'navigator.onLine is false. Loaded images stay browsable. Upload, Rename, Delete and Merge are disabled, and the banner says why.' })
], tableTitle: 'Status to copy', table: [
{ a: '200 / 201', b: 'Upload, rename, merge', c: 'Upload: row reads "Added to your library". Rename: "Image renamed" / "It\'s now "north-wall-01.jpg". The URL is the same." Merge: "Copies merged" / "2 copies merged. 5 articles updated."' },
{ a: '204', b: 'Delete, bulk delete', c: '"Image deleted" / ""window-frame.jpg" is gone from your library." Bulk: "3 images deleted" / "They\'re gone from your library."' },
{ a: '400', b: 'Upload row', c: '"broken.png couldn\'t be read" / "The server couldn\'t read this image. Save it again as a PNG or JPEG, then try again." In a dialog: "Something in the form isn\'t valid. Check the highlighted fields."' },
{ a: '401', b: 'Any call', c: 'Handled globally: /login?redirect=/media&reason=expired. No local copy.' },
{ a: '403', b: 'Any call, unverified', c: 'Handled globally: /register/pending.' },
{ a: '404', b: 'Rename, delete, merge, panel', c: 'Toast (info): "That image no longer exists" / "It was deleted somewhere else, so we removed it from the library." The panel or dialog closes.' },
{ a: '409', b: 'Merge', c: 'Dialog alert: "One of these images changed, so nothing was merged. The list is up to date now. Check it and try again."' },
{ a: '413', b: 'Upload row', c: '"scan.tif is 14.2 MB" / "Images can be up to 10 MB. Use a PNG, JPEG, WEBP or SVG image."' },
{ a: '415', b: 'Upload row', c: '"notes.pdf isn\'t an image" / "Images can be up to 10 MB. Use a PNG, JPEG, WEBP or SVG image."' },
{ a: '429', b: 'Upload', c: 'Alert (info): "Too many uploads" / "For your security, wait a moment before uploading again." The button reads "Try again in 0:42" and counts down.' },
{ a: '500 / network', b: 'List', c: 'Alert: "Couldn\'t load your images" / "Check your connection and try again." with "Try again".' },
{ a: '500 / network', b: 'Upload row', c: '"Upload failed" / "The server didn\'t accept the file. Nothing was added to your library." with "Try again".' },
{ a: '500 / network', b: 'Rename dialog', c: '"Couldn\'t rename the image. Your text is still here. Try again in a moment."' },
{ a: '500 / network', b: 'Delete dialog', c: '"Couldn\'t delete the image, so it\'s still there. Try again in a moment."' },
{ a: '500 / network', b: 'Merge dialog', c: '"Couldn\'t merge the copies. Nothing was changed. Try again in a moment."' },
{ a: 'Partial', b: 'Bulk delete', c: 'Toast (error, stays): "Couldn\'t delete 1 image" / "2 images were deleted. window-frame.jpg is still in your library. Try again." with "Retry".' },
{ a: 'Offline', b: 'Whole page', c: 'Banner: "You\'re offline. You can look through the images that are loaded, but uploading, renaming and deleting need a connection."' }
] },
{ label: 'Media picker', title: 'Picker in the editor', route: '/article/:id/edit', api: 'GET /v1/media/?q=&limit=&cursor= · POST /v1/media/ (same as the Media page)', note: 'The existing "Add an image" dialog gains two tabs, Upload and Library. The Upload tab is the current flow unchanged, so it still offers crop and resize, and a new image lands in the library and is inserted as before. The Library tab opens on the Library tab when the library has images and on Upload when it is empty. Images load 24 at a time with "Load more". Newest first, and images already in this article carry "In this article". Alt text is set here and lives only in the article. The dialog is 640 px wide on desktop and a bottom sheet on mobile.', states: [
pk({ tab: 'Upload' }, { name: 'Upload tab', trigger: 'The image button in the toolbar. Identical to the current "Add an image" content; only the tabs are new. Rejected, uploading and failed states are unchanged.', inArticle: false }),
pk({ tab: 'Upload', dup: true }, { name: 'Upload tab: already in your library', trigger: 'A chosen file has the same content as an existing image. Nothing is sent. "Use existing" inserts the existing image (the alt text step follows); "Upload anyway" continues to crop and upload as usual.' }),
pk({ loading: true }, { name: 'Library: loading', trigger: 'The Library tab was opened, or a search changed. Skeleton tiles after 150 ms.' }),
pk({}, { name: 'Library: nothing selected', trigger: 'Newest first. Tiles are buttons labelled with filename, size and use, and Enter or Space selects. Images already in this article carry "In this article". "Insert image" is disabled.' }),
pk({ sel: 2, alt: '' }, { name: 'Library: selected', trigger: 'One image selected (single selection). Below the grid: thumbnail, filename, dimensions and size, and an optional alt text field. "Insert image" turns on.' }),
pk({ sel: 2, alt: 'A kitchen with new oak worktops and white tiles' }, { name: 'Library: alt text entered', trigger: 'Alt text is optional. Empty alt text is inserted as a decorative image. It is not saved on the image.' }),
pk({ more: true }, { name: 'Library: loading more', trigger: '"Load more" pressed. The button shows progress and new skeleton tiles appear at the end. Focus stays on the button until the new tiles arrive, then moves to the first new tile.' }),
pk({ empty: 'first' }, { name: 'Library: empty', trigger: 'Zero images. "Upload an image" switches to the Upload tab.' }),
pk({ q: 'wall', empty: 'search' }, { name: 'Library: no results', trigger: 'Search matched nothing. "Clear search" resets it.' }),
pk({ error: true }, { name: 'Library: failed to load', trigger: 'A 500 or network failure. The error shows in the dialog and Try again repeats the request. A 429 uses the same countdown alert as the Media page, and a 401 is handled globally.' }),
MS({ kind: 'picker', inArticle: true, name: 'Inserted', trigger: 'Insert image from either tab. The image goes in at the cursor with the chosen alt text, and the article now has unsaved changes.', toasts: [TT('success', 'circle-check', 'Image added', 'Save to keep it in the article.')] }),
MS({ kind: 'picker', inArticle: true, picker: false, modal: { k: 'remove' }, name: 'Remove image: confirm', trigger: 'Remove image on an image in the article. It now only removes it from this article, and the copy says the file stays in the library. The confirm button is neutral, not red, because nothing is deleted. Title: "Remove this image from the article?"' }),
MS({ kind: 'picker', name: 'Removed', trigger: 'Confirmed. The image leaves the article body, which now has unsaved changes.', toasts: [TT('success', 'circle-check', 'Image removed', 'It\'s still in your library.')] })
] },
{ label: 'Integration', title: 'Connect your website', route: '/integration', api: 'none (static)', note: 'Written for a developer. The base URL is window.location.origin.', states: [ { label: 'Integration', title: 'Connect your website', route: '/integration', api: 'none (static)', note: 'Written for a developer. The base URL is window.location.origin.', states: [
withM({ kind: 'integration', nav: 'integration', crumbs: ['Integration'], mTitle: 'Integration', name: 'Default', trigger: 'Opened from the sidebar or the Home card.' }), withM({ kind: 'integration', nav: 'integration', crumbs: ['Integration'], mTitle: 'Integration', name: 'Default', trigger: 'Opened from the sidebar or the Home card.' }),
withM({ kind: 'integration', nav: 'integration', crumbs: ['Integration'], mTitle: 'Integration', copied: true, name: 'Copied', trigger: 'The base URL was copied. The button reads "Copied" for 2 s and this is announced.' }) withM({ kind: 'integration', nav: 'integration', crumbs: ['Integration'], mTitle: 'Integration', copied: true, name: 'Copied', trigger: 'The base URL was copied. The button reads "Copied" for 2 s and this is announced.' })
] }, ] },
{ label: 'Users', title: 'Users', route: '/users', api: 'GET /v1/user/ · POST /v1/user/invite · DELETE /v1/user/invite/:id (pending) · POST /v1/user/invite/:id/renew (pending)', note: 'One shared workspace: every user sees the same articles and this same list. Columns: email, display name, role (owner or admin), invite status and created date. A pending invite can be cancelled and an expired one renewed; accepted accounts have no row actions. An invite is Pending until its link is used, Expired after 3 days, and Accepted once the account is created.', states: [
withM({ ...U(), name: 'Default', trigger: 'The list loaded, newest first.' }),
withM({ ...U({ users: { loading: true } }), name: 'Loading', trigger: 'The first load, or a retry. Skeletons appear after 150 ms.' }),
withM({ ...U({ users: { rows: people.slice(-1), only: true } }), name: 'Only you', trigger: 'Nobody has been invited yet. The admin who registered is always listed.' }),
withM({ ...U({ users: { error: true } }), name: 'Error', trigger: 'A 500 or network failure on the list request.' }),
withM({ ...U({ modal: inv() }), name: 'Invite: default', trigger: '"Invite user" in the page header, or the bottom button on mobile.' }),
withM({ ...U({ modal: inv({ fields: invF('sam.oliveira@renew', { err: 'Enter a full email address, like name@example.com.' }) }) }), name: 'Invite: validation', trigger: 'On submit or blur. Nothing is sent.' }),
withM({ ...U({ modal: inv({ loading: true, confirm: 'Sending…', fields: invF('lea.martin@renew.example') }) }), name: 'Invite: sending', trigger: 'Request in flight. The field is disabled and the dialog can\'t be dismissed.' }),
withM({ ...U({ modal: inv({ fields: invF('jonas@renew.example', { err: 'This address already has an account.' }) }) }), name: 'Invite: already a user (409)', trigger: 'The email belongs to an existing user. For a live pending invite the message reads "There\'s already a pending invite for this address." An expired invite can be sent again.' }),
withM({ ...U({ modal: inv({ notice: 'Couldn\'t send the invite. Try again in a moment.', fields: invF('lea.martin@renew.example') }) }), name: 'Invite: failed', trigger: '500, network failure, or the email couldn\'t be sent. The address stays in the field.' }),
withM({ ...U({ modal: { title: 'Cancel this invite?', desc: 'The link sent to sam.oliveira@renew.example will stop working. You can invite the address again later.', cancel: 'Keep invite', confirm: 'Cancel invite', tone: 'danger' } }), name: 'Cancel invite: confirm', trigger: '"Cancel invite" on a Pending row.' }),
withM({ ...U({ modal: { title: 'Cancel this invite?', desc: 'The link sent to sam.oliveira@renew.example will stop working. You can invite the address again later.', cancel: 'Keep invite', confirm: 'Cancelling…', tone: 'danger', loading: true } }), name: 'Cancel invite: sending', trigger: 'Request in flight. Both buttons are disabled.' }),
withM({ ...U({ modal: { title: 'Cancel this invite?', desc: 'The link sent to sam.oliveira@renew.example will stop working. You can invite the address again later.', cancel: 'Keep invite', confirm: 'Cancel invite', tone: 'danger', notice: 'Couldn\'t cancel the invite. Try again in a moment.' } }), name: 'Cancel invite: failed', trigger: '500 or network failure. The dialog stays open.' }),
withM({ ...U({ users: { rows: people.slice(1) }, toasts: [T('success', 'circle-check', 'Invite cancelled', 'sam.oliveira@renew.example can no longer use the link.')] }), name: 'Cancel invite: done', trigger: '204: the row disappears and a toast confirms.' }),
withM({ ...U({ users: { rows: people.map(p => p.st === 'expired' ? { ...p, busy: 'Renewing…' } : p) } }), name: 'Renew invite: sending', trigger: '"Renew invite" on an Expired row. No confirmation, since it only sends an email. The button shows progress and is disabled.' }),
withM({ ...U({ users: { rows: [{ ...people[1], st: 'pending', c: 'Today', hl: true }, ...people.filter((p, i) => i !== 1)] }, toasts: [T('success', 'circle-check', 'Invite renewed', 'p.huber@gmail.com has 3 days to accept the new link.')] }), name: 'Renew invite: done', trigger: '200: the row becomes Pending with today\'s date, moves to the top, and the old link stops working.' }),
withM({ ...U({ toasts: [T('error', 'circle-x', 'Couldn\'t renew the invite', 'Try again in a moment.')] }), name: 'Renew invite: failed', trigger: '500 or network failure. The row stays Expired and the button can be pressed again.' }),
withM({ ...U({ users: { rows: [{ email: 'lea.martin@renew.example', role: 'admin', st: 'pending', c: 'Today', hl: true }, ...people] } , toasts: [T('success', 'circle-check', 'Invite sent', 'lea.martin@renew.example has 3 days to accept.')] }), name: 'Invite sent', trigger: '201: the dialog closes, the new invite appears at the top as Pending, and a toast confirms.' })
] },
{ label: 'Settings', title: 'Settings: Updates', route: '/settings', api: 'GET /v1/system/update · POST …/check · POST …/download · POST …/restart (all pending)', note: 'New Updates card under Version, owner only. Update downloads and checks the new version and changes nothing. Restart installs it and restarts the site (about 10 seconds). "Restart later" is simply leaving the card or the dialog. A plain Restart shows only when no update is waiting. Admins see the version and a note. When the server isn\'t prepared, the card shows the notice and a "How to update" link with no buttons. Progress is a progressbar with a value, announced at 25% steps and when each step changes. The card is a polite live region. After the restart the page reloads, focus lands on the "Updates" heading, and a toast confirms. Buttons are disabled while any step runs, and any owner on any device sees the same state from the server. Cue elsewhere: see Home. Out of scope: choosing versions, downgrades, automatic updates, update history.', states: [
SU({ icon: 'circle-check', tone: 'success', title: 'You\'re up to date', text: 'You have the latest version of RenewCMS.', meta: LAST, btns: [B('Check for updates', 'sec', 'refresh-cw'), B('Restart', 'sec', 'power')], hint: RESTART_FOOT }, { name: 'Up to date', trigger: 'Opened with no newer version. Restart is available but not emphasised.' }),
SU({ icon: 'loader-circle', title: 'Checking for updates…', text: 'This usually takes a few seconds.', btns: [B('Checking…', 'sec', 'loader-circle', true)] }, { name: 'Checking', trigger: 'Check for updates pressed, or the first open after 24 hours. Announced as "Checking for updates". Buttons are disabled.' }),
SU({ icon: 'wifi-off', tone: 'warning', title: 'Couldn\'t check for updates', text: 'RenewCMS couldn\'t reach the update server. Check your connection and try again. Your site isn\'t affected.', meta: 'Last checked yesterday at 18:12', btns: [B('Try again', 'primary', 'rotate-cw'), B('Restart', 'sec', 'power')], hint: RESTART_FOOT }, { name: 'Check failed', trigger: 'Offline, or the update server didn\'t answer (500, network). The last known result is kept.' }),
SU({ icon: 'circle-arrow-up', tone: 'info', title: 'Version 2.3.0 is available', text: 'You have v2.2.0-beta. Update downloads the new version and checks it. Nothing changes until you restart.', meta: LAST, notes: NOTES(false), btns: [B('Update', 'primary', 'download')], hint: 'Takes about 2 minutes. Your site stays online.' }, { name: 'Update available', trigger: 'A newer version exists. Release notes are collapsed. Update is the one primary button.', navBadge: true }),
SU({ icon: 'circle-arrow-up', tone: 'info', title: 'Version 2.3.0 is available', text: 'You have v2.2.0-beta. Update downloads the new version and checks it. Nothing changes until you restart.', meta: LAST, notes: NOTES(true), btns: [B('Update', 'primary', 'download')], hint: 'Takes about 2 minutes. Your site stays online.' }, { name: 'Update available, notes open', trigger: '"What\'s new in 2.3.0" expanded. It is a button with aria-expanded, and the list is plain text.', navBadge: true }),
SU({ icon: 'download', tone: 'info', title: 'Downloading version 2.3.0…', text: 'You can leave this page. The download continues and your site stays online.', pct: 42, barLabel: 'Downloading version 2.3.0', barText: '42% · 11 of 26 MB', btns: [B('Updating…', 'sec', 'loader-circle', true)] }, { name: 'Downloading', trigger: 'Update pressed (202). Progress polls every second. Announced as "Downloading, 25 percent" and so on, never every tick.', navBadge: true }),
SU({ icon: 'shield-check', tone: 'info', title: 'Checking the download…', text: 'Making sure the file is complete and safe to install. This takes a few seconds.', indet: true, barLabel: 'Checking the download', barText: 'Almost there', btns: [B('Updating…', 'sec', 'loader-circle', true)] }, { name: 'Verifying', trigger: 'The download finished. No percentage, so the bar is indeterminate. Announced as "Checking the download".', navBadge: true }),
SU({ icon: 'circle-check', tone: 'success', title: 'Version 2.3.0 is ready to install', text: 'The download is checked. Restart to install it. Your site will be unavailable for about 10 seconds.', meta: 'Nothing has changed yet.', notes: NOTES(false), btns: [B('Restart', 'primary', 'power')], hint: 'Not now? Leave this page. The update waits here, and the banner on Home reminds you.' }, { name: 'Ready to install', trigger: 'The file passed its checks. Restart becomes the primary action. "Restart later" is closing the dialog or leaving the page.', navBadge: true }),
SU({ icon: 'circle-check', tone: 'success', title: 'Version 2.3.0 is ready to install', text: 'The download is checked. Restart to install it. Your site will be unavailable for about 10 seconds.', meta: 'Nothing has changed yet.', btns: [B('Restart', 'primary', 'power')] }, { name: 'Restart: confirm', trigger: 'Restart pressed. Same dialog behaviour as the delete confirm: focus moves to the first button, Escape and "Restart later" close it, and focus returns to Restart. The confirm button is neutral, not red, because nothing is lost.', navBadge: true, modal: installModal() }),
SU({ icon: 'circle-check', tone: 'success', title: 'Version 2.3.0 is ready to install', text: 'The download is checked. Restart to install it. Your site will be unavailable for about 10 seconds.', meta: 'Nothing has changed yet.', btns: [B('Restart', 'primary', 'power')] }, { name: 'Restart: request failed', trigger: '500 or network failure before the restart began. The site is still running.', navBadge: true, modal: installModal({ notice: 'Couldn\'t start the restart. Nothing was changed and your site is still running. Try again in a moment.' }) }),
SU({ icon: 'circle-check', tone: 'success', title: 'Version 2.3.0 is ready to install', text: '', btns: [] }, { name: 'Restarting to install', trigger: 'Full-page overlay, so it survives the server going away. The page polls until the site answers, then reloads. It is a live region announced once as "Installing version 2.3.0. Your site is restarting."', overlay: { title: 'Installing version 2.3.0', text: 'Your site is restarting with the new version. This takes about 10 seconds. This page reloads on its own when the site is back.', meta: 'Started at 09:51', barL: '30%' } }),
SU({ icon: 'circle-check', tone: 'success', title: '', text: '', btns: [] }, { name: 'Restarting, taking longer', trigger: 'No answer after 60 seconds. The copy changes and a manual reload appears. The overlay stays until the site is back.', overlay: { title: 'Still restarting', text: 'This is taking longer than usual. Keep this page open. It reloads on its own when the site is back, or you can reload it now.', meta: 'Started at 09:51 · 1 minute ago', btn: 'Reload page', barL: '65%' } }),
SU({ icon: 'circle-check', tone: 'success', title: 'You\'re on version 2.3.0', text: 'The update is installed and your site is running again.', meta: 'Updated today at 09:52', btns: [B('Check for updates', 'sec', 'refresh-cw'), B('Restart', 'sec', 'power')], hint: RESTART_FOOT, link: 'Read the release notes', v: 'v2.3.0', focus: '2px solid var(--ui-primary)', toasts: undefined }, { name: 'Update done', trigger: 'The page reloaded on the new version. Focus lands on the "Updates" heading (ring shown), the toast is announced, and the version updates.', toasts: [T('success', 'circle-check', 'Update installed', 'RenewCMS is now on version 2.3.0.')] }),
SU({ icon: 'triangle-alert', tone: 'warning', title: 'The update didn\'t install', text: 'RenewCMS put the previous version back, so your site is running as before. Nothing was lost.', meta: 'What to do next: try again in a few minutes. If it fails again, ask whoever manages your server to check the update.', btns: [B('Try again', 'primary', 'rotate-cw')] }, { name: 'Update failed, rolled back', trigger: 'The site came back on v2.2.0-beta. The error toast stays until dismissed and the card keeps the explanation.', toasts: [T('error', 'circle-x', 'The update didn\'t install', 'Your site is back on v2.2.0-beta.')] }),
SU({ icon: 'circle-x', tone: 'error', title: 'The download didn\'t finish', text: 'The connection dropped before the file was complete. Nothing was changed and your site is running as before.', btns: [B('Try again', 'primary', 'rotate-cw')] }, { name: 'Download failed', trigger: 'A 500, or the connection dropped. Focus moves to the card heading. Try again restarts the download.', navBadge: true }),
SU({ icon: 'triangle-alert', tone: 'warning', title: 'We didn\'t use this update', text: 'The file didn\'t pass our safety check, so it was not installed. Nothing was changed. Try downloading it again. If this keeps happening, contact RenewCMS support.', btns: [B('Try again', 'primary', 'rotate-cw')] }, { name: 'Verification failed', trigger: 'The downloaded file isn\'t trusted. The tone is a warning, and the file is thrown away. Technical detail goes to the server log, not the screen.', navBadge: true }),
SU({ icon: 'info', tone: 'info', title: 'Too many tries', text: 'Wait a moment before trying again.', btns: [B('Try again in 0:42', 'sec', 'clock', true)] }, { name: 'Too many requests (429)', trigger: 'Retry-After counted down in the button. It re-enables at zero.' }),
SU(notPrep(false), { name: 'Not prepared', trigger: 'The server can\'t update from the browser. No buttons, not even Restart. The command is for the person who runs the server and is a single line. The placeholder command is subject to the real one.', navBadge: true }),
SU(notPrep(true), { name: 'Not prepared: command copied', trigger: 'Copy pressed. The button reads "Copied" for 2 s and it is announced.', navBadge: true }),
SU({ icon: 'circle-check', tone: 'success', title: 'You\'re up to date', text: 'You have the latest version of RenewCMS.', meta: LAST, btns: [B('Check for updates', 'sec', 'refresh-cw'), B('Restart', 'sec', 'power')], hint: RESTART_FOOT }, { name: 'Plain restart: confirm', trigger: 'Restart with no update waiting. Nothing is installed.', modal: restartModal() }),
SU({ icon: 'circle-check', tone: 'success', title: '', text: '', btns: [] }, { name: 'Plain restart: restarting', trigger: 'Same overlay as the update restart with shorter copy.', overlay: { title: 'Restarting your site', text: 'This takes about 10 seconds. This page reloads on its own when the site is back.', meta: 'Started at 09:51', barL: '30%' } }),
SU({ icon: 'circle-check', tone: 'success', title: 'Your site is back', text: '', btns: [] }, { name: 'Plain restart: done', trigger: 'The page reloaded. Focus lands on the "Updates" heading.', toasts: [T('success', 'circle-check', 'Site restarted', 'Your site is running again.')] }),
SU({ icon: 'circle-arrow-up', tone: 'info', title: 'Version 2.3.0 is available', text: 'You have v2.2.0-beta. Only the owner can update RenewCMS. Ask the owner of this site.', meta: LAST }, { name: 'Admin view', trigger: 'Admins see the version and the note, with no buttons. Up to date: "You\'re up to date" and "Only the owner can update or restart the site." No Home banner or Settings pill.' }),
SU({ icon: 'circle-arrow-up', tone: 'info', title: 'Version 2.3.0 is available', text: 'You have v2.2.0-beta. Only the owner can update RenewCMS. Ask the owner of this site.', meta: LAST }, { name: 'Role changed (403)', trigger: 'An owner was changed to admin while the page was open and pressed a button. The card reloads in the admin view.', toasts: [T('error', 'circle-x', 'Only the owner can do this', 'Ask the owner of this site to update RenewCMS.')] }),
SU({ icon: 'circle-arrow-up', tone: 'info', title: 'Version 2.3.0 is available', text: 'You have v2.2.0-beta. Update downloads the new version and checks it. Nothing changes until you restart.', meta: LAST, btns: [B('Update', 'primary', 'download', true)] }, { name: 'Update already running (409)', trigger: 'Another owner started it. The card switches to that run\'s progress.', navBadge: true, toasts: [T('info', 'info', 'An update is already running', 'Another owner started it. Progress shows here.')] })
], tableTitle: 'Status to copy', table: [
{ a: '200', b: 'Check, up to date', c: '"You\'re up to date" / "You have the latest version of RenewCMS." / "Last checked today at 09:41"' },
{ a: '200', b: 'Check, newer version', c: '"Version 2.3.0 is available" / "You have v2.2.0-beta. Update downloads the new version and checks it. Nothing changes until you restart."' },
{ a: '202', b: 'Update, Restart', c: 'Accepted. The card switches to progress. Announced: "Downloading version 2.3.0, 25 percent".' },
{ a: '200', b: 'Update finished', c: '"Version 2.3.0 is ready to install" / "The download is checked. Restart to install it. Your site will be unavailable for about 10 seconds."' },
{ a: '200', b: 'After restart', c: 'Toast: "Update installed" / "RenewCMS is now on version 2.3.0." Plain restart: "Site restarted" / "Your site is running again."' },
{ a: '400', b: 'Update, nothing to install', c: 'Toast (info): "Nothing to update" / "You already have the latest version." The card refreshes.' },
{ a: '401', b: 'Any call', c: 'Handled globally: /login?redirect=/settings&reason=expired. No local copy.' },
{ a: '403', b: 'Any button, not the owner', c: 'Toast (error): "Only the owner can do this" / "Ask the owner of this site to update RenewCMS." The card reloads as the admin view. An unverified account is handled globally.' },
{ a: '409', b: 'Update, Restart', c: 'Already running: toast (info) "An update is already running" / "Another owner started it. Progress shows here." Not prepared: the card shows the "Not prepared" state and "How to update".' },
{ a: '422', b: 'Update, file not trusted', c: '"We didn\'t use this update" / "The file didn\'t pass our safety check, so it was not installed. Nothing was changed. Try downloading it again. If this keeps happening, contact RenewCMS support."' },
{ a: '429', b: 'Check, Update', c: 'Card alert (info): "Too many tries" / "Wait a moment before trying again." Button reads "Try again in 0:42" and counts down.' },
{ a: '500 / network', b: 'Check', c: '"Couldn\'t check for updates" / "RenewCMS couldn\'t reach the update server. Check your connection and try again. Your site isn\'t affected." with "Try again".' },
{ a: '500 / network', b: 'Update', c: '"The download didn\'t finish" / "The connection dropped before the file was complete. Nothing was changed and your site is running as before." with "Try again".' },
{ a: '500 / network', b: 'Restart dialog', c: '"Couldn\'t start the restart. Nothing was changed and your site is still running. Try again in a moment."' },
{ a: 'Site back, old version', b: 'After restart', c: '"The update didn\'t install" / "RenewCMS put the previous version back, so your site is running as before. Nothing was lost." Next step: "try again in a few minutes. If it fails again, ask whoever manages your server to check the update."' },
{ a: 'No answer, 60 s', b: 'Restart overlay', c: '"Still restarting" / "This is taking longer than usual. Keep this page open. It reloads on its own when the site is back, or you can reload it now."' },
{ a: 'Offline', b: 'Whole page', c: 'Existing banner. Check, Update and Restart are disabled. During a restart, the overlay keeps polling and ignores the offline state.' }
] },
{ label: 'Profile', title: 'Profile', route: '/profile', api: 'GET /v1/auth/me · PATCH /v1/user/me (pending) · POST /v1/auth/password-reset', note: 'Opened from the account menu at the bottom of the sidebar. Username, email and password are read-only. The display name is optional, trimmed, and up to 60 characters. Once saved it replaces the username everywhere a person is named: the sidebar, the account menu, the Home greeting, the Users list (with the username beside it) and the emails RenewCMS sends, such as "Marta Alves invited you to RenewCMS". Saving it empty goes back to the username. The reset link uses the same flow as "Forgot password" and ends on the auth board\'s "Choose a new password" screen.', states: [
withM({ ...home, home: { sub: 'Here\'s where things stand on your site.', stats, recent }, userMenu: true, name: 'Account menu', trigger: 'The account chip at the bottom of the sidebar. On mobile, the account row in the navigation drawer opens it as a sheet. Escape or a click outside closes it.' }),
P({ loading: true }, { name: 'Loading', trigger: 'Opened directly by URL before /auth/me has returned. From the menu, the cached user renders straight away.' }),
P({}, { name: 'Default, no display name', trigger: 'The usual first visit. The username is used everywhere.' }),
P({ value: dname, focus: true, dirty: true }, { name: 'Editing', trigger: 'Typing in the field. Save turns on, and leaving the page asks for confirmation.' }),
P({ value: 'Marta Alves, Head of Renovations, Brussels and Wallonia office', focus: true, dirty: true, err: 'Use 60 characters or fewer.' }, { name: 'Too long', trigger: 'Over 60 characters. Checked as you type, and Save stays off.' }),
P({ value: dname, dirty: true, saving: true }, { name: 'Saving', trigger: 'Save, or Enter in the field. The field is disabled.' }),
P({}, { display: dname, name: 'Saved', trigger: '200: the sidebar and account menu switch to the display name at once, and a toast confirms.', toasts: [T('success', 'circle-check', 'Display name saved', 'You now appear as Marta Alves across RenewCMS and in emails.')] }),
P({ value: dname, dirty: true, notice: 'Couldn\'t save your display name. Your text is still here. Try again in a moment.' }, { name: 'Save failed', trigger: '500 or network failure. The typed value is kept.' }),
P({ reset: 'sending' }, { display: dname, name: 'Reset: sending', trigger: '"Send reset link". No confirmation, since it only sends an email.' }),
P({ reset: 'sent' }, { display: dname, name: 'Reset: sent', trigger: '200. The message stays until the page is left. "Send again" sends a new link and the old one stops working.' }),
P({ reset: 'limited' }, { display: dname, name: 'Reset: too many requests (429)', trigger: 'Rate limited. The button is disabled for 5 minutes.' }),
P({ reset: 'error' }, { display: dname, name: 'Reset: failed', trigger: '500 or network failure. The button can be pressed again.' }),
withM({ ...U(), display: dname, name: 'Display names in the Users list', trigger: 'The Display name column shows the name when one is set and a dash when not. Your own row follows your saved name.' })
] },
{ label: 'Global', title: 'Global states', route: 'any route', api: '', note: 'A 401 on any back-office call redirects to /login?redirect=<path>&reason=expired (see "Session expired" on the auth board). A 403 from an unverified account redirects to /register/pending. A 429 appears only on log in and password reset. Toasts sit bottom right on desktop and bottom center on mobile, at most 3 at once. Success and info last 5 s; errors stay until dismissed.', states: [ { label: 'Global', title: 'Global states', route: 'any route', api: '', note: 'A 401 on any back-office call redirects to /login?redirect=<path>&reason=expired (see "Session expired" on the auth board). A 403 from an unverified account redirects to /register/pending. A 429 appears only on log in and password reset. Toasts sit bottom right on desktop and bottom center on mobile, at most 3 at once. Success and info last 5 s; errors stay until dismissed.', states: [
withM({ kind: 'error', nav: '', crumbs: ['Not found'], mTitle: 'Not found', name: '404 inside the shell', trigger: 'An unknown route while logged in. Logged out, the same content appears inside AuthShell.', err: { code: '404', title: 'Page not found', text: 'The link may be mistyped, or the page may have moved.', primary: 'Go to Home', secondary: 'All articles' } }), withM({ kind: 'error', nav: '', crumbs: ['Not found'], mTitle: 'Not found', name: '404 inside the shell', trigger: 'An unknown route while logged in. Logged out, the same content appears inside AuthShell.', err: { code: '404', title: 'Page not found', text: 'The link may be mistyped, or the page may have moved.', primary: 'Go to Home', secondary: 'All articles' } }),
withM({ kind: 'error', nav: 'home', crumbs: ['Home'], mTitle: 'Home', name: 'Generic error', trigger: 'An unexpected error while rendering a route.', err: { code: 'Error', title: 'Something went wrong', text: 'This page couldn\'t load. Your saved work is safe. Try again, and if it keeps happening, restart the RenewCMS server.', primary: 'Try again', secondary: 'Go to Home' } }), withM({ kind: 'error', nav: 'home', crumbs: ['Home'], mTitle: 'Home', name: 'Generic error', trigger: 'An unexpected error while rendering a route.', err: { code: 'Error', title: 'Something went wrong', text: 'This page couldn\'t load. Your saved work is safe. Try again, and if it keeps happening, restart the RenewCMS server.', primary: 'Try again', secondary: 'Go to Home' } }),
withM({ ...L({ offline: true }), name: 'Offline banner', trigger: 'navigator.onLine is false. The banner is shown on every back-office page.' }), withM({ ...L({ offline: true }), name: 'Offline banner', trigger: 'navigator.onLine is false. The banner is shown on every back-office page.' }),
withM({ ...L({ toasts: [T('success', 'circle-check', 'Article published', '"Winter checklist for timber windows" is now online.'), T('info', 'info', 'That article no longer exists', 'It was deleted somewhere else, so we removed it from the list.'), T('error', 'circle-x', 'Couldn\'t unpublish', 'The server didn\'t respond. Nothing changed.', 'Retry')] }), name: 'Toast stack', trigger: 'Three at most, newest at the bottom. A fourth pushes out the oldest non-error toast.' }) withM({ ...L({ toasts: [T('success', 'circle-check', 'Article published', '"Winter checklist for timber windows" is now online.'), T('info', 'info', 'That article no longer exists', 'It was deleted somewhere else, so we removed it from the list.'), T('error', 'circle-x', 'Couldn\'t unpublish', 'The server didn\'t respond. Nothing changed.', 'Retry')] }), name: 'Toast stack', trigger: 'Three at most, newest at the bottom. A fourth pushes out the oldest non-error toast.' })
] } ] }
] ])
} }
finish(gs) { return gs.map(g => ({ ...g, states: g.states.map(st => ({ notMedia: !st.isMedia, ...st, m: { ...st.m } })) })) }
renderVals() { renderVals() {
const modes = [['system', 'System'], ['light', 'Light'], ['dark', 'Dark']].map(([k, label]) => { const modes = [['system', 'System'], ['light', 'Light'], ['dark', 'Dark']].map(([k, label]) => {
const on = this.state.mode === k const on = this.state.mode === k
+72
View File
@@ -0,0 +1,72 @@
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="color-scheme" content="light dark">
<meta name="supported-color-schemes" content="light dark">
<title>You're invited to RenewCMS</title>
<style>
body { margin: 0; padding: 0; width: 100%; -webkit-text-size-adjust: 100%; }
table { border-collapse: collapse; }
a { color: #111111; }
@media (max-width: 620px) {
.rc-card { padding: 28px 20px !important; }
.rc-btn a { display: block !important; }
}
@media (prefers-color-scheme: dark) {
.rc-bg { background-color: #0a0a0a !important; }
.rc-card { background-color: #111111 !important; border-color: #333333 !important; }
.rc-h1, .rc-word { color: #fafafa !important; }
.rc-text { color: #e6e4e0 !important; }
.rc-muted { color: #999999 !important; }
.rc-mark { border: 1px solid #444444 !important; }
.rc-btn td { background-color: #fafafa !important; }
.rc-btn a { background-color: #fafafa !important; color: #111111 !important; border-color: #fafafa !important; }
.rc-url { color: #e6e4e0 !important; background-color: #1a1a1a !important; }
.rc-rule { border-color: #333333 !important; }
}
</style>
</head>
<body class="rc-bg" style="margin:0;padding:0;background-color:#fafafa;">
<div style="display:none;max-height:0;overflow:hidden;opacity:0;color:transparent;">{{.InvitedBy}} invited you to work on articles in RenewCMS. The invite expires in 3 days.</div>
<table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" class="rc-bg" style="background-color:#fafafa;">
<tr>
<td align="center" style="padding:40px 12px;">
<table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" style="max-width:600px;">
<tr>
<td style="padding:0 0 20px 0;">
<table role="presentation" cellpadding="0" cellspacing="0" border="0">
<tr>
<td class="rc-mark" width="32" height="32" align="center" valign="middle" bgcolor="#111111" style="width:32px;height:32px;background-color:#111111;color:#ffffff;font-family:Arial,Helvetica,sans-serif;font-size:19px;font-weight:bold;line-height:32px;">R</td>
<td class="rc-word" style="padding-left:10px;font-family:'IBM Plex Sans',Arial,Helvetica,sans-serif;font-size:17px;font-weight:600;color:#111111;">RenewCMS</td>
</tr>
</table>
</td>
</tr>
<tr>
<td class="rc-card" style="background-color:#ffffff;border:1px solid #e6e4e0;padding:40px;font-family:'IBM Plex Sans',Arial,Helvetica,sans-serif;">
<h1 class="rc-h1" style="margin:0 0 16px 0;font-size:24px;line-height:32px;font-weight:600;color:#111111;">You're invited to RenewCMS</h1>
<p class="rc-text" style="margin:0 0 28px 0;font-size:16px;line-height:26px;color:#222222;">{{.InvitedBy}} invited you to write and publish articles in RenewCMS at {{.Host}}. Accept to choose a username and password. You'll sign in with your own account.</p>
<table role="presentation" cellpadding="0" cellspacing="0" border="0" class="rc-btn">
<tr>
<td bgcolor="#111111" style="background-color:#111111;">
<a href="{{.Host}}/invite/accept?c={{.VerificationCode}}" target="_blank" style="display:inline-block;padding:14px 24px;border:1px solid #111111;background-color:#111111;color:#ffffff;font-family:'IBM Plex Sans',Arial,Helvetica,sans-serif;font-size:16px;font-weight:600;line-height:20px;text-decoration:none;text-align:center;">Accept invite</a>
</td>
</tr>
</table>
<p class="rc-muted" style="margin:16px 0 0 0;font-size:14px;line-height:22px;color:#666666;">This invite was sent to {{.Email}}. It expires in 3 days and works once.</p>
<p class="rc-muted" style="margin:28px 0 8px 0;font-size:14px;line-height:22px;color:#666666;">If the button doesn't work, copy this address into your browser:</p>
<p class="rc-url" style="margin:0;padding:10px 12px;background-color:#f3f2f0;font-family:'IBM Plex Mono',Menlo,Consolas,monospace;font-size:13px;line-height:20px;color:#222222;word-break:break-all;">{{.Host}}/invite/accept?c={{.VerificationCode}}</p>
<p class="rc-text rc-rule" style="margin:28px 0 0 0;padding-top:20px;border-top:1px solid #e6e4e0;font-size:14px;line-height:22px;color:#222222;">Not expecting this? Ignore this email and no account will be created. If the invite has expired, ask {{.InvitedBy}} to send a new one.</p>
</td>
</tr>
<tr>
<td class="rc-muted" style="padding:20px 0 0 0;font-family:'IBM Plex Sans',Arial,Helvetica,sans-serif;font-size:12px;line-height:18px;color:#666666;">RenewCMS · {{.Host}}</td>
</tr>
</table>
</td>
</tr>
</table>
</body>
</html>
+153 -3
View File
@@ -74,14 +74,121 @@ Every state is drawn at desktop and mobile on the screen boards, with final copy
| Editor | `/article/:id/edit` | Near the limit | At least 9 000 HTML characters | [editor](screens/editor.md) | | Editor | `/article/:id/edit` | Near the limit | At least 9 000 HTML characters | [editor](screens/editor.md) |
| Editor | `/article/:id/edit` | Too long | Over 10 000: Save and Publish disabled | [editor](screens/editor.md) | | Editor | `/article/:id/edit` | Too long | Over 10 000: Save and Publish disabled | [editor](screens/editor.md) |
| Editor | `/article/:id/edit` | Preview | Switch on | [editor](screens/editor.md) | | Editor | `/article/:id/edit` | Preview | Switch on | [editor](screens/editor.md) |
| Editor | `/article/:id/edit` | Uploading, rejected, inserted | ImageUploader | [editor](screens/editor.md) | | Editor | `/article/:id/edit` | Choose, crop and resize, uploading, rejected, inserted | ImageUploader | [editor](screens/editor.md) |
| Editor | `/article/:id/edit` | Publishing, unpublishing | PATCH publish or unpublish | [editor](screens/editor.md) | | Editor | `/article/:id/edit` | Publishing, unpublishing | PATCH publish or unpublish | [editor](screens/editor.md) |
| Editor | `/article/:id/edit` | Leave guard | Navigating away while dirty | [editor](screens/editor.md) | | Editor | `/article/:id/edit` | Leave guard | Navigating away while dirty | [editor](screens/editor.md) |
| Editor | `/article/:id/edit` | Offline | navigator.onLine is false | [editor](screens/editor.md) | | Editor | `/article/:id/edit` | Offline | navigator.onLine is false | [editor](screens/editor.md) |
| Editor | `/article/:id/edit` | Deleted | 204: /article with toast | [editor](screens/editor.md) | | Editor | `/article/:id/edit` | Deleted | 204: /article with toast | [editor](screens/editor.md) |
| Editor | `/article/:id/edit` | Session expired | 401: draft kept in sessionStorage, then /login | [editor](screens/editor.md) | | Editor | `/article/:id/edit` | Session expired | 401: draft kept in sessionStorage, then /login | [editor](screens/editor.md) |
| Media | `/media` | Grid, many images | Default view | [media](screens/media.md) |
| Media | `/media` | Grid, few images | Three images | [media](screens/media.md) |
| Media | `/media` | List view | The list icon in the toggle | [media](screens/media.md) |
| Media | `/media` | Loading | The first load, a retry, or a change of search or filter | [media](screens/media.md) |
| Media | `/media` | Empty library, first run | Zero images | [media](screens/media.md) |
| Media | `/media` | No results | Search or filter matched nothing | [media](screens/media.md) |
| Media | `/media` | Hover, focus and keyboard | Hover (second item) darkens the border, adds the pop shadow and reveals the checkbox | [media](screens/media.md) |
| Media | `/media` | Selection and bulk bar | Checkbox on any item, or Space | [media](screens/media.md) |
| Media | `/media` | Bulk delete: confirm | Delete in the bulk bar | [media](screens/media.md) |
| Media | `/media` | Bulk delete: in progress | Requests in flight | [media](screens/media.md) |
| Media | `/media` | Bulk delete: partly failed | Some requests failed | [media](screens/media.md) |
| Media | `/media` | Bulk delete: done | 204 for all | [media](screens/media.md) |
| Media | `/media` | Detail panel: in use | Click or Enter on an item | [media](screens/media.md) |
| Media | `/media` | Detail panel: unused | Used in nothing | [media](screens/media.md) |
| Media | `/media` | Detail panel: duplicate | The image has identical copies | [media](screens/media.md) |
| Media | `/media` | Copy URL | Copy URL | [media](screens/media.md) |
| Media | `/media` | Rename: dialog | Rename in the panel | [media](screens/media.md) |
| Media | `/media` | Rename: saving | PATCH in flight | [media](screens/media.md) |
| Media | `/media` | Rename: validation | Empty or only symbols, on submit or blur | [media](screens/media.md) |
| Media | `/media` | Rename: failed | 500 or network failure | [media](screens/media.md) |
| Media | `/media` | Rename: done | 200: the panel title and list update in place | [media](screens/media.md) |
| Media | `/media` | Delete: unused image | Delete in the panel | [media](screens/media.md) |
| Media | `/media` | Delete: image in use | Stronger confirm | [media](screens/media.md) |
| Media | `/media` | Delete: in progress | DELETE in flight | [media](screens/media.md) |
| Media | `/media` | Delete: failed | 500 or network failure | [media](screens/media.md) |
| Media | `/media` | Delete: done | 204: the panel closes, the item leaves the grid and focus moves to the next item | [media](screens/media.md) |
| Media | `/media` | Image already gone (404) | Any action on an image that was deleted elsewhere | [media](screens/media.md) |
| Media | `/media` | Upload: drag over the page | Files dragged onto the page | [media](screens/media.md) |
| Media | `/media` | Upload: several files, mixed | Upload button or drop, several files | [media](screens/media.md) |
| Media | `/media` | Upload: summary | All rows settled | [media](screens/media.md) |
| Media | `/media` | Upload: rejected files (413, 400) | Type and size are checked in the browser first, so nothing is sent | [media](screens/media.md) |
| Media | `/media` | Upload: too many requests (429) | Rate limited | [media](screens/media.md) |
| Media | `/media` | Duplicates: groups | The Duplicates tab | [media](screens/media.md) |
| Media | `/media` | Duplicates: empty | No groups | [media](screens/media.md) |
| Media | `/media` | Merge: confirm | "Merge into this one" on floorboards.jpg | [media](screens/media.md) |
| Media | `/media` | Merge: in progress | Request in flight | [media](screens/media.md) |
| Media | `/media` | Merge: failed | 500 or network failure | [media](screens/media.md) |
| Media | `/media` | Merge: conflict (409) | A copy was deleted, or a new copy appeared, since the page loaded | [media](screens/media.md) |
| Media | `/media` | Merge: done | 200: the group leaves the list | [media](screens/media.md) |
| Media | `/media` | List failed to load | A 500 or network failure on the list request | [media](screens/media.md) |
| Media | `/media` | Offline | navigator.onLine is false | [media](screens/media.md) |
| Media picker | `/article/:id/edit` | Upload tab | The image button in the toolbar | [media-picker](screens/media-picker.md) |
| Media picker | `/article/:id/edit` | Upload tab: already in your library | A chosen file has the same content as an existing image | [media-picker](screens/media-picker.md) |
| Media picker | `/article/:id/edit` | Library: loading | The Library tab was opened, or a search changed | [media-picker](screens/media-picker.md) |
| Media picker | `/article/:id/edit` | Library: nothing selected | Newest first | [media-picker](screens/media-picker.md) |
| Media picker | `/article/:id/edit` | Library: selected | One image selected (single selection) | [media-picker](screens/media-picker.md) |
| Media picker | `/article/:id/edit` | Library: alt text entered | Alt text is optional | [media-picker](screens/media-picker.md) |
| Media picker | `/article/:id/edit` | Library: loading more | "Load more" pressed | [media-picker](screens/media-picker.md) |
| Media picker | `/article/:id/edit` | Library: empty | Zero images | [media-picker](screens/media-picker.md) |
| Media picker | `/article/:id/edit` | Library: no results | Search matched nothing | [media-picker](screens/media-picker.md) |
| Media picker | `/article/:id/edit` | Library: failed to load | A 500 or network failure | [media-picker](screens/media-picker.md) |
| Media picker | `/article/:id/edit` | Inserted | Insert image from either tab | [media-picker](screens/media-picker.md) |
| Media picker | `/article/:id/edit` | Remove image: confirm | Remove image on an image in the article | [media-picker](screens/media-picker.md) |
| Media picker | `/article/:id/edit` | Removed | Confirmed | [media-picker](screens/media-picker.md) |
| Integration | `/integration` | Default | Page load | [integration](screens/integration.md) | | Integration | `/integration` | Default | Page load | [integration](screens/integration.md) |
| Integration | `/integration` | Copied | Copy clicked (2 s) | [integration](screens/integration.md) | | Integration | `/integration` | Copied | Copy clicked (2 s) | [integration](screens/integration.md) |
| Users | `/users` | Default | List loaded, newest first | [users](screens/users.md) |
| Users | `/users` | Loading | First load or retry | [users](screens/users.md) |
| Users | `/users` | Only you | Nobody invited yet | [users](screens/users.md) |
| Users | `/users` | Error | 500 or network | [users](screens/users.md) |
| Users | `/users` | Invite: default, validation, sending | Invite modal opened, invalid email, POST in flight | [users](screens/users.md) |
| Users | `/users` | Invite: already a user | 409 | [users](screens/users.md) |
| Users | `/users` | Invite: failed | 500, network or mail failure | [users](screens/users.md) |
| Users | `/users` | Invite sent | 201: dialog closes, Pending row on top, toast | [users](screens/users.md) |
| Users | `/users` | Cancel invite: confirm, sending, failed | "Cancel invite" on a Pending row; DELETE in flight; 500 or network | [users](screens/users.md) |
| Users | `/users` | Cancel invite: done | 204: row removed, toast | [users](screens/users.md) |
| Users | `/users` | Renew invite: sending | "Renew invite" on an Expired row; POST in flight | [users](screens/users.md) |
| Users | `/users` | Renew invite: done | 200: row Pending on top, toast | [users](screens/users.md) |
| Users | `/users` | Renew invite: failed | 500 or network: toast, row stays Expired | [users](screens/users.md) |
| Settings | `/settings` | Up to date | Opened with no newer version | [settings](screens/settings.md) |
| Settings | `/settings` | Checking | Check for updates pressed, or the first open after 24 hours | [settings](screens/settings.md) |
| Settings | `/settings` | Check failed | Offline, or the update server didn't answer (500, network) | [settings](screens/settings.md) |
| Settings | `/settings` | Update available | A newer version exists | [settings](screens/settings.md) |
| Settings | `/settings` | Update available, notes open | "What's new in 2.3.0" expanded | [settings](screens/settings.md) |
| Settings | `/settings` | Downloading | Update pressed (202) | [settings](screens/settings.md) |
| Settings | `/settings` | Verifying | The download finished | [settings](screens/settings.md) |
| Settings | `/settings` | Ready to install | The file passed its checks | [settings](screens/settings.md) |
| Settings | `/settings` | Restart: confirm | Restart pressed | [settings](screens/settings.md) |
| Settings | `/settings` | Restart: request failed | 500 or network failure before the restart began | [settings](screens/settings.md) |
| Settings | `/settings` | Restarting to install | Full-page overlay, so it survives the server going away | [settings](screens/settings.md) |
| Settings | `/settings` | Restarting, taking longer | No answer after 60 seconds | [settings](screens/settings.md) |
| Settings | `/settings` | Update done | The page reloaded on the new version | [settings](screens/settings.md) |
| Settings | `/settings` | Update failed, rolled back | The site came back on v2.2.0-beta | [settings](screens/settings.md) |
| Settings | `/settings` | Download failed | A 500, or the connection dropped | [settings](screens/settings.md) |
| Settings | `/settings` | Verification failed | The downloaded file isn't trusted | [settings](screens/settings.md) |
| Settings | `/settings` | Too many requests (429) | Retry-After counted down in the button | [settings](screens/settings.md) |
| Settings | `/settings` | Not prepared | The server can't update from the browser | [settings](screens/settings.md) |
| Settings | `/settings` | Not prepared: command copied | Copy pressed | [settings](screens/settings.md) |
| Settings | `/settings` | Plain restart: confirm | Restart with no update waiting | [settings](screens/settings.md) |
| Settings | `/settings` | Plain restart: restarting | Same overlay as the update restart with shorter copy | [settings](screens/settings.md) |
| Settings | `/settings` | Plain restart: done | The page reloaded | [settings](screens/settings.md) |
| Settings | `/settings` | Admin view | Admins see the version and the note, with no buttons | [settings](screens/settings.md) |
| Settings | `/settings` | Role changed (403) | An owner was changed to admin while the page was open and pressed a button | [settings](screens/settings.md) |
| Settings | `/settings` | Update already running (409) | Another owner started it | [settings](screens/settings.md) |
| Home | `/home` | Update available (owner) | Owner only: quiet banner and Settings pill | [home](screens/home.md) |
| Home | `/home` | Update ready to install (owner) | Download checked: banner copy changes | [home](screens/home.md) |
| Profile | `/profile` | Account menu | Account chip clicked | [profile](screens/profile.md) |
| Profile | `/profile` | Loading | Opened by URL before /auth/me returns | [profile](screens/profile.md) |
| Profile | `/profile` | Default, no display name | First visit | [profile](screens/profile.md) |
| Profile | `/profile` | Editing, too long | Typing; over 60 characters | [profile](screens/profile.md) |
| Profile | `/profile` | Saving, saved, save failed | PATCH in flight, 200, 500 or network | [profile](screens/profile.md) |
| Profile | `/profile` | Reset: sending, sent, 429, failed | POST /v1/auth/password-reset | [profile](screens/profile.md) |
| Profile | `/profile` | Display names in the Users list | Accounts with a display name | [profile](screens/profile.md) |
| Accept invite | `/invite/accept?c=` | Checking the link | On load: GET invite | [accept-invite](screens/accept-invite.md) |
| Accept invite | `/invite/accept?c=` | Default, validation errors, filled, submitting | Valid, unused code; email read-only | [accept-invite](screens/accept-invite.md) |
| Accept invite | `/invite/accept?c=` | Username taken | 409 | [accept-invite](screens/accept-invite.md) |
| Accept invite | `/invite/accept?c=` | Invalid or used, expired | 404 or no c parameter, 410 | [accept-invite](screens/accept-invite.md) |
| Accept invite | `/invite/accept?c=` | Server error | 500 or network | [accept-invite](screens/accept-invite.md) |
| Accept invite | `/invite/accept?c=` | Success | 200: logged in, /home with toast | [accept-invite](screens/accept-invite.md) |
## HTTP status to copy ## HTTP status to copy
@@ -98,18 +205,61 @@ Response bodies are plain text and are never shown. `useApi` throws an `ApiError
| 403 | Verify | "This verification link doesn't work." Offers Cancel registration and start over | ResultPanel | | 403 | Verify | "This verification link doesn't work." Offers Cancel registration and start over | ResultPanel |
| 403 | Cancel registration | "Your account is already verified." Goes to /home | Toast | | 403 | Cancel registration | "Your account is already verified." Goes to /home | Toast |
| 403 | Reset confirm | "This reset link has expired." Offers Request a new link | ResultPanel | | 403 | Reset confirm | "This reset link has expired." Offers Request a new link | ResultPanel |
| 409 | Invite | "This address already has an account." or, for a live invite, "There's already a pending invite for this address." | Field error |
| 404 | Accept invite | "This invite link doesn't work." Offers Go to log in | ResultPanel |
| 409 | Accept invite | "That username is taken. Try another." | Field |
| 410 | Accept invite | "This invite has expired. Ask the person who invited you to send a new one." | ResultPanel |
| 404 | Editor load | "This article doesn't exist." Offers All articles | ErrorView | | 404 | Editor load | "This article doesn't exist." Offers All articles | ErrorView |
| 404 | Row or editor action | "That article no longer exists." The row is removed | Toast | | 404 | Row or editor action | "That article no longer exists." The row is removed | Toast |
| 404 | Unknown route | "Page not found" | ErrorView | | 404 | Unknown route | "Page not found" | ErrorView |
| 429 | Profile, reset link | "Too many requests. You've asked for several links recently. Wait a few minutes, then try again." Button disabled | Note |
| 429 | Log in, reset request | "Too many attempts. For your security, wait a moment before trying again." With a countdown | Alert + disabled button | | 429 | Log in, reset request | "Too many attempts. For your security, wait a moment before trying again." With a countdown | Alert + disabled button |
| 500 | Save | "Save failed" + Retry. Changes are kept | SaveStatus | | 500 | Save | "Save failed" + Retry. Changes are kept | SaveStatus |
| 500 | Publish / unpublish | "Couldn't publish" / "Couldn't unpublish" + Retry | Toast | | 500 | Publish / unpublish | "Couldn't publish" / "Couldn't unpublish" + Retry | Toast |
| 500 | Load users | "Couldn't load users. Check your connection and try again." + Try again | Alert |
| 500 | Cancel invite | "Couldn't cancel the invite. Try again in a moment." The dialog stays open | Notice in dialog |
| 500 | Renew invite | "Couldn't renew the invite. Try again in a moment." The row stays Expired | Toast |
| 500 | Invite | "Couldn't send the invite. Try again in a moment." The address stays | Alert in dialog |
| 500 | Save display name | "Couldn't save your display name. Your text is still here. Try again in a moment." | Alert in card |
| 500 | Send reset link (profile) | "Couldn't send the link. Check your connection and try again." | Note |
| 500 | Delete | "Couldn't delete the article, so it's still there. Try again in a moment." | Inline in dialog | | 500 | Delete | "Couldn't delete the article, so it's still there. Try again in a moment." | Inline in dialog |
| 500 | Upload | "Upload failed. The server didn't accept the file. Your article hasn't changed." | ImageUploader | | 500 | Upload | "Upload failed. The server didn't accept the file. Your article hasn't changed." | ImageUploader |
| network | Anywhere | "Couldn't reach RenewCMS. Check your connection and try again." Offline: banner | Alert / toast / banner | | network | Anywhere | "Couldn't reach RenewCMS. Check your connection and try again." Offline: banner | Alert / toast / banner |
## API the design marked pending ## API the design marked pending
All four now exist: `GET /v1/auth/me`, `GET /v1/auth/registration`, `429` with `Retry-After` on `/v1/auth/login` and `/v1/auth/password-reset`, and `/static/uploadedImages/*`. Still not supported, so shown disabled or omitted: Existing: `GET /v1/auth/me`, `GET /v1/auth/registration`, `429` with `Retry-After` on `/v1/auth/login` and `/v1/auth/password-reset`, and `/static/uploadedImages/*`.
Renaming a title (shown read-only, with an explanation in Details), resending the verification email (the pending page explains how to start over), changing the password while logged in, editing the profile or email, listing or deleting individual images, multiple users. Added by the Users and Profile screens, none of which exist yet:
- `GET /v1/user/`: the users and their invites, newest first.
- `POST /v1/user/invite`: sends an invitation email. 201, 409 for an existing account or a live pending invite.
- `DELETE /v1/user/invite/:id`: cancels a Pending invite. 204. Owner only.
- `POST /v1/user/invite/:id/renew`: replaces the code, resets the 3 days and created date, and resends the email. 200 with the invite. Owner only.
- `GET /v1/user/` and `GET /v1/auth/me` gain a `role` ("owner" or "admin"); the list gains `email` on accepted users.
- `POST /v1/user/invite` becomes owner only, and always creates an admin.
- `GET /v1/settings`: `{ "version": "..." }`.
- `PATCH /v1/user/me`: saves the display name. `GET /v1/auth/me` returns it.
- `GET /v1/auth/invite?c=CODE`: looks up the invite on load, returns `{ email }`, 404 or 410. `POST /v1/auth/invite/accept` takes `{ code, username, password }` and returns 200 with the session cookie, 409 for a taken username, 404 or 410.
Still not supported, so shown disabled or omitted:
Renaming a title (shown read-only, with an explanation in Details), resending the verification email (the pending page explains how to start over), changing the email or username, removing users, promoting or demoting anyone, and any role other than owner and admin. Changing the password while logged in works only through the emailed reset link on the Profile page.
Added by the Updates card, none of which exists yet (owner only unless noted, see [settings](screens/settings.md)):
- `GET /v1/system/update` (any verified user): `{ current, latest, available, notes: { version, released_at, items }, checked_at, can_apply, state, progress, error, started_at }`. `state` is `idle`, `downloading`, `verifying`, `ready`, `restarting`, `succeeded` or `failed`. `can_apply` is false when the server hasn't been prepared, or for admins.
- `POST /v1/system/update/check`: asks the release feed. 200, 429 with `Retry-After`, 500 when the feed can't be reached.
- `POST /v1/system/update/download`: 202 starts the download and verification, 400 when there is nothing to update, 403, 409 when one is already running or the server isn't prepared, 422 when the file fails verification, 429.
- `POST /v1/system/update/restart`: 202 starts the install and restart (or only a restart when no update is ready), 403, 409, 500.
- A restart must survive the server going away: the SPA polls `/healthz` and `GET /v1/system/update` until they answer.
Added by the Media screens, none of which exist yet:
- `GET /v1/media/?q=&filter=&sort=&limit=&cursor=&hash=`: the library, newest first by default. `hash` (SHA-256 hex) returns only the images with that content, which is how the browser checks for a duplicate before uploading. Each item carries `id`, `filename`, `url`, `size`, `content_type`, `width`, `height` (null for SVG), `uploaded_by`, `created_at`, `used_in` (count) and `duplicate` (bool). The response also carries the counts for the Unused and Duplicates tabs.
- `POST /v1/media/`: multipart `file`, no article id. 201 with the item. It always stores the file: the duplicate check happens in the browser (hash with `crypto.subtle`, then `GET /v1/media/?hash=`), and when `crypto.subtle` is unavailable the check is skipped and any duplicate shows up under Duplicates. The server keeps each image's SHA-256. 413 for over 10 MB, 415 for another type, 400 for an unreadable image, 429 with `Retry-After`.
- `PATCH /v1/media/{id}`: `{ filename }`, the extension is kept and the URL does not change. 200, 404.
- `DELETE /v1/media/{id}`: 204, 404. Deleting an image that is in use is allowed.
- `POST /v1/media/merge`: `{ keep_id, merge_ids }`. Rewrites article bodies from the merged copies' URLs to the kept image's URL, then deletes the copies. 200 with `{ articles_updated, merged }`, 404, 409 when a listed copy is gone or the group changed.
- `GET /v1/media/{id}/usage`: `[{ id, title, published }]`, read from article bodies.
- Images no longer belong to an article, and deleting an article no longer deletes images. `POST /v1/article/{id}/image` and `DELETE /v1/article/{id}/image/{imageId}` are replaced by the endpoints above.
+19 -1
View File
@@ -57,6 +57,8 @@ task --list # everything available
task test # Go tests; extra args pass through: task test -- -run TestCreateArticle -v task test # Go tests; extra args pass through: task test -- -run TestCreateArticle -v
task cover # coverage of the use cases → tmp/coverage.out task cover # coverage of the use cases → tmp/coverage.out
task mutate # gremlins mutation testing → tmp/gremlins.json task mutate # gremlins mutation testing → tmp/gremlins.json
task test:web # SPA component tests (Vitest)
task visual:check -- log-in # screenshot design vs SPA for a screen → tmp/visual/log-in/
task lint # gofmt check, go vet, eslint --fix, vue-tsc task lint # gofmt check, go vet, eslint --fix, vue-tsc
task fmt # gofmt -w + prettier task fmt # gofmt -w + prettier
task run # build the production binary and run it (SPA embedded) on :8080 task run # build the production binary and run it (SPA embedded) on :8080
@@ -67,7 +69,23 @@ task clean # remove bin/, tmp/ and the built SPA
- All Go tests live in [`test/`](../test) (package `test`, black-box). They use in-memory fakes of the domain `Repository` interfaces, so they need no database, SMTP server or network. - All Go tests live in [`test/`](../test) (package `test`, black-box). They use in-memory fakes of the domain `Repository` interfaces, so they need no database, SMTP server or network.
- HTTP-level tests use `net/http/httptest` against a chi router. Call `validator.InitValidator()` before invoking a handler. - HTTP-level tests use `net/http/httptest` against a chi router. Call `validator.InitValidator()` before invoking a handler.
- The frontend has no test runner yet. `task lint:web` runs eslint and a type check. - SPA component tests use Vitest + Vue Test Utils (`task test:web`). `task lint:web` runs eslint and a type check.
## Visual check against the design
`task visual:check -- <screen> [state]` compares the SPA with the Claude Design boards in [`docs/design/source`](design/source). The screen is a file name from [`docs/design/screens`](design/screens) (`log-in`, `home`, …), and the state is one of its headings.
- It builds the SPA into `tmp/visual/dist` and serves both the build and the boards locally, so no API or dev server is needed.
- For every state it screenshots:
- the board's frame for that state;
- the SPA in the same state, at 1440×900 and 390×844, in light and dark.
- It saves `design-*.png`, `app-*.png` and `diff-*.png` (differing pixels in red) to `tmp/visual/<screen>/<state>/`, and a summary to `tmp/visual/<screen>/report.md`.
- [`web/visual/states.ts`](../web/visual/states.ts) says how to reach each state in the SPA: the route, the mocked `/v1` responses (keyed `'METHOD /v1/path'`) and any user steps. A state without an entry is captured on the design side only, and marked "design only" in the report.
- Narrow a run with `--viewport=desktop|mobile` and `--theme=light|dark`.
- Lucide icons are served from the local `@iconify-json/lucide` set, for both the boards and the SPA. api.iconify.design rate-limits repeated runs.
- The first time on a machine, run `bunx playwright install chromium` in `web/`.
The pixel percentage only points at where to look, because font anti-aliasing always differs a little. Judge by comparing the image pairs.
## Data ## Data
+31
View File
@@ -0,0 +1,31 @@
# Release notes format
Name: `vX.Y.Z-beta - Short theme` (theme is 2 to 6 words, sentence case).
Tag: `vX.Y.Z-beta`, always with the `v`.
Body, in this order. Omit a section only when it would be empty, except Upgrading, which is always present.
1. Intro: one or two plain sentences on what the release is about. No heading.
2. `## New`: user-visible features. Group with a bold title line (`**Group name**`) followed by bullets.
3. `## Improvements and fixes`: flat bullets.
4. `## API`: one bullet per endpoint change, `METHOD /v1/path` in backticks, then behaviour and status codes. Prefix breaking or shape changes with "Changed:".
5. `## Under the hood`: dependencies, tests, docs, architecture. Only when relevant to contributors.
6. `## Upgrading`: binary replacement, schema/migration changes, new env vars, behaviour changes for existing installs.
7. `## Known limitations`: only when there are real ones.
Rules: bullets are full sentences ending with a period; user-facing wording, no commit prefixes; sentence-case headings; no horizontal rules, no metadata block, no "Pre-1.0" boilerplate (the prerelease flag says it); every release ships all 6 binaries from `task release`.
## Published releases
Each body lives in `docs/releases/<tag>.md`. Publish with `tea releases create --tag <tag> --title "<name>" --note-file docs/releases/<tag>.md --prerelease --asset <file>` after `task release`, with one `--asset` per file: the six binaries, `bin/checksums.txt` and `bin/checksums.txt.sig`. `task release` produces all eight and fails before building when the signing key is missing or wrong (see [deployment.md](deployment.md#release-signing-key-maintainers-once)). Never publish a release without the two checksum files.
| Tag | Name |
| --- | --- |
| `2.0.0-beta` (legacy tag without the `v`, kept as is) | v2.0.0-beta - Vue 3 SPA and domain-driven backend |
| `v2.1.0-beta` | v2.1.0-beta - Image upload in the editor |
| `v2.2.0-beta` | v2.2.0-beta - Image crop, image removal & reset screens |
| `v2.3.0-beta` | v2.3.0-beta - Multi-user invitations, display names & profile page |
| `v2.4.0-beta` | v2.4.0-beta - Owner role, invite management & Settings page |
| `v2.5.0-beta` | v2.5.0-beta - Media library & image picker |
| `v2.6.0-beta` | v2.6.0-beta - Signed updates and browser restart |
| `v2.6.2-beta` | v2.6.2-beta - English and French interface |
+28
View File
@@ -0,0 +1,28 @@
A ground-up rewrite of RenewCMS's backend architecture and frontend. The Go-template UI is replaced by a Vue 3 single-page app embedded in the same binary.
## New
**Vue 3 single-page app**
- Built with Vite, Pinia and vue-router, and embedded into the single binary. There is no separate frontend deployment.
- The UI uses Nuxt UI (migrated from an initial PrimeVue base) with shared design tokens.
- New screens: login, registration, home and navigation, article list, article editor (ProseMirror-based) with a creation modal, image upload, and an account and integration screen.
- A typed API client and a session store handle 401, unverified 403, 429 and offline states the same way everywhere.
**Domain-driven backend**
- `internal/domain` (entities, sentinel errors, repository interfaces) is isolated from persistence (GORM), mailer and API concerns, with a strict inward dependency rule.
- Business logic moved out of handlers and the persistence layer into use cases: article rules, image validation, password and code hashing, not-found handling, and session invalidation on password reset.
- The composition root (`api/dependecyInjection.go`) wires the database, repositories and use cases explicitly. Runtime settings are read once at startup.
- The auth handler is split into dedicated registration, login, verification and password-reset handlers, each with per-client rate limiting on the public routes.
## Improvements and fixes
- API responses no longer leak password hashes, verification or reset code hashes, or their expiry dates.
- Article read rules now apply the same way to the single-article and list endpoints: the public sees online articles only, verified users also see offline ones.
- Registration only opens when no verified account exists, and deleting a user frees its username and email for reuse.
- Rate limiting now keys off the real peer IP.
## Under the hood
- Use cases are covered by a full in-memory fake test suite with clean gremlins mutation coverage.
- Vitest and Vue Test Utils run the frontend tests, and an automated visual-parity check compares the app to the design source boards.
## Upgrading
- Deployment is unchanged: a single binary, systemd and a reverse proxy. Replace the binary and restart.
+20
View File
@@ -0,0 +1,20 @@
This release adds image upload to the article editor and fixes several rough edges from v2.0.0-beta.
## New
**Image upload in the article editor**
- The editor's Image toolbar button, or dropping a file onto the editor, opens an upload dialog.
- Choose or drop a PNG, JPEG, WEBP or SVG file up to 10 MB. Progress is shown live, and the image is inserted at the cursor as soon as it is uploaded.
- Invalid files (wrong type or too large) are rejected in the browser before anything is sent. The same wording is reused if the server rejects a file the browser let through.
- A failed upload leaves the article untouched and offers a retry.
## Improvements and fixes
- Uploaded images now render in the editor and the article body. The dev server proxy was missing a route for the endpoint that serves them.
- Clicking a row in the article list now opens the editor. The row-click handler was reading the wrong argument.
- The article details panel's copy URL control now copies the link and confirms with a toast.
- The user menu's dropdown trigger no longer misrenders when the sidebar is collapsed.
- The sidebar's collapsed or expanded state is remembered across reloads.
- Smaller styling and layout fixes in the article details panel, editor toolbar and new-article dialog.
## Upgrading
- Replace the binary and restart.
+32
View File
@@ -0,0 +1,32 @@
This release reworks image handling in the article editor and brings the password-reset screens up to the new design.
## New
**Crop and resize before upload**
- A Crop and resize step now sits between picking an image and uploading it. It applies to JPEG, PNG and WEBP files. SVG files still upload straight away.
- Move or resize the crop frame by dragging it or its handles. Arrow keys nudge it by 1 px, and Shift+arrow resizes it by 1 px.
- Aspect ratios: Original, Free, 16:9, 4:3 and 1:1.
- Rotate and Reset buttons.
- Output width presets: Original, 1600 px (default), 1200 px and 800 px. The output is never wider than the crop frame.
- A live line shows the final pixel size and an approximate file size before you upload.
**Remove images from the editor**
- Images in an article can now be removed from the editor. The image file and its database row are both deleted.
- The editor renders images as a dedicated image node.
**Password-reset screens**
- The Forgot password and Reset password screens follow the new design and cover every state in the spec.
## API
- `DELETE /v1/article/{id}/image/{imageId}` (authenticated) deletes an image. It returns 204 on success, 404 for an unknown article or image, and 400 for an ID that isn't a valid uint32.
- Changed: `POST /v1/article/{id}/image` now returns `{"id": …, "location": …}` instead of `{"location": …}`. The change is additive, but anything parsing the response strictly should be checked.
## Under the hood
- The editor now depends on `@tiptap/extension-image`, `@tiptap/pm` and `@tiptap/vue-3`, all pinned to 3.31.3.
- New feature specs and QA procedures cover crop and resize, image removal and both reset screens.
- New Go HTTP tests cover image deletion, and Vitest specs were added and updated for the editor and reset views.
- The visual-check states cover the new screens, and the design docs are updated to match.
## Upgrading
- No new environment variables and no schema changes.
- Replace the binary and restart.
+43
View File
@@ -0,0 +1,43 @@
RenewCMS is no longer a one-person tool. The admin can now invite other people, each with their own account and the exact same access, and everyone can set a display name.
## New
**Invite other users**
- A new Users page in the back-office lists everyone who can sign in, plus pending and expired invites, with a status badge for each.
- Invite user sends an email with a personal link. The link works once and expires after 3 days.
- Invited people choose their own username and password on a new Accept invite screen, and land on Home already logged in.
- Everyone shares one workspace: same articles, same images, same access.
- Registration stays closed to everyone who wasn't invited.
- A new invitation email template supports light and dark mode.
**Display name and profile**
- A new Profile page is opened from the account menu at the bottom of the sidebar.
- Set an optional display name (up to 60 characters). It replaces your username in the sidebar, the account menu, the Home greeting, the Users list and the emails RenewCMS sends. Clear it to go back to your username.
- Send yourself a password reset link from the Profile page.
- The account chip now opens a menu with Profile and Log out, and keeps the System, Light and Dark theme choice.
## Improvements and fixes
- Accepting an invite is atomic: two simultaneous requests with the same link can only create one account.
- The Accept invite screen shows a retry option instead of a permanent spinner when the invite can't be loaded.
- Invite email validation is now the same in the browser and on the server.
- The mobile account sheet reports its open state correctly and returns focus to the account chip when it closes.
- A failed password reset email is now logged on the server. The response is unchanged.
## API
- `PATCH /v1/user/me` sets the display name.
- `GET /v1/auth/me` and `POST /v1/auth/verify` now return `display_name`.
- `GET /v1/user/` lists users and invites.
- `POST /v1/user/invite` sends an invite and is rate limited.
- `GET /v1/auth/invite` and `POST /v1/auth/invite/accept` power the Accept invite screen.
## Under the hood
- Deleting a user now goes through the persistence model.
## Upgrading
- Download the binary for your platform, replace the old one and restart. Your `.env` and SQLite file stay as they are.
- The database migrates itself on startup. It adds a `display_name` column to `users` and a new `invites` table. Existing data is untouched. Back up your SQLite file first as a precaution.
- Invitation emails need working SMTP settings, like the verification and reset emails already do. No new environment variables.
## Known limitations
- Users and invites can't be removed, revoked or resent yet, and there are no roles: everybody is an equal admin.
- Invited addresses that already have an account are rejected. An expired invite can be replaced by sending a new one.
+42
View File
@@ -0,0 +1,42 @@
RenewCMS now knows who owns the workspace. The owner manages invites, including cancelling and renewing them, while every admin keeps the same access to content. A new Settings page shows which build is running.
## New
**Owner and admin roles**
- The first registered account is the owner. Everyone who joins through an invite is an admin.
- Only the owner can send, cancel or renew invites. Admins keep the same access to articles, images, the Users list, their Profile and Settings.
- There is exactly one owner. Roles can't be changed or transferred yet.
- Existing installs are migrated automatically: the oldest account becomes the owner and every other account an admin.
**Invite management**
- Pending invites get a Cancel invite action on the Users page. The invite link stops working.
- Expired invites get a Renew invite action. It sends a new email with a new personal link valid for 3 days, and the old link stays dead.
**Users list**
- The Users table and the mobile card list now show Email, Display name (a dash when empty), Role, Invite status and Created.
- A new role badge tells the owner and admins apart.
**Settings page**
- A new Settings page at `/settings` sits after Integration in the sidebar and the mobile drawer. It shows the version of the running build.
## Improvements and fixes
- The desktop account menu's icons, labels and check mark are now centred in their 32 px rows.
- The account menu follows the redesigned board: System, Light and Dark stay in both the menu and the mobile sheet.
- The article editor's toolbar scrolls horizontally on mobile instead of overflowing.
- The editor's last-saved label now moves from minutes to hours and days instead of counting minutes only.
## API
- `DELETE /v1/user/invite/{id}` cancels a pending invite and returns 204.
- `POST /v1/user/invite/{id}/renew` returns 200 with a new code, sets `expires_at` to now plus 3 days and `created_at` to now, and resends the invitation email.
- Changed: `POST /v1/user/invite` is now owner-only, like the two endpoints above. Other users get 403 with "Only the owner can do this."
- `GET /v1/settings` (authenticated, verified users) returns the running build's version.
- Changed: user objects from `GET /v1/user/`, `GET /v1/auth/me` and `POST /v1/auth/verify` now include `role` (`owner` or `admin`).
## Upgrading
- Replace the binary and restart. Your `.env` and SQLite file stay as they are.
- The database migrates itself on startup. It adds a `role` column to `users` and fills it in: the account with the lowest id becomes the owner, every other account an admin. A database that already has roles is left unchanged. Back up your SQLite file first as a precaution.
- Behaviour change: admins who joined through a v2.3.0-beta invite can no longer send invites.
- No new environment variables.
## Known limitations
- No endpoint changes or transfers the owner role, and users can't be removed yet.
+55
View File
@@ -0,0 +1,55 @@
RenewCMS now has a media library. Every uploaded image lives in one place where you can browse, rename, delete and clean up duplicates, and the article editor can reuse an image you already uploaded.
## New
**Media page**
- A new Media page at `/media` sits between Articles and Users in the sidebar and the mobile drawer.
- Browse the library as a grid or a list, with search by filename, sort by newest, oldest, name or largest, and Unused and Duplicates tabs with counts.
- Open an image to see its type, size, dimensions, uploader, upload date and URL, copy its URL, and see which articles use it.
- Rename an image. Only the filename changes, the URL stays the same, so articles keep working.
- Delete one image or many at once. Deleting an image that is still used asks for a stronger confirmation and lists the articles that will show a broken image.
- Upload several images at once, with a progress row for each one and a summary. Drop files anywhere on the page.
- When you upload a file that is already in the library, you are told so and can use the existing image instead.
- A Duplicates view groups identical images and merges them into one. Articles that used the other copies switch to the one you keep.
**Image picker in the editor**
- The editor's "Add an image" dialog now has Upload and Library tabs. Pick an image you already uploaded, set its alt text and insert it.
- Images already in the article are tagged "In this article".
- Removing an image from an article now only removes it from that article. The file stays in the library.
## Improvements and fixes
- Deleting an article no longer deletes its images, and its confirmation says so.
- An image that no longer exists shows a "This image is no longer available" placeholder in the editor, with a way to remove it, instead of a collapsed pixel.
- Deleted images stop showing as soon as you open an article, not only after a refresh. Uploaded images are now revalidated by the browser instead of being cached for a year.
- The editor's Images row in the article details counts the images in the article body.
## API
- `GET /v1/media/` lists the library with `q`, `filter` (`all`, `unused`, `duplicates`), `sort`, `limit`, `cursor` and `hash` parameters. Each item carries its size, type, dimensions, uploader, `used_in` count and a `duplicate` flag, and the response carries the counts for each tab.
- `POST /v1/media/` uploads an image (multipart `file`). It returns 201, 400 for an unreadable image, 413 for a file over 10 MB and 415 for another type.
- `PATCH /v1/media/{id}` renames an image and keeps its extension and URL. It returns 200, or 404.
- `DELETE /v1/media/{id}` deletes an image, even when articles use it. It returns 204, or 404.
- `POST /v1/media/merge` takes `keep_id` and `merge_ids`, switches the articles that use the other copies to the kept image, deletes the copies and returns how many articles changed. It returns 409 when a copy is gone or the images are no longer identical.
- `GET /v1/media/{id}/usage` lists the articles that use an image, with their title and whether they are online.
- Changed: images no longer belong to an article. `GET /v1/article/{id}` no longer returns `images`, and deleting an article keeps its images.
- Changed: `DELETE /v1/article/{id}/image/{imageId}` and `POST /v1/article/{id}/image` are removed, replaced by the `/v1/media/` endpoints.
- Changed: `/static/uploadedImages/*` now sends `Cache-Control: public, no-cache` instead of a one-year `immutable` lifetime.
## Under the hood
- The image domain, repository, use cases and handlers were rebuilt around a library model, keeping the domain, use-case and infrastructure layering.
- WEBP dimensions are read with `golang.org/x/image`. `golang.org/x/sys` and `golang.org/x/text` were updated with it.
- New feature specs and tests cover the media API, the Media page, uploads, duplicates and the editor picker.
## Upgrading
- Replace the binary and restart. Your `.env`, SQLite file and uploads directory stay as they are, and there are no new environment variables.
- The database migrates itself on startup. It adds columns to the images table, and a one-time backfill reads each existing image file to fill in its size, type, dimensions and content hash. An image whose file is missing is left alone. Back up your SQLite file and uploads directory first as a precaution.
- Existing images become part of the library and are no longer tied to an article. The old article link is no longer used.
- Clients that call the removed article image endpoints, or read `images` from an article, must switch to `/v1/media/`.
- Browsers keep serving images they cached before the upgrade until they are reloaded once.
## Known limitations
- The Media page shows only the first 100 images.
- There is no rate limit on `/v1/media/` yet.
- The library list loads every article and image in memory, so very large libraries will be slow.
- A file whose extension doesn't match its content type, such as a JPEG labelled as PNG, is rejected.
- Searching filenames with non-ASCII letters is case-sensitive.
- Uploaded SVGs are served as they are. They are sandboxed with a restrictive content security policy, but not sanitised.
+46
View File
@@ -0,0 +1,46 @@
RenewCMS can now check for releases, download a signed update and install it from Settings. On Linux with systemd, the owner can restart the site from the browser, with automatic binary rollback if the new version fails to start.
## New
**Updates in Settings**
- Owners can check for a newer release, read its release notes and download it while the site stays online.
- Downloads show progress, verify the release signature and binary checksum, check the staged version and back up the database before becoming ready to install.
- The Home page and Settings navigation show an owner-only update notification, and the Home banner can be dismissed for each version.
- Admins can read the update status without starting an update or restart.
**Browser restart and installation**
- Owners can confirm an update installation or a plain site restart from Settings.
- A restart overlay waits for the site to return and offers a reload action when the restart takes longer than expected.
- Linux installations with systemd can enable browser updates using `renewcms enable-browser-updates` and remove the helper using `renewcms disable-browser-updates`.
- The helper verifies the staged files again, keeps the previous binary and restores it if the new version does not start successfully.
## Improvements and fixes
- Update status and download progress survive navigation and are shared between owners.
- Update checks and download starts have separate per-user rate limits with retry countdowns.
- Restart confirmations identify whether the action installs an update or only restarts the site, and refuse a request when another owner's action has changed that state.
- Completion messages are shown in the browser tab that requested the restart.
## API
- `GET /v1/system/update` returns the current and latest versions, release notes, release URL, helper availability, progress, state, error kind and operation timestamps for verified users, without changing state.
- `POST /v1/system/update/check` checks the release feed for owners and returns 200, 403 for insufficient permissions, 429 with `Retry-After`, or 500 when the feed cannot be reached.
- `POST /v1/system/update/download` starts an owner-only background download with 202, or returns 400 when nothing is available, 403, 409 for an unavailable helper or conflicting job, 422 for a pre-flight refusal, or 429.
- `POST /v1/system/update/restart` accepts an optional `kind` of `update` or `restart` and returns 202, 400 for invalid input, 403, 409 for an unavailable helper or conflicting state, or 500 when the request cannot be saved.
## Under the hood
- Releases include signed `checksums.txt` and `checksums.txt.sig` files alongside the six platform binaries.
- The update helper runs separately from the unprivileged app, copies staged files into a private directory and verifies the bytes it installs rather than trusting a mutable staged path.
- Feature specifications, fake-backed Go tests and SPA tests cover release checks, downloads, restart requests and rollback decisions.
## Upgrading
- Back up your SQLite database and uploads, then replace the binary and restart manually for this first release with browser-update support.
- No database schema change is introduced by the update features.
- `UPDATE_FEED_URL` is optional and defaults to the project's release feed; existing configuration remains usable.
- On Linux with systemd, run `sudo renewcms enable-browser-updates` after the manual upgrade to enable future updates and restarts from Settings.
- Keep the update status files, staged files and backups beside the database in the data directory, with the permissions described in `docs/deployment.md`.
## Known limitations
- The privileged update helper has automated coverage through fakes, but its first real Linux/systemd update and rollback checks are still pending.
- Browser installation and restart require Linux with systemd; Windows, macOS and other init systems remain manual upgrades.
- Updating or restarting briefly takes the site offline, and a reverse proxy may return errors during that interval.
- Automatic rollback restores the previous binary; it does not restore the database, so schema-changing upgrades still require a backup and a recovery plan.
- Update assets and redirects must use HTTPS on the configured feed host.
+29
View File
@@ -0,0 +1,29 @@
This release adds English and French throughout the SPA, with an instant language switch and a preference remembered on this browser.
## New
**English and French interface**
- Choose English or Français from the Language control in the desktop or mobile profile submenu.
- Switch interface language immediately while keeping your current page and unsaved work.
- Keep your selected language after navigation, reload and logout, including on authentication screens.
- See translated forms, validation, notifications, dialogs and accessibility labels, with localized dates, numbers and counts.
## Improvements and fixes
- Keep partial bulk-delete failure notifications available after retrying, including when switching languages.
## Under the hood
- Add translation catalog parity, fallback, persistence and SPA interaction tests.
## Upgrading
- Install the signed update through Settings on a prepared Linux/systemd installation, or replace the binary and restart the service.
- No database migration or new environment variable is required.
- English remains the default until a language is selected; the preference is stored locally in the browser.
- User content, API data and transactional emails retain their existing language.
## Known limitations
- Visual parity checks for this feature were skipped under the accepted slice waiver.
+160
View File
@@ -0,0 +1,160 @@
Feature: An invited person accepts their invitation and gets a verified account
As a person who received an invitation email
I want to open the link, see which address it was sent to, choose a username and password,
and land logged in
So that I get an account with exactly the same access as everyone else, while registration
stays closed to anyone who was not invited
Background:
Given GET /v1/auth/invite and POST /v1/auth/invite/accept are mounted in NewAuthRouter and are
public: no jwt cookie is required and an existing jwt cookie is ignored
And both are rate-limited per client IP with the auth rate limiter (AUTH_RATE_LIMIT_MAX_ATTEMPTS,
AUTH_RATE_LIMIT_WINDOW_SECONDS), counted independently of /login, /password-reset and
POST /v1/user/invite
And an invite is looked up by comparing the raw code against the stored hashed code with the
same hash.Hasher used to create it, and the raw code is never stored
And an invite is usable only when accepted_at is empty and expires_at is in the future
And a code that matches no invite, matches an accepted invite, or is missing or empty answers
404 with body apperr.InviteInvalidErrorMessage "This invite link doesn't work."
And a code that matches an unaccepted invite whose expires_at is in the past answers 410 with
body apperr.InviteExpiredErrorMessage "This invite has expired."
And the POST body has the validate tags code required, username required,min=3,max=20 and
password required,min=8, checked with validator.Validate.Struct before any lookup, and a
failure answers 400 with the validator's text; an unparseable body answers 400 with
apperr.BodyErrorMessage
And error responses are plain text from http.Error, success responses are JSON
And accepting creates a user with the invite's email (already lower case), the chosen username,
the hashed password, is_verified true, an empty verification code, and an empty display name
And the created user is an admin: same access to articles, the users list and Settings, but
cannot invite
And the jwt cookie is set exactly as registration sets it: HttpOnly, path "/", 24 hours, with
claims user_id and token_version, and Secure in production
Scenario: The invited email is read from a valid code
Given a pending invite for "lea.martin@renew.example" whose raw code is "3f0c1a52-8d0e-4c53-9a3a-6b7c0d9e1f42"
When the client sends GET /v1/auth/invite?c=3f0c1a52-8d0e-4c53-9a3a-6b7c0d9e1f42
Then the response status is 200
And the response body is a JSON object with exactly the key email, with value "lea.martin@renew.example"
And the response has Cache-Control "no-store"
And the invite is unchanged
Scenario Outline: A link that does not work is reported without saying why
Given a pending invite for "lea.martin@renew.example", an accepted invite for "sam@renew.example"
and an expired invite for "p.huber@gmail.com", each with its own raw code
When the client sends GET /v1/auth/invite<query>
Then the response status is <status>
And the response body is "<body>"
Examples:
| query | status | body |
| ?c=not-a-known-code | 404 | This invite link doesn't work. |
| ?c=<accepted invite code> | 404 | This invite link doesn't work. |
| ?c= | 404 | This invite link doesn't work. |
| | 404 | This invite link doesn't work. |
| ?c=<expired invite code> | 410 | This invite has expired. |
Scenario: Accepting creates a verified user, logs them in and closes the invite
Given a verified user "marta" and a pending invite for "Lea.Martin@Renew.example" created at
invitation time, with raw code "3f0c1a52-8d0e-4c53-9a3a-6b7c0d9e1f42"
When the client sends POST /v1/auth/invite/accept with body
{"code": "3f0c1a52-8d0e-4c53-9a3a-6b7c0d9e1f42", "username": "lea", "password": "limewash2026"}
Then the response status is 200
And the response body is a JSON object {"message": "Invite accepted! HTTPonly jwt cookie created"}
And a jwt cookie is set, and decoding it gives the new user's id and token_version
And the user repository holds a user "lea" with email "lea.martin@renew.example", is_verified
true, an empty verification_code and a stored password that is a hash, not "limewash2026"
And the invite now has accepted_at set and its status is "accepted"
And no email was sent
Scenario: The new account works like any other account
Given the invite from the previous scenario was accepted and the jwt cookie was kept
When the client sends GET /v1/auth/me and GET /v1/user/ with that cookie
Then both responses are 200
And the GET /v1/user/ list shows user "lea" with status "accepted" and no invite for
"lea.martin@renew.example"
Scenario: An accepted code cannot be used again
Given an invite that was just accepted by "lea"
When the client sends POST /v1/auth/invite/accept with the same code, username "lea2" and
password "limewash2026"
Then the response status is 404
And the response body is "This invite link doesn't work."
And no user "lea2" exists and no jwt cookie is set
When the client sends GET /v1/auth/invite with the same code
Then the response status is 404
Scenario Outline: A code that cannot be used creates nothing
Given <state>
When the client sends POST /v1/auth/invite/accept with a body using <code> and username "lea" and password "limewash2026"
Then the response status is <status>
And the response body is "<body>"
And no user was created, no jwt cookie is set and no invite changed
Examples:
| state | code | status | body |
| no invite has that code | an unknown one | 404 | This invite link doesn't work. |
| an invite that expired an hour ago | its code | 410 | This invite has expired. |
Scenario: A taken username is refused and the invite stays usable
Given a verified user "marta" and a pending invite for "lea.martin@renew.example"
When the client sends POST /v1/auth/invite/accept with username "marta" and password "limewash2026"
Then the response status is 409
And the response body is "That username is taken. Try another."
And no jwt cookie is set and the invite is still pending
When the client resends with username "lea"
Then the response status is 200
Scenario: An address that got an account in the meantime is refused
Given a pending invite for "lea.martin@renew.example" and an unverified user "leam" with email "Lea.Martin@Renew.example"
When the client sends POST /v1/auth/invite/accept with username "lea" and password "limewash2026"
Then the response status is 409
And the response body is exactly apperr.EmailHasAccountErrorMessage
And no user "lea" was created, no jwt cookie is set and the invite is still pending
Scenario Outline: An invalid body is rejected before the code is looked up
Given a pending invite with a known code
When the client sends POST /v1/auth/invite/accept with body <body>
Then the response status is 400
And no user was created and the invite is still pending
Examples:
| body |
| {"code": "<code>", "username": "le", "password": "limewash2026"} |
| {"code": "<code>", "username": "abcdefghijklmnopqrstu", "password": "limewash2026"} |
| {"code": "<code>", "username": "lea", "password": "lime"} |
| {"code": "<code>", "password": "limewash2026"} |
| {"username": "lea", "password": "limewash2026"} |
| not json |
Scenario: An existing jwt cookie is ignored and replaced
Given a valid jwt cookie for verified user "marta" and a pending invite for "lea.martin@renew.example"
When the client sends POST /v1/auth/invite/accept with that cookie and username "lea", password "limewash2026"
Then the response status is 200
And the Set-Cookie jwt carries the new user's id, not marta's
Scenario: A failure while accepting rolls back and leaves the invite pending and no user behind
Given a pending invite and the accept operation of the invite repository set to fail
When the client sends POST /v1/auth/invite/accept with username "lea" and password "limewash2026"
Then the response status is 500
And the user insert and the invite update are rolled back together
And no user "lea" exists, no jwt cookie is set and the invite is still pending
Scenario: The accept endpoints are rate-limited
Given AUTH_RATE_LIMIT_MAX_ATTEMPTS is 2 for a window covering the whole test
When the client at IP "203.0.113.30" sends 2 requests to POST /v1/auth/invite/accept and then a 3rd
Then the 3rd response is 429 with body apperr.TooManyRequestsErrorMessage and a Retry-After header
And GET /v1/auth/registration from the same client is not rejected with 429
Scenario: Registration stays closed for everyone else
Given a verified user and an accepted invite
When the client sends POST /v1/auth/register with username "sam", password "hunter2example12",
email "sam@renew.example"
Then the response status is 403
And the response body is exactly apperr.RegistrationClosedErrorMessage
And GET /v1/auth/registration still reports {"open": false}
Scenario: The invite response never leaks the code or other invite data
Given a pending invite
When the client sends GET /v1/auth/invite with its code
Then the body contains no key named code, hashed_code, invited_by, expires_at, id or accepted_at
+38
View File
@@ -0,0 +1,38 @@
# QA procedure: accept invitation (API)
Package `test` (black-box). Reuse `mockUserRepo`, `stubHasher`, `mockMailRepo`, `mockInviteRepo` (extend it with an accept method and a `failSwitch` entry for it; type names stay unique in the package).
## Setup shared by every case
1. `validator.InitValidator()` once.
2. Use cases: the accept use case (constructor takes only domain interfaces: user repo, invite repo, hasher; final names are the coder's), a get-invite use case for GET, plus `CreateUser`, `GetUser`, `ListUsersAndInvites` for the regression cases.
3. Handler built with `NewHandler(...)` over the use cases, mounted on a fresh `chi.NewRouter()` mirroring `NewAuthRouter`: `GET /invite` and `POST /invite/accept` inside a group with `TrustedProxyRealIP(nil)` + `NewRateLimiter(...)`; `/register`, `/registration` and (with `jwtauth.Verifier`, `Authenticator`, `RequireCurrentToken`) `/me` for regression. `jwtauth.New("HS256", []byte("test-secret"), nil)`. `httptest` only.
4. Seed invites via `mockInviteRepo` with `HashedCode == "hashed:"+rawCode` (stubHasher); times relative to `time.Now()`, 5 s tolerance.
## GET /v1/auth/invite
5. Valid code -> 200; decode `map[string]json.RawMessage`: keys exactly `email`; value the stored lower-case email; `Cache-Control: no-store`; invite unchanged. Raw body contains none of `code`, `hashed_code`, `invited_by`, `expires_at`, `id`, `accepted_at`.
6. Table: unknown code, accepted invite code, `?c=`, no query -> 404 with body exactly `apperr.InviteInvalidErrorMessage`; expired code -> 410 with `apperr.InviteExpiredErrorMessage`.
## POST /v1/auth/invite/accept
7. Happy path: body `{code, username:"lea", password:"limewash2026"}` -> 200, `{"message":…}`. `Set-Cookie` `jwt` HttpOnly, Path "/", decode via `jwtauth` to get `user_id` and `token_version` of the created user. `userRepo`: user "lea", `Email=="lea.martin@renew.example"`, `IsVerified`, empty `VerificationCode`, password `"hashed:limewash2026"`. Invite `AcceptedAt` not nil. `SentEmails` empty.
8. Follow-up with the cookie: `GET /me` -> 200; list use case shows user "lea" and no invite for the address.
9. Repeat POST with the same code -> 404 `InviteInvalid`, no user "lea2", no `Set-Cookie`; GET same code -> 404.
10. Table for 404 (unknown code) and 410 (expired an hour ago): exact bodies, no user, no cookie, invites unchanged.
11. Username "marta" taken -> 409, body `apperr.UsernameTakenErrorMessage` ("That username is taken. Try another."), no cookie, invite still pending; retry with "lea" -> 200.
12. Unverified user with email `Lea.Martin@Renew.example` present -> 409, body `apperr.EmailHasAccountErrorMessage`, no user created, invite pending, no cookie.
13. 400 table (username 2 chars, 21 chars, password 4 chars, no username, no code, `not json`): status 400, user repo and invite unchanged. Code lookup is not reached (assert the invite repo saw no accept call).
14. Cookie of verified user 7 sent with a valid accept -> 200 and the new cookie's `user_id` is the new user's.
15. Invite repo `AcceptWithUser` set to fail (`failSwitch`) -> 500, no user "lea" remains (the failed accept created none, and the use case never calls user repo `Delete`), invite pending, no cookie. The real rollback is covered against SQLite in `test/accept_invitation_atomic_test.go`.
16. Rate limit: limiter of 2 per minute, `RemoteAddr` `203.0.113.30:1234`, three POSTs -> third is 429 with body `apperr.TooManyRequestsErrorMessage` and `Retry-After`; `GET /registration` afterwards is not 429.
## Regression
17. Verified user present: `POST /register` -> 403 body `apperr.RegistrationClosedErrorMessage`, no user created; `GET /registration` -> `{"open":false}` after an invite was accepted. Empty user repo -> `POST /register` still 200 with a `verification` mail.
## Use case level (no HTTP)
18. Accept use case: unknown or empty code -> `errors.Is(err, invite.ErrInviteNotFound)`; expired -> an expired sentinel; taken username -> a username-taken sentinel; email owned -> `invite.ErrEmailHasAccount` (sentinel names are the coder's). Domain sentinels asserted with `errors.Is`.
## Open questions (no design state, not invented)
- GET /v1/auth/invite failing on load with a 500 or a network error: the design has no state for it.
- 429 on POST /v1/auth/invite/accept: the SPA shows the design's server-error alert ("Couldn't create the account").
## Manual verification
- Fresh SQLite file: invite acceptance persists across restart, `accepted_at` stored, unique username constraint holds; send a real invitation and open its link end to end (real SMTP, real embedded SPA).
+105
View File
@@ -0,0 +1,105 @@
Feature: Accept invite screen
As a person who opened the link in the invitation email
I want /invite/accept?c=CODE to show me the invited address and let me choose a username and
password
So that I finish setting up my account and arrive logged in
Background:
Given /invite/accept is a public route (meta.auth "public") rendered as AcceptInvitePage inside
AuthShell, per docs/design/routes.md
And on mount AcceptInvitePage reads the "c" query parameter once: if it is absent or empty no
request is made and the "Invalid or used link (404)" state renders
And otherwise it calls GET /v1/auth/invite?c=CODE and shows "Checking the link" until it resolves
And the Username and Password rules are Register's, including PasswordStrengthHint, with no
confirm field; validation runs on blur and on submit and nothing is sent when it fails
And a submit that passes calls POST /v1/auth/invite/accept with { code: c, username, password }
And a logged-in visitor sees the same screen: the route stays public and nothing redirects
And the board is docs/design/source/RenewCMS Screens Auth.dc.html, group "Accept invite"; the
board frame decides layout and sample data (lea.martin@renew.example, "lea", "limewash2026",
"marta")
Scenario: Checking the link
When the user opens /invite/accept?c=abc123 and GET /v1/auth/invite has not resolved
Then a full-card spinner reads "Checking your invite…"
Scenario: Default
Given GET /v1/auth/invite?c=abc123 resolves 200 with {"email": "lea.martin@renew.example"}
Then the heading is "Accept your invite"
And the description is "Choose a username and password to finish setting up your account."
And the Email field has placeholder "you@example.com", shows "lea.martin@renew.example", is
read-only, with help "From your invitation."
And the Username field has placeholder "e.g. lea", counter "0 / 20" and help "Letters and numbers,
3 to 20 characters. You'll use it to log in."
And the Password field is a password input with show/hide and checklist "At least 8 characters" unmet
And the submit button reads "Accept invite"
And the footer reads "Already have an account?" with a "Log in" link to /login
Scenario: Validation errors
Given the form is shown, Username is "ma" and Password is "lime"
When the user blurs both fields and submits
Then POST /v1/auth/invite/accept is never called
And the Username shows counter "2 / 20" in error and the error "Use 3 to 20 characters."
And the checklist item "At least 8 characters" is in its error state
Scenario: Filled, valid
Given Username is "lea" and Password is "limewash2026" with the password shown
Then the counter reads "3 / 20", the checklist item "At least 8 characters" is met and no error shows
Scenario: Submitting
When the user submits valid values and POST /v1/auth/invite/accept has not resolved
Then the fields and button are disabled
And the submit button reads "Creating account…" and is loading
Scenario: Username taken (409)
When POST /v1/auth/invite/accept resolves 409 with body "That username is taken. Try another."
Then the Username keeps "marta", shows counter "5 / 20", is focused and shows the error
"That username is taken. Try another."
And the Password keeps its value, the form re-enables and the button reads "Accept invite"
Scenario Outline: The link does not work
When <trigger>
Then no form is shown
And a ResultPanel (tone error, icon i-lucide-link-2-off) reads "This invite link doesn't work"
with text "It may be incomplete, or it may already have been used. If you already set up your
account, log in instead." and note "Open the link from your email again, or copy the full
address into your browser."
And its only action is a primary "Go to log in" that navigates to /login
Examples:
| trigger |
| the user opens /invite/accept with no c parameter (no request is made) |
| GET /v1/auth/invite?c=abc123 resolves 404 |
| the submit resolves 404, replacing the form |
| the submit resolves 409 with apperr.EmailHasAccountErrorMessage |
Scenario Outline: Expired link (410)
When <trigger>
Then no form is shown
And a ResultPanel (tone error, icon i-lucide-clock) reads "This invite has expired" with text
"Invites work once, for 3 days. Ask the person who invited you to send a new one."
And its only action is a secondary "Go to log in" that navigates to /login
Examples:
| trigger |
| GET /v1/auth/invite?c=abc123 resolves 410 |
| the submit resolves 410, replacing the form |
Scenario Outline: Server error
When the submit <failure>
Then an error Alert (icon i-lucide-circle-x) reads "Couldn't create the account" with "Something
went wrong on the server. Try again in a moment." above the heading
And the form is still shown with Email, Username "lea" and Password "limewash2026" kept, re-enabled
Examples:
| failure |
| resolves 500 |
| resolves 429 |
| never reaches the server |
Scenario: Success
When POST /v1/auth/invite/accept resolves 200 with the jwt cookie
Then a ResultPanel (tone success, icon i-lucide-circle-check) reads "Your account is ready" with
text "Taking you to your dashboard…"
And a Toast (icon i-lucide-circle-check) reads "Welcome to RenewCMS" with "You're logged in as lea."
And after 800 ms the app navigates to /home with no verification step
+26
View File
@@ -0,0 +1,26 @@
# QA: Accept invite screen
## Automated (Vitest + Vue Test Utils, `task test:web`)
Mock `useApi` for GET `/v1/auth/invite` and POST `/v1/auth/invite/accept` per case; mount AcceptInvitePage inside AuthShell with a test router at `/invite/accept?c=abc123`. Use fake timers for the 800 ms redirect only; never freeze the date.
1. Checking the link: GET unresolved -> "Checking your invite…" spinner.
2. Default: GET 200 `{email:"lea.martin@renew.example"}` -> heading, description, read-only Email with help, Username "0 / 20" and its help, Password checklist unmet, button "Accept invite", footer "Log in" -> /login.
3. Validation errors: Username "ma", Password "lime", blur + submit -> no POST, "Use 3 to 20 characters.", counter "2 / 20" error, checklist error.
4. Filled, valid: "lea" / "limewash2026" shown -> "3 / 20", checklist met.
5. Submitting: POST unresolved -> fields disabled, "Creating account…" loading.
6. Username taken: POST 409 body "That username is taken. Try another." -> value "marta" kept, "5 / 20", focus on Username, error copy, password kept, form re-enabled.
7. Link does not work (table): no `c` (no request at all), GET 404, POST 404, POST 409 with `This address already has an account.` -> ResultPanel link-2-off with the title, text, note and one primary "Go to log in"; click navigates to /login.
8. Expired (table): GET 410, POST 410 -> ResultPanel clock, title, text, one secondary "Go to log in".
9. Server error (table): POST 500, POST 429, rejected fetch -> Alert "Couldn't create the account" + description, form kept.
10. Success: POST 200 -> ResultPanel "Your account is ready", Toast "Welcome to RenewCMS" / "You're logged in as lea."; advance 800 ms -> router path is /home.
11. Logged-in visitor: session store holds a verified user; mounting shows the Default state, no redirect.
## Open questions (no design state, not invented)
- GET /v1/auth/invite failing on load with a 500 or a network error: the design has no state for it.
## Visual (`task visual:check -- accept-invite`, desktop and mobile, light and dark; hard gate 10 %)
Sample data from the board frame: email `lea.martin@renew.example`; username `lea` (taken state: `marta`); password `limewash2026`; validation state username `ma`, password `lime`. States: Checking the link, Default, Validation errors, Filled valid, Submitting, Username taken (409), Invalid or used link (404), Expired link (410), Server error, Success. `skip: clock-sensitive`: none (expiry is driven by the 410 status, not the clock). Layout placement comes from the board frame markup, not from components.md prose.
## Manual checks (not covered by screenshots)
- Keyboard: Tab order Username -> Password -> show/hide -> Accept invite -> Log in; Username is focused after a 409; the ResultPanel title takes focus on 404/410.
- Password show/hide and hover states; the 800 ms hand-off; the Toast disappearing.
- Real e2e: open the emailed link against `task dev`.
@@ -0,0 +1,121 @@
Feature: Typed API client and session store with global 401, unverified-403, 429 and offline handling
As the maintainer of RenewCMS
I want useApi to expose one generic authenticated request method that every future screen call
site builds on, that turns a mid-session 401 into a redirect to /login with the expired reason
and clears the session, turns a 403 from a known-unverified session into a redirect to
/register/pending, surfaces the Retry-After seconds from a 429 so screens can show a countdown,
and marks the app offline on a network failure
So that later screen slices (login, articles, editor, ...) get consistent global session and
connectivity handling instead of each reimplementing 401/403/429/offline handling ad hoc
Background:
Given useApi exports a generic request(path, options) method, used by getMe and by every future
endpoint call, that always sends credentials: 'include' and parses a JSON response body on
success
And a non-2xx response makes request(...) throw an ApiError carrying the numeric status; a 429
response also carries retryAfter, the integer number of seconds parsed from the response's
Retry-After header, or undefined if the header is absent or not a plain integer
And a fetch that rejects instead of resolving (no connectivity, DNS failure, the request never
reaches a server) makes request(...) throw a NetworkError instead of an ApiError, so callers
can tell "the server answered with an error" apart from "the request never got an answer" with
instanceof
And useApi exports a shared reactive isOffline ref, module-scoped so every caller of useApi() and
every component observes the same value: a NetworkError sets it true; it is also true whenever
navigator.onLine is false; a request that completes (2xx or a non-network ApiError) while
navigator.onLine is true sets it back to false
And getMe() calls request('/v1/auth/me', { onUnauthorized: 'passthrough' }): a 401 from this one
call still throws a plain ApiError with status 401, exactly as before, and does not trigger the
redirect below, because this call only ever runs as part of session.check() during router
navigation (features/nuxt_ui_shell_foundation.feature), and the router's own guard already
redirects to /login?redirect=<target>&reason=expired for a "no session" boot result
And every other call to request(...) uses the default onUnauthorized: 'redirect': on a 401,
before the ApiError reaches the caller, useApi calls the session store's clear() action (session
= null, status stays 'ready') and navigates the router to
/login?redirect=<currentPath>&reason=expired, where <currentPath> is
router.currentRoute.value.fullPath at the moment the 401 is received
And on a 403, useApi reads the session store: if it holds a session whose verified is false, this
is the global "unverified account" case from docs/design/routes.md and states.md, so useApi
navigates the router to /register/pending; the ApiError still reaches the caller as a plain 403,
and the session store is left untouched, since it already correctly records verified: false; any
other 403 (no session, or a session whose verified is true) is not the global case: useApi does
nothing extra and the ApiError propagates to the caller unchanged, for the screen to interpret
(wrong-credentials at login, already-verified at cancel-registration, an expired verify or reset
link, and registration-closed are all screen-level, out of scope here)
And the session store gains a clear() action (session = null, status = 'ready', independent of
check()/retry()) used by the global 401 handling above
Scenario: A successful authenticated request returns the parsed body
Given a mocked fetch that resolves 200 with JSON body {"id": 5}
When useApi().request('/v1/article/5') is called
Then the returned value is {"id": 5}
And isOffline is false
Scenario: A 401 received mid-session redirects to login with the expired reason and clears the session
Given the session store holds session {"verified": true} and status "ready"
And the current route is /article/12/edit
And a mocked fetch that resolves 401
When useApi().request('/v1/article/12') is called
Then the call rejects with an ApiError whose status is 401
And the session store's session becomes null and its status stays "ready"
And the router navigates to "/login?redirect=/article/12/edit&reason=expired"
Scenario: The boot call to getMe does not trigger the global 401 redirect
Given the session store holds session null and status "checking"
And a mocked fetch that resolves 401
When useApi().getMe() is called directly, outside of router navigation
Then the call rejects with an ApiError whose status is 401
And the router does not navigate anywhere
Scenario: A 403 while the session is known to be unverified redirects to the pending page
Given the session store holds session {"verified": false} and status "ready"
And a mocked fetch that resolves 403
When useApi().request('/v1/article/') is called
Then the call rejects with an ApiError whose status is 403
And the router navigates to "/register/pending"
And the session store's session is still {"verified": false}
Scenario Outline: A 403 that is not the global unverified case passes through untouched
Given the session store holds session <session> and status "ready"
And a mocked fetch that resolves 403
When useApi().request('/v1/some/endpoint') is called
Then the call rejects with an ApiError whose status is 403
And the router does not navigate anywhere
And the session store is unchanged
Examples:
| session |
| null |
| {"verified": true} |
Scenario: A 429 on a rate-limited endpoint exposes the Retry-After seconds
Given a mocked fetch that resolves 429 with a Retry-After header of "30"
When useApi().request('/v1/auth/login', { method: 'POST' }) is called
Then the call rejects with an ApiError whose status is 429 and whose retryAfter is 30
Scenario: A 429 with no Retry-After header exposes an undefined retryAfter
Given a mocked fetch that resolves 429 with no Retry-After header
When useApi().request('/v1/auth/password-reset', { method: 'POST' }) is called
Then the call rejects with an ApiError whose status is 429 and whose retryAfter is undefined
Scenario: A network failure throws a NetworkError and marks the app offline
Given navigator.onLine is true
And a mocked fetch that rejects with a TypeError, as a real fetch does when the network is
unreachable
When useApi().request('/v1/article/') is called
Then the call rejects with a NetworkError, not an ApiError
And isOffline becomes true
Scenario: A later successful request clears the offline flag
Given isOffline is true from a previous network failure
And navigator.onLine is true
And a mocked fetch that resolves 200 with JSON body {}
When useApi().request('/v1/article/') is called
Then isOffline becomes false
Scenario: The browser's own online/offline events also drive the shared flag
Given isOffline is false
When the browser fires a "offline" event on window
Then isOffline becomes true
When the browser fires a "online" event on window
Then isOffline becomes false
@@ -0,0 +1,76 @@
# QA: Typed API client and session store with global 401, unverified-403, 429 and offline handling
This is a composable/store-only slice with no new screen and no new `/v1` handler, so there is no
Go `httptest` procedure. Verification is entirely Vitest (`task test:web`), unit-testing
`web/src/composables/useApi.ts` and `web/src/stores/session.ts` directly, plus a small check that
the existing router guard suite still passes unmodified.
## Automated (Vitest + Vue Test Utils, `task test:web`)
Mock `global.fetch` per case (`vi.fn()`), install a Pinia instance (`createPinia()` /
`setActivePinia`) before each test, and import the real `router` singleton from `@/router` so
`request(...)`'s navigation calls are observable on `router.currentRoute`. No real backend, no
httptest server, no live SMTP.
1. **Successful request returns parsed JSON and leaves isOffline false** — mock fetch resolving
`{ ok: true, status: 200, json: async () => ({ id: 5 }) }`; call
`useApi().request('/v1/article/5')`; assert it resolves to `{ id: 5 }`, assert `fetch` was called
with `credentials: 'include'`, and assert the exported `isOffline` ref is `false`.
2. **401 mid-session redirects and clears the session** — seed the session store with
`session = { verified: true }`, `status = 'ready'`; navigate the router to `/article/12/edit`
first so `router.currentRoute.value.fullPath` matches; mock fetch resolving status 401; call
`useApi().request('/v1/article/12')`; assert the promise rejects with an `ApiError` whose
`status === 401`; assert `session.session === null` and `session.status === 'ready'`; assert
`router.currentRoute.value.fullPath` is
`/login?redirect=%2Farticle%2F12%2Fedit&reason=expired` (or the equivalent decoded query object).
3. **getMe's own 401 does not trigger the global redirect** — seed
`session = null, status = 'checking'`; mock fetch resolving status 401; record
`router.currentRoute.value.fullPath` before the call; call `useApi().getMe()`; assert it rejects
with `ApiError` status 401; assert the router's current route is unchanged from before the call.
4. **403 with a known-unverified session redirects to /register/pending** — seed
`session = { verified: false }, status = 'ready'`; mock fetch resolving status 403; call
`useApi().request('/v1/article/')`; assert the promise rejects with `ApiError` status 403; assert
`router.currentRoute.value.path === '/register/pending'`; assert
`session.session` is still `{ verified: false }`.
5. **403 with no session, or a verified session, passes through untouched** — two cases,
`session = null` and `session = { verified: true }`, both `status = 'ready'`; mock fetch resolving
status 403; navigate the router to a known path first; call `useApi().request(...)`; assert the
promise rejects with `ApiError` status 403; assert the router's current route did not change;
assert the session store's state object is unchanged (`toEqual` the pre-call snapshot).
6. **429 exposes retryAfter parsed from the Retry-After header** — mock fetch resolving
`{ ok: false, status: 429, headers: new Headers({ 'Retry-After': '30' }) }`; call
`useApi().request('/v1/auth/login', { method: 'POST' })`; assert the rejection is an `ApiError`
with `status === 429` and `retryAfter === 30`.
7. **429 with no Retry-After header exposes retryAfter as undefined** — same as above with no header
set; assert `retryAfter === undefined`.
8. **Network failure throws NetworkError, not ApiError, and sets isOffline true** — set
`Object.defineProperty(navigator, 'onLine', { value: true, configurable: true })`; mock fetch to
`mockRejectedValue(new TypeError('Failed to fetch'))`; call `useApi().request('/v1/article/')`;
assert the rejection is instanceof `NetworkError` and `not instanceof ApiError`; assert `isOffline`
is `true` after the rejection settles.
9. **A later successful request clears isOffline** — starting from `isOffline === true` (reuse the
state from test 8, or set it directly if the module exposes a test seam), keep
`navigator.onLine === true`, mock fetch resolving 200; call `useApi().request('/v1/article/')`;
assert `isOffline` becomes `false` after the call resolves.
10. **window online/offline events drive isOffline directly** — dispatch
`window.dispatchEvent(new Event('offline'))`; assert `isOffline === true`; dispatch
`window.dispatchEvent(new Event('online'))`; assert `isOffline === false`. If `useApi`'s offline
tracking is implemented as a composable that needs to be "activated" (e.g. listeners attached on
first `useApi()` call or app mount), call `useApi()` once before dispatching the events.
11. **Regression: existing getMe/session/router-guard suites stay green** — run
`web/src/router/__tests__/routerGuard.spec.ts` (and any existing `useApi`/`session` spec files)
unmodified alongside the new tests in the same `task test:web` run; assert no existing test's
assertions changed and all still pass. This is not a new scenario to author, just a check that the
new request()/isOffline/clear() additions don't regress boot, session caching or the
public/session/verified/any redirect matrix already covered by
`features/nuxt_ui_shell_foundation.feature`.
## Manual verification
- **Real network offline test** — disable the machine's network adapter (or use browser devtools'
"Offline" throttling) against a `bun dev` instance, trigger a real authenticated call, and confirm
`isOffline` flips and a consuming banner-style UI would show, since Vitest only simulates a
rejected `fetch`, never a real dropped connection.
- **429 countdown UI** — this slice only proves `useApi` surfaces `retryAfter`; the actual countdown
display (`useRetryAfter`, per `docs/design/components.md`) belongs to the login and
password-reset screen slices and is out of scope here.
+259
View File
@@ -0,0 +1,259 @@
Feature: Articles list screen
As a verified RenewCMS owner
I want /article to list every article with its status, let me search and filter it, and let me
publish, unpublish or delete a row without leaving the page
So that I can manage my whole set of articles from one place, with the list always reflecting
what the server actually holds
Background:
Given /article is a verified route (meta.auth "verified") rendered as ArticlesPage inside
DashboardShell, per docs/design/routes.md
And ArticlesPage calls GET /v1/article/ once per navigation to load the full list (all
articles, online and draft, because the request carries the jwt cookie), and every row
action goes over PATCH /v1/article/{id}/publish, PATCH /v1/article/{id}/unpublish or
DELETE /v1/article/{id}; all three endpoints already exist and this slice wires the SPA to
them unchanged, except for one persistence-layer change: ArticleRepository.FindByFilters
(which backs GET /v1/article/) gains a .Preload("Images") call, mirroring the one
ArticleRepository.Get already has, so every article in the list response carries its real
Images array instead of coming back empty; no domain or use-case change is needed, since
article.Article.Images already exists
And the PageHeader shows breadcrumb "Articles" (mobile title "Articles")
And search and the active tab live in the URL query string (?q=, ?status=), so the filtered
view can be linked and survives a reload; the list is always sorted by last updated, newest
first, with no interactive sort control in this slice; search is case-insensitive, ignores
accents, matches anywhere in the title, and is debounced 120 ms; tab counts (All, Online,
Drafts) are always computed from the full list fetched by GET /v1/article/, so they never
change while the user is only searching
And the list is rendered as ArticleTable (desktop, md and up) or ArticleCardList (below md),
both fed by the same articles array, loading flag and per-row busy state, and both routed
through the same row actions
And each row shows its title (a real link to /article/:id/edit), an ArticleStatusBadge (online
or draft), and its updated date (relative within 7 days, e.g. "5 days ago"; an absolute date
beyond that, e.g. "18 Aug 2026", with the full timestamp in a title attribute)
And clicking anywhere on a row except its menu button navigates to /article/:id/edit
And each row's ellipsis button (or Enter while it is focused) opens that row's menu, named
"Actions for {title}", listing Edit (to /article/:id/edit), Publish or Unpublish (whichever
applies to that row's current status), Copy API URL, and, below a separator, "Delete…" in
brick red, always last
And "Copy API URL" writes the absolute URL "{origin}/v1/article/{id}" to the clipboard; on
success it raises a success toast (icon circle-check, id "article-link-copied-{id}"): title
"Link copied" text "The API URL for \"{title}\" is on your clipboard."; if the clipboard
write itself fails, it raises an error toast instead (icon circle-x, id
"article-link-copy-failed-{id}"): title "Couldn't copy the link", with no text line
And row actions are never optimistic: a row only changes once the server responds; while a
publish or unpublish request for a row is in flight, that row alone is disabled and shows a
busy label ("Publishing…" or "Unpublishing…"), and every other row stays interactive
And a successful publish or unpublish (200) updates that row's ArticleStatusBadge and updated
date in place and raises a success toast (icon circle-check, id
"article-published-{id}" or "article-unpublished-{id}" per components.md's action-plus-id
toast convention): title "Article published" text "\"{title}\" is now online." for a
publish, or title "Article unpublished" text "\"{title}\" is now offline." for an unpublish
And a 500 or network failure on a publish or unpublish leaves that row exactly as it was
before the request and raises an error toast (icon circle-x, duration 0 so it stays until
dismissed or retried, id "article-publish-failed-{id}" or "article-unpublish-failed-{id}"):
title "Couldn't publish" or "Couldn't unpublish", text "The server didn't respond. Nothing
changed.", with an action "Retry" that re-sends the same request
And a 404 on any row action (publish, unpublish or delete) closes any open row menu or delete
dialog for that row, removes the row from the list, recomputes the tab counts from the
remaining articles, and raises an info toast (icon info, id "article-not-found-{id}"): title
"That article no longer exists" text "It was deleted somewhere else, so we removed it from
the list."
And "Delete…" opens ConfirmDialog: title "Delete this article?" text "\"{title}\" will be
deleted. Its images stay in your library. This can't be undone." (the second sentence is
present only when the article body holds at least one image),
"Cancel" and "Delete article" (danger); while the DELETE request is in flight the dialog
cannot be dismissed by Cancel, Esc or a backdrop click, both buttons are disabled, the
confirm button reads "Deleting…" with a loading indicator, and aria-busy is set
And a 500 on the delete request keeps the dialog open and instead shows an inline alert inside
the dialog: "Couldn't delete the article, so it's still there. Try again in a moment.",
re-enabling "Cancel" and "Delete article" so the user can retry or back out; the article is
left untouched
And a successful delete (204) closes the dialog, removes the row, moves focus to the next row
(or the page heading if the deleted row was last), recomputes the tab counts, and raises a
success toast (icon circle-check, id "article-deleted-{id}"): title "Article deleted" text
"\"{title}\" is gone."; this is also where a delete initiated from the editor
ends up
And the list, sorted by last updated with the most recently updated article first, holds
these 6 articles by default: id 1 "How we price a bathroom renovation" (online, updated "2
hours ago"), id 2 "Choosing lime plaster for old stone walls" (draft, updated "Yesterday"),
id 3 "Before and after: the Rue Verte kitchen" (online, updated "3 days ago"), id 4 "Winter
checklist for timber windows" (draft, updated "5 days ago"), id 5 "Why we reuse original
floorboards" (online, updated "18 Aug 2026"), id 6 "Our first passive-house retrofit"
(online, updated "2 Jul 2026") — 6 total, 4 online, 2 drafts
Scenario: Default — the list loads sorted by last updated, newest first
Given GET /v1/article/ resolves 200 with the 6-article fixture above
When the user navigates to /article
Then the breadcrumb reads "Articles" (mobile title "Articles")
And the tabs read "All 6" "Online 4" "Drafts 2"
And the rows appear in exactly the fixture's order, each with its title link, its
ArticleStatusBadge and its updated date
And the table (desktop) carries a visually hidden caption "Articles, sorted by last updated,
newest first"
Scenario: Loading — skeleton rows while the first request, or a retry, is in flight
Given GET /v1/article/ has not yet resolved
When the user navigates to /article
Then 5 skeleton rows replace the table or card list, and the list container is aria-busy="true"
When GET /v1/article/ then resolves 200 with the 6-article fixture
Then the skeleton rows are replaced by the Default state's rows
Scenario: Row menu open shows Edit, the status-appropriate action, Copy API URL and Delete…
Given the Default state, with the row for id 4 "Winter checklist for timber windows" (draft,
updated "5 days ago")
When the user activates that row's ellipsis button
Then that row's menu opens, named "Actions for Winter checklist for timber windows", listing
Edit, Publish, Copy API URL, and, below a separator, "Delete…" in brick red
And every other row is unaffected
Scenario: Copy API URL succeeds — the absolute URL is copied and confirmed
Given the Default state, with the row for id 4 "Winter checklist for timber windows"
When the user chooses "Copy API URL" from id 4's row menu
Then "{origin}/v1/article/4" is written to the clipboard
And a success toast appears: icon circle-check, id "article-link-copied-4", title "Link
copied", text "The API URL for \"Winter checklist for timber windows\" is on your
clipboard."
Scenario: Copy API URL fails — the clipboard write itself is rejected
Given the Default state, with the row for id 4 "Winter checklist for timber windows"
When the user chooses "Copy API URL" from id 4's row menu, and the clipboard write fails
Then an error toast appears: icon circle-x, id "article-link-copy-failed-4", title "Couldn't
copy the link", with no text line
Scenario: Empty — zero articles
Given GET /v1/article/ resolves 200 with zero articles
When the user navigates to /article
Then the tabs read "All 0" "Online 0" "Drafts 0"
And an EmptyState (variant no-articles) replaces the list: icon file-text, title "No articles
yet", text "Write your first one. It stays a draft until you publish it.", and a primary
action "New article"
When the user activates "New article"
Then NewArticleModal opens
Scenario: No results — a search matches nothing, but the tab counts still show the full list
Given the Default state has loaded
When the user types "tiles" into the search field
Then, after the 120 ms debounce, an EmptyState (variant no-results) replaces the list: icon
search, title "No articles match \"tiles\"", text "Check the spelling, or search for a
shorter part of the title.", and an action "Clear search"
And the tabs still read "All 6" "Online 4" "Drafts 2"
When the user activates "Clear search"
Then the search field is cleared, the Default state's rows reappear, and focus returns to the
search field
Scenario Outline: An empty tab shows its own EmptyState, while the other tab still counts correctly
Given GET /v1/article/ resolves 200 with <fixture>
When the user navigates to /article and selects the "<tab>" tab
Then the tabs read "<counts>"
And an EmptyState replaces the list: title "<title>" text "<text>" action "<action>"
Examples:
| fixture | tab | counts | title | text | action |
| 4 articles, all online, none drafts | Drafts | All 4, Online 4, Drafts 0 | No drafts | Everything you've written is online. | New article |
| 4 articles, all drafts, none online | Online | All 4, Online 0, Drafts 4 | Nothing is online yet | Publish a draft and it will appear on your website. | Show drafts |
Scenario: Action in progress — publishing a row disables only that row
Given the Default state has loaded
When the user chooses "Publish" from id 4 "Winter checklist for timber windows"'s row menu
Then PATCH /v1/article/4/publish is sent
And that row alone is disabled and shows the busy label "Publishing…", while the other 5 rows
stay interactive
Scenario: Published — a 200 updates the row in place and raises a toast
Given the user chose "Publish" from id 4 "Winter checklist for timber windows"'s row menu, and
the request is in flight
When PATCH /v1/article/4/publish resolves 200 with the article, is_online true, updated "Just
now"
Then id 4's row shows an online ArticleStatusBadge and updated date "Just now", no longer busy
And a success toast appears: icon circle-check, id "article-published-4", title "Article
published", text "\"Winter checklist for timber windows\" is now online."
Scenario Outline: Action failed, publish — a 500 or a network error leaves the row unchanged and offers Retry
Given the user chose "Publish" from id 4 "Winter checklist for timber windows"'s row menu, and
the request is in flight
When PATCH /v1/article/4/publish <failure>
Then id 4's row stays unchanged (draft, updated "5 days ago", no longer busy), because a row
never changes before the server responds
And an error toast appears, staying until dismissed or retried: icon circle-x, id
"article-publish-failed-4", title "Couldn't publish", text "The server didn't respond.
Nothing changed.", action "Retry"
When the user activates "Retry"
Then PATCH /v1/article/4/publish is sent again
Examples:
| failure |
| resolves with a 500 response |
| never reaches the server |
Scenario Outline: Action failed, unpublish — a 500 or a network error leaves the row unchanged and offers Retry
Given the user chose "Unpublish" from id 3 "Before and after: the Rue Verte kitchen"'s row
menu, and the request is in flight
When PATCH /v1/article/3/unpublish <failure>
Then id 3's row stays unchanged (online, updated "3 days ago", no longer busy), because a row
never changes before the server responds
And an error toast appears, staying until dismissed or retried: icon circle-x, id
"article-unpublish-failed-3", title "Couldn't unpublish", text "The server didn't respond.
Nothing changed.", action "Retry"
When the user activates "Retry"
Then PATCH /v1/article/3/unpublish is sent again
Examples:
| failure |
| resolves with a 500 response |
| never reaches the server |
Scenario Outline: Row vanished, draft row — a 404 on publish or delete removes the row and shows an info toast
Given the Default state has loaded
When the user <trigger> for id 2 "Choosing lime plaster for old stone walls"
And the request resolves 404
Then id 2's row is removed from the list (and any open menu or dialog for it closes)
And the tabs read "All 5" "Online 4" "Drafts 1"
And an info toast appears: icon info, id "article-not-found-2", title "That article no longer
exists", text "It was deleted somewhere else, so we removed it from the list."
Examples:
| trigger |
| chooses "Publish" from its row menu |
| confirms "Delete article" in its ConfirmDialog |
Scenario: Row vanished, online row — a 404 on unpublish removes the row and shows an info toast
Given the Default state has loaded
When the user chooses "Unpublish" from id 3 "Before and after: the Rue Verte kitchen"'s row
menu
And the request resolves 404
Then id 3's row is removed from the list (and any open menu closes)
And the tabs read "All 5" "Online 3" "Drafts 2"
And an info toast appears: icon info, id "article-not-found-3", title "That article no longer
exists", text "It was deleted somewhere else, so we removed it from the list."
Scenario: Delete confirm — opens the dialog with the row's title and image count
Given the Default state has loaded, and id 4 "Winter checklist for timber windows" has 3 images
When the user chooses "Delete…" from id 4's row menu
Then ConfirmDialog opens: title "Delete this article?" text "\"Winter checklist for timber
windows\" will be deleted. Its images stay in your library. This can't be undone.", "Cancel" and "Delete
article" (danger)
Scenario: Delete in progress — the dialog cannot be dismissed while the request is in flight
Given ConfirmDialog is open for id 4 "Winter checklist for timber windows"
When the user activates "Delete article"
Then DELETE /v1/article/4 is sent
And both "Cancel" and the confirm button are disabled, the confirm button reads "Deleting…"
with a loading indicator, aria-busy is set, and Esc and a backdrop click do not close it
Scenario: Delete failed — a 500 shows an inline alert inside the dialog and keeps the article
Given ConfirmDialog is open for id 4 "Winter checklist for timber windows", and "Delete
article" has been activated
When DELETE /v1/article/4 resolves 500
Then the dialog stays open, showing the alert "Couldn't delete the article, so it's still
there. Try again in a moment.", with "Cancel" and "Delete article" re-enabled
And id 4's row is untouched in the list behind the dialog
Scenario: Deleted — a 204 closes the dialog, removes the row, and moves focus to the next row
Given ConfirmDialog is open for id 4 "Winter checklist for timber windows", and "Delete
article" has been activated
When DELETE /v1/article/4 resolves 204
Then the dialog closes, id 4's row is removed from the list, and focus moves to the next row
And the tabs read "All 5" "Online 4" "Drafts 1"
And a success toast appears: icon circle-check, id "article-deleted-4", title "Article
deleted", text "\"Winter checklist for timber windows\" is gone."
+176
View File
@@ -0,0 +1,176 @@
# QA: Articles list screen
## Implementation note for coder (informational, not a QA assertion)
`internal/infrastructure/persistence/repositories/articleRepository.go`'s `FindByFilters` gains
`.Preload("Images")`, mirroring `Get`, so `GET /v1/article/` carries real `Images` arrays for the
delete dialog's count. This is a persistence-layer change asserted by the existing
`var _ domain.Repository = &ArticleRepository{}`; it needs no domain or use-case change, since
`article.Article.Images` already exists.
Toast ids follow components.md's action-plus-id convention: "article-published-{id}",
"article-unpublished-{id}", "article-publish-failed-{id}", "article-unpublish-failed-{id}",
"article-not-found-{id}", "article-deleted-{id}", "article-link-copied-{id}",
"article-link-copy-failed-{id}".
## HTTP-level (Go, `test/`, `task test`)
Build `article.NewHandler(...)` over the real use cases wired to a fake `article.Repository` (in
the style of `test/article_test.go`'s `mockArticleRepo`), mounted on a fresh `chi.NewRouter()`
mirroring `NewArticleRouter` in `api/router.go` (the outer group, no auth, for `GET /`). Call
`validator.InitValidator()` first.
1. **GET /v1/article/ returns each article's images array populated** — seed the fake repository
with an article whose `Images` slice holds two `image.Image` entries (ids 10 and 11), send
`GET /v1/article/` with `httptest`, decode the JSON array, and assert the matching entry's
`images` field is a 2-element array containing those ids (not `null` and not empty), proving
the handler's response reflects `FindByFilters`'s `Images` data. Because the fake repository's
`FindByFilters` is written by this test rather than GORM, it can't exercise the real
`.Preload("Images")` SQL by itself — this test only proves the handler passes the repository's
`Images` data through to JSON unchanged. The `.Preload` call itself against a real SQLite file is
covered under Manual verification below.
## Automated (Vitest + Vue Test Utils, `task test:web`)
Mock `useApi`'s calls for `GET /v1/article/`, `PATCH /v1/article/{id}/publish`,
`PATCH /v1/article/{id}/unpublish`, `DELETE /v1/article/{id}`, and the clipboard write (e.g.
`navigator.clipboard.writeText`), per case; no real backend, no httptest server. Mount
ArticlesPage inside DashboardShell with a resolved verified session and a test router at
/article. Sample data throughout is the Background's 6-article fixture (ids 1-6, titles and dates
as listed), unless a scenario's Examples row substitutes a smaller fixture.
1. **Default** — mock `GET /v1/article/` resolving 200 with the 6-article fixture; assert
breadcrumb "Articles"; assert tabs "All 6" "Online 4" "Drafts 2"; assert the rows render in
fixture order with title link, ArticleStatusBadge and updated date; assert the table's visually
hidden caption reads "Articles, sorted by last updated, newest first".
2. **Loading** — mock `GET /v1/article/` with an unresolved promise; assert 5 skeleton rows and
`aria-busy="true"` on the list container; resolve 200 with the fixture; assert the Default
state's rows replace the skeletons.
3. **Row menu open** — from Default, click id 4's ellipsis button; assert the menu opens named
"Actions for Winter checklist for timber windows" with items Edit, Publish, Copy API URL, and a
separator then "Delete…"; assert no other row is affected.
4. **Copy API URL succeeds** — from Default, mock the clipboard write to resolve, choose "Copy API
URL" from id 4's menu; assert the clipboard write was called with
`"{origin}/v1/article/4"` (using the test's `window.location.origin`); assert a toast was
raised with id "article-link-copied-4", icon circle-check, title "Link copied", text "The API
URL for \"Winter checklist for timber windows\" is on your clipboard."
5. **Copy API URL fails** — from Default, mock the clipboard write to reject, choose "Copy API
URL" from id 4's menu; assert a toast was raised with id "article-link-copy-failed-4", icon
circle-x, title "Couldn't copy the link", and no description text.
6. **Empty** — mock `GET /v1/article/` resolving 200 with `[]`; assert tabs "All 0" "Online 0"
"Drafts 0"; assert the no-articles EmptyState (icon file-text, title "No articles yet", text,
action "New article"); click it; assert NewArticleModal opens.
7. **No results** — from Default, type "tiles" into the search field; advance past the 120 ms
debounce (fake timers); assert the no-results EmptyState (icon search, title "No articles match
\"tiles\"", text, action "Clear search"); assert tabs still read "All 6" "Online 4" "Drafts 2";
click "Clear search"; assert the Default rows reappear and the search field has focus.
8. **Empty tab, Examples-driven** — (a) mock `GET /v1/article/` with 4 online-only articles, select
the Drafts tab, assert tabs "All 4" "Online 4" "Drafts 0" and the no-drafts EmptyState (icon
pencil-line, title "No drafts", text "Everything you've written is online.", action "New
article"); (b) mock 4 draft-only articles, select the Online tab, assert tabs "All 4" "Online 0"
"Drafts 4" and the EmptyState titled "Nothing is online yet", text "Publish a draft and it will
appear on your website.", action "Show drafts" (icon per the board, confirmed in the visual
check below).
9. **Action in progress** — from Default, choose "Publish" from id 4's menu; assert
`PATCH /v1/article/4/publish` is called; assert id 4's row is disabled with busy label
"Publishing…" and the other 5 rows stay enabled.
10. **Published** — continuing from 9, resolve the PATCH 200 with `is_online: true`, updated "Just
now"; assert id 4's row shows the online badge and "Just now", no longer busy; assert a toast
was raised with id "article-published-4", icon circle-check, title "Article published", text
"\"Winter checklist for timber windows\" is now online."
11. **Action failed, publish, Examples-driven** — for each of a 500 response and a network
rejection: choose "Publish" from id 4's menu, resolve/reject the mocked PATCH accordingly;
assert id 4's row stays exactly unchanged (draft, "5 days ago", not busy) throughout — the row
is never touched before the (failed) response, so there is nothing to revert; assert a toast
with id "article-publish-failed-4", icon circle-x, title "Couldn't publish", text "The server
didn't respond. Nothing changed.", action "Retry"; click "Retry"; assert the same PATCH is
called again.
12. **Action failed, unpublish, Examples-driven** — for each of a 500 response and a network
rejection: choose "Unpublish" from id 3's menu (an online row), resolve/reject the mocked
PATCH accordingly; assert id 3's row stays exactly unchanged (online, "3 days ago", not busy);
assert a toast with id "article-unpublish-failed-3", icon circle-x, title "Couldn't
unpublish", text "The server didn't respond. Nothing changed.", action "Retry"; click "Retry";
assert the same PATCH is called again.
13. **Row vanished, draft row, Examples-driven** — for each of (publish 404), (delete-confirm
404) on id 2 (a draft row): trigger the action, resolve the mocked call 404; assert id 2's row
is removed; assert tabs read "All 5" "Online 4" "Drafts 1"; assert a toast with id
"article-not-found-2", icon info, title "That article no longer exists", text "It was deleted
somewhere else, so we removed it from the list."
14. **Row vanished, online row** — choose "Unpublish" from id 3's menu, resolve the mocked PATCH
404; assert id 3's row is removed; assert tabs read "All 5" "Online 3" "Drafts 2"; assert a
toast with id "article-not-found-3", icon info, title "That article no longer exists", text
"It was deleted somewhere else, so we removed it from the list."
15. **Delete confirm** — from Default (with id 4 carrying 3 images in the mocked
`GET /v1/article/` response), choose "Delete…" from id 4's menu; assert ConfirmDialog opens
with title "Delete this article?", text "\"Winter checklist for timber windows\" and its 3
images will be deleted. This can't be undone.", "Cancel" and "Delete article".
16. **Delete in progress** — from the open dialog, click "Delete article"; assert
`DELETE /v1/article/4` is called; assert both buttons are disabled, the confirm button reads
"Deleting…", `aria-busy` is set, and Esc / backdrop click do not close it.
17. **Delete failed** — continuing from 16, resolve the DELETE 500; assert the dialog stays open
with the inline alert "Couldn't delete the article, so it's still there. Try again in a
moment.", both buttons re-enabled; assert id 4's row is unchanged in the list behind the
dialog.
18. **Deleted** — continuing from 16 (a fresh attempt), resolve the DELETE 204; assert the dialog
closes, id 4's row is removed, focus moves to the next row; assert tabs read "All 5" "Online
4" "Drafts 1"; assert a toast with id "article-deleted-4", icon circle-check, title "Article
deleted", text "\"Winter checklist for timber windows\" is gone."
## Visual (manual verification — desktop and mobile, light and dark)
Reference: `docs/design/screens/articles.md` and `docs/design/source/RenewCMS Screens
Back-office.dc.html`, group "Articles". Run `task visual:check -- articles` for each state below
and compare against the board frame; add each state's mock setup to `web/visual/states.ts` first,
reusing the 6-article fixture (ids/titles/dates above) as sample data. This screen shows relative
dates ("2 hours ago", "5 days ago"), so fix `now` to the value the board's own script assumes for
those relative strings to render identically (derive it from "2 hours ago" against "12 Mar 2026"
and the absolute dates shown, e.g. "18 Aug 2026", per the board's `base` fixture in the source
file).
- [ ] Default: tabs "All 6/Online 4/Drafts 2", 6 rows in fixture order, title/status/updated
columns (confirm against the board frame directly whether a Created column is also shown —
components.md's prose and the rendered board table disagree on this).
- [ ] Row menu open: id 4's menu open with Edit/Publish/Copy API URL/Delete…, matching the board's
dropdown placement and the brick-red Delete… treatment.
- [ ] Loading: 5 skeleton rows shaped like the real layout.
- [ ] Empty: EmptyState icon file-text, title, text, single "New article" action.
- [ ] No results: EmptyState icon search, title with the quoted search term, text, "Clear search".
- [ ] No drafts / Nothing online: both empty-tab EmptyStates, including the "Nothing is online
yet" state's icon (confirm it directly against the board frame, since it isn't given in the
prose extraction read for this slice).
- [ ] Action in progress: id 4's row at 50% opacity with a spinner in the status cell and
"aria-busy".
- [ ] Published / Action failed toasts: colors, icons and the "Retry" action match the board.
- [ ] Copy API URL: no board state depicts its toasts; verify their copy and icons directly in the
app against this spec rather than a board frame.
- [ ] Row vanished: the info toast and the row's removal match the board.
- [ ] Delete confirm / in progress / failed: the dialog's three states match the board exactly,
including the inline alert's placement in the failed state.
- [ ] Deleted: toast copy matches, and focus visibly lands on the next row.
- [ ] Keyboard/focus: roving tabindex across the tab list (Tab enters on the selected tab, ←/→
move and activate); each row's title link is reachable and Enter opens the editor; each
row's menu opens with Enter/Space/↓, arrow keys and type-ahead navigate it, Home/End jump to
the ends, Esc closes it and returns focus to the ellipsis button; ConfirmDialog traps focus,
starts on Cancel, and Enter does not confirm by default; on a successful delete, focus lands
on the next row (or the page heading if none).
- [ ] Motion: skeleton pulse and modal open/close follow the standard timings and stop under
reduced motion.
## Manual verification
- **Real GET/PATCH/DELETE round trips against a running server** — Vitest only mocks `useApi`;
confirm the real 200/404/500 responses, and the real `updated_at`-based ordering, against
`task dev` with a live SQLite file, since these automated tests never exercise the actual Go
handlers or use cases.
- **Real .Preload("Images") behavior against a live SQLite file** — confirm `GET /v1/article/`
returns accurate, non-empty `images` arrays for articles with real uploaded images, and `[]` for
articles with none, against a running server, since the HTTP-level Go test above only proves the
handler forwards whatever the (fake) repository returns, not that the real GORM query populates
it correctly.
- **Real image-count accuracy in the delete dialog** — confirm the delete dialog's count matches
an article's actual attached images end to end (upload images, then delete), since Vitest only
ever supplies a mocked count.
- **Toast placement and stacking on a live app, including the three-toast cap** — confirm against
a running app, since Vitest only asserts `useToast().add` was called with the right arguments.
- **Real clipboard write on a live app** — confirm `navigator.clipboard.writeText` actually places
the URL on the system clipboard in a real browser, since Vitest only mocks the clipboard API.
@@ -0,0 +1,94 @@
Feature: AuthShell and log-in screen conform to the design spec
As the maintainer of RenewCMS
I want AuthShell and LoginView built from the exact primitives docs/design/components.md
specifies — AppLogo, UPageCard's own title/description styling, the muted page background,
UForm with "Forgot password?" in the Password field's #hint slot, and the neutral-by-default,
red-on-error input border
So that the log-in screen (and every other AuthShell-based screen) matches the visual spec of
record instead of ad hoc markup that happens to look similar
Background:
Given AuthShell is the layout for every public route, per docs/design/routes.md
And AuthShell composes a UPageCard variant="outline" as the centered card, with AppLogo
rendered as the card's first element — left-aligned above the title/description block,
sharing the card's own 24px gap — not as a separate element centered outside/above the
card, per docs/design/components.md's AuthShell section and
docs/design/source/AuthCard.dc.html
And AppLogo is a reusable component (props include size) rendering the brand mark from
docs/design/source/brand/favicon.svg as inline SVG, not an <img>
And UPageCard's title renders through its own title slot as an h1 (tabindex="-1", so route
changes can move focus to it, per AuthShell's a11y spec), and its description renders
through UPageCard's description prop — neither is freeform markup in the default slot
And from the sm breakpoint up, the centered <main> sits on the muted page background
(--ui-bg-muted), the same canvas the rest of the app uses; below sm it sits on --ui-bg
instead, per docs/design/components.md's AuthShell "Responsive" line
And LoginView's form is a UForm wrapping the Username and Password UFormFields and the
submit button
And the Password UFormField's "Forgot password?" link renders through the field's #hint
slot, in the position the Auth board draws it — right-aligned on the label row — per
docs/design/source/RenewCMS Screens Auth.dc.html, group "Log in"
And every UInput on the page uses the neutral control-edge border (--ui-border-accented) by
default, and turns to the error edge (--ui-error) only when its field has an error, per
docs/design/components.md's Input section (":highlight bound to the field error") and
foundations.md's Borders and elevation
Scenario: AppLogo renders the brand mark as inline SVG, and theme-switches
Given a public screen renders inside AuthShell
When AuthShell mounts
Then an AppLogo renders as UPageCard's first element, inside the card, left-aligned, sharing
the card's 24px gap with the title/description block below it — not centered above the card
And the logo is inline SVG sourced from docs/design/source/brand/favicon.svg, at 32px, not as
an <img> tag
And the logo carries alt="RenewCMS" (role="img" aria-label="RenewCMS" on the SVG)
And the logo is not wrapped in a link, since there is nothing public to go back to
And the black square has no edge stroke in light mode or in dark mode, per
docs/design/source/AuthCard.dc.html's renderVals(), which computes the logo's edge as the
literal, non-theme-branched value "transparent"
Scenario: UPageCard's title is the page h1, and its description uses UPageCard's own styling
Given AuthShell renders with title "Log in" and description
"Welcome back. Log in to manage your articles."
When AuthShell mounts
Then the card is a UPageCard with variant="outline"
And UPageCard's title slot renders an h1 with tabindex="-1" containing "Log in"
And UPageCard's description prop is "Welcome back. Log in to manage your articles."
And neither the title nor the description is rendered as separate freeform markup inside
UPageCard's default slot
Scenario: The page sits on the muted background from sm up, and on the default background below sm
Given AuthShell renders any public screen at a viewport of sm or wider
When AuthShell mounts
Then the centered <main> uses the muted background token (--ui-bg-muted)
And the card keeps its border, is capped at 400px, and its top sits 12vh from the top
Scenario: Below sm, AuthShell drops the muted background, the card border and the card padding
Given AuthShell renders any public screen at a viewport below sm
When AuthShell mounts
Then the centered <main> uses the default background token (--ui-bg), not the muted one
And the card has no border and fills the screen with 20px padding
And the fields and buttons on the page render at the xl size
Scenario: The login form is a UForm
Given the user is on /login
When the login form renders
Then the form is a UForm, not a plain HTML <form>, wrapping the Username UFormField, the
Password UFormField and the submit button
Scenario: "Forgot password?" renders in the Password field's hint slot
Given the user is on /login
When the login form renders
Then the Password UFormField's "Forgot password?" link is rendered through the field's
#hint slot
And the Password field's label reads only "Password", with no link inside it
Scenario: Inputs are neutral by default and turn to the error edge only when their field has an error
Given the user is on /login with no validation errors yet
When the Username and Password UInput fields render
Then both use the neutral control-edge border (--ui-border-accented), with :highlight false
When the user submits with Username "ma" and Password empty (the Validation errors state,
per docs/design/screens/log-in.md)
Then the Username UInput's edge turns to the error color (--ui-error), with :highlight true,
alongside the message "Use at least 3 characters."
And the Password UInput's edge turns to the error color (--ui-error), with :highlight true,
alongside the message "Enter your password."
@@ -0,0 +1,88 @@
# QA: AuthShell and log-in screen conform to the design spec
## Automated (Vitest + Vue Test Utils, `task test:web`)
No `/v1` calls are relevant to these assertions; mount AuthShell and LoginView directly (LoginView
already needs `useApi`/`GET /v1/auth/registration` mocked per features/login_screen.qa.md's setup,
reused here only as scaffolding, not as the thing under test).
1. **AppLogo renders inline SVG with no edge in either mode** — mount AuthShell with title
"Log in"; assert an inline `<svg>` (not `<img>`) renders as UPageCard's first child element,
left-aligned (not centered) above the title/description block, sharing the card's 24px gap, at
32px, with `role="img" aria-label="RenewCMS"`, and is not inside an `<a>`; assert its outer
square has no stroke in light mode; switch to dark mode (toggle the `.dark` class the way
`nuxt_ui_shell_foundation`'s color-mode tests do) and assert the outer square still has no
stroke, per `docs/design/source/AuthCard.dc.html`'s literal, non-theme-branched
`edge: 'transparent'`.
2. **UPageCard title is an h1 with tabindex="-1"** — mount AuthShell with title "Log in" and
description "Welcome back. Log in to manage your articles."; assert
`wrapper.find('h1').attributes('tabindex')` is `"-1"` and its text is "Log in"; assert the
description text "Welcome back. Log in to manage your articles." renders via UPageCard's
`description` prop (not as a sibling `<p>` hand-authored in AuthShell's template). This
replaces the older assertion in `AuthShell.spec.ts` that only checked for any `<h1>`; keep that
assertion passing (h1 text still equals the title) while adding the tabindex check.
3. **Muted background at sm and up** — mount AuthShell at a `>= 640px` viewport (mock
`useBreakpoints`/matchMedia the way other shell tests do); assert `<main>`'s class list
includes the muted background utility (e.g. `bg-muted`); assert the card renders with a
border and is capped at 400px width, offset 12vh from the top.
4. **Default background, borderless card, 20px padding, xl controls below sm** — mount AuthShell
at a `< 640px` viewport; assert `<main>`'s class list includes the default background utility
(`bg-default`) and not the muted one; assert the card has no border class; assert the card's
padding is 20px; assert the Username/Password inputs and submit button render at `size="xl"`.
5. **Login form is a UForm** — mount LoginView at /login; assert the form wrapping the fields is
a UForm component instance, not a bare `<form>` element with only `@submit.prevent` wired by
hand.
6. **Forgot password in the #hint slot** — mount LoginView at /login; assert the Password
UFormField is passed content (or renders content) in its `hint` slot containing a
"Forgot password?" link to /register/reset/request; assert the field's rendered label text is
exactly "Password" with no link inside it.
7. **Inputs default to neutral, then highlight red on error** — mount LoginView at /login; assert
the Username and Password `UInput` components render with `highlight` falsy (or absent) and
the theme's default ring class (`ring-(--ui-border-accented)`); then trigger the Validation
errors state (type "ma" into Username, submit with Password empty); assert both `UInput`s now
receive `:highlight="true"` (or the field's error is otherwise truthy) so the edge renders in
`--ui-error`, alongside "Use at least 3 characters." and "Enter your password." respectively.
### Implementation finding for coder
`web/src/views/LoginView.vue`'s Username and Password `UInput`s currently receive no `:highlight`
prop at all — `UFormField` gets `:error="usernameError"` / `:error="passwordError"`, but that value
is never forwarded to the inner `UInput`. Today the edge never turns red in the Validation errors
state; this isn't a stale/inverted binding, it's a missing one. Wiring `:highlight="!!usernameError"`
/ `:highlight="!!passwordError"` (or equivalent) onto each `UInput` is the fix scenario 7 above
pins down.
## Visual (manual verification — desktop and mobile, light and dark)
Reference: `docs/design/source/RenewCMS Screens Auth.dc.html`, group "Log in", plus
`docs/design/source/RenewCMS Components Product.dc.html`'s AuthShell drawing and
`docs/design/source/RenewCMS Components Primitives.dc.html`'s Input drawing.
- [ ] AppLogo renders inside UPageCard as its first element, left-aligned above the title (not
centered above the card), sharing the card's 24px gap; the mark matches the favicon.svg
drawing exactly (white R on a black square), desktop and mobile; no edge stroke is visible
around the square in either light or dark mode.
- [ ] UPageCard title ("Log in") renders at the card-title size/weight from the AuthShell drawing
and receives focus (visible focus ring) on route change; description text matches
"Welcome back. Log in to manage your articles." styling, desktop and mobile, light and dark.
- [ ] At sm and up: 400px card with its border, 12vh top offset, on the muted page canvas, light
and dark.
- [ ] Below sm: card fills the screen borderless with 20px padding on the default (not muted)
background; fields and the submit button render at the touch (xl, 44px) size, light and
dark.
- [ ] The Password field's "Forgot password?" link sits right-aligned on the label row (the hint
position), matching the Auth board, desktop and mobile, light and dark.
- [ ] Username and Password fields show the neutral control-edge border by default; in the
Validation errors state (short username, empty password) both fields' edges turn to the
error color alongside their messages, in both light and dark.
- [ ] Keyboard/focus: Tab order remains Username → Password → show/hide toggle → "Forgot
password?" → submit; UPageCard's h1 is reachable/focusable via tabindex="-1" on route
change, matching AuthShell's existing a11y spec.
## Manual verification
- **AppLogo reused in DashboardShell** — out of scope for this slice (AuthShell/login only).
`DashboardShell.vue`'s sidebar header is currently a plain `<span class="font-semibold">
RenewCMS</span>` (not AppLogo), and its footer is a bare `<span>Log out</span>` instead of the
UserMenu component components.md specifies. Both need their own "Built from" conformance pass in
a later DashboardShell slice; AppLogo (built here with a `size` prop) will be ready to drop in
at that point without changes.
+104
View File
@@ -0,0 +1,104 @@
Feature: DashboardShell wordmark, sidebar collapse and the UserMenu
As the maintainer of RenewCMS
I want DashboardShell built from the exact primitives docs/design/components.md specifies —
AppLogo plus the "RenewCMS" wordmark in the sidebar header, and a UserMenu (UDropdownMenu on a
ghost UButton with a UAvatar) in the sidebar footer, with a collapsed rail that hides text but
never drops an accessible name
So that every verified route's sidebar matches the visual spec of record and stays usable when
collapsed, instead of the current plain-text "RenewCMS" header and "Log out" footer
Background:
Given DashboardShell is the layout for every verified route, per docs/design/routes.md
And DashboardShell composes a UDashboardGroup storage="local" with a UDashboardSidebar
collapsible :resizable="false" :default-size="14" :collapsed-size="3.5", per
docs/design/components.md's DashboardShell section
And the sidebar's #header slot renders AppLogo (the same reusable inline-SVG brand mark
AuthShell uses) followed by the "RenewCMS" wordmark text, not the plain
<span class="font-semibold">RenewCMS</span> the shell renders today
And the sidebar's #default slot is a UNavigationMenu orientation="vertical" :collapsed bound
to the sidebar's own collapsed state, with items Home, Articles, Users, Integration and Settings, in that order
And the sidebar's #footer slot renders a UserMenu component, not the plain
<span>Log out</span> text the shell renders today
And UserMenu is the account menu specified in features/profile_page.feature, anchored to a
ghost UButton block containing a UAvatar and the session's name (the display name when not
empty, else the username)
And the UAvatar's initials follow features/profile_page.feature (the first letters of the
first two words of a display name, the first two characters of a single word or of a
username, upper-cased; for example "marta" gives "MA"), and the avatar is aria-hidden
because the name is shown next to it
And UserMenu's groups, top to bottom, are: a header (the name and the email); Profile; a
checkbox group of System, Light and Dark bound to useColorMode().preference, with the
current preference's item checked; then Log out, in its own trailing group
And Log out calls POST /v1/auth/logout inside a try/finally with a loading flag (no catch),
then calls session.clear() and navigates to /login — the exact same shape PendingView.vue
and VerifyView.vue already use for their own log-out actions, not a new resilience pattern
And per docs/design/components.md's DashboardShell a11y note, in the collapsed rail the
UNavigationMenu's items show tooltips and keep their aria-label; the wordmark and UserMenu
apply that same spirit when the sidebar collapses to :collapsed-size="3.5"
Scenario: The sidebar header renders AppLogo and the "RenewCMS" wordmark
Given the user is on any verified route with the sidebar expanded
When DashboardShell mounts
Then the sidebar's #header slot renders an AppLogo before the text "RenewCMS"
And the wordmark text "RenewCMS" is visible next to the logo
And neither the logo nor the wordmark is a link, since there is nothing to navigate to from
the shell itself
Scenario: The sidebar collapse trigger toggles the rail and exposes aria-expanded
Given the user is on any verified route with the sidebar expanded
When the user activates UDashboardSidebarCollapse in the navbar's leading slot
Then the sidebar transitions to its :collapsed-size="3.5" icon-only rail
And UDashboardSidebarCollapse carries aria-expanded, reflecting the sidebar's new collapsed
state
When the user activates UDashboardSidebarCollapse again
Then the sidebar returns to its :default-size="14" expanded width
And aria-expanded reflects the expanded state
Scenario: UserMenu lists the header, Profile, color-mode checkboxes, then Log out
Given the session's username is "marta" and its email is "marta@renew.example"
When the user activates the UserMenu trigger in the sidebar footer
Then the menu opens with a UAvatar showing initials "MA" and the trigger's own name text
"marta"
And the first group is the header showing "marta" and "marta@renew.example"
And the next item is "Profile"
And the following group is a checkbox group with items System, Light and Dark, and exactly the
item matching the current useColorMode().preference is checked
And the final group contains only "Log out", separated from the color-mode group
Scenario Outline: Selecting a color-mode item updates the preference and its checked state
Given the user has opened the UserMenu dropdown
And the current useColorMode().preference is "<from>"
When the user activates the "<to>" checkbox item
Then useColorMode().preference is set to "<to>"
And the "<to>" item is checked and the "<from>" item is no longer checked
Examples:
| from | to |
| system | light |
| light | dark |
| dark | system |
Scenario: A successful logout clears the session and navigates to /login
Given the user has opened the UserMenu dropdown
When the user activates "Log out"
Then a POST request is made to /v1/auth/logout
And once it resolves, the local session is cleared
And the user is navigated to /login
Scenario: Collapsed sidebar hides the wordmark and username text but keeps an icon-only rail
Given the user is on any verified route
When the sidebar is collapsed to its :collapsed-size="3.5" icon-only rail
Then the AppLogo icon in the sidebar header remains visible, but the "RenewCMS" wordmark text
is hidden, not merely visually truncated
And the header keeps an accessible name for the brand mark (an aria-label or sr-only text
reading "RenewCMS" on the logo or its wrapper), so collapsing the rail is not a pure a11y
regression
And the UserMenu trigger in the sidebar footer still shows the UAvatar, but the name text
next to it is hidden
And the UserMenu trigger keeps an accessible name that includes the name (an aria-label
such as "marta — account menu", or a tooltip plus aria-label), matching the same
tooltip/aria-label spirit the collapsed rail's UNavigationMenu items already use per
docs/design/components.md's DashboardShell a11y note
And activating the collapsed UserMenu trigger still opens the same menu, with the same
header, Profile, color-mode checkbox group and Log out item as the expanded state
+65
View File
@@ -0,0 +1,65 @@
# QA: DashboardShell branding (wordmark, sidebar collapse, UserMenu)
## Automated (Vitest + Vue Test Utils, `task test:web`)
Mount DashboardShell (or a verified route rendered inside it) with a resolved session (username
"marta") and a test router. Mock `useApi`'s `/v1/auth/logout` call per case; no real backend, no
httptest server. Stub `useColorMode()` so its `preference` can be asserted and set.
1. **Header renders AppLogo and the wordmark** — mount DashboardShell expanded; assert the
sidebar's #header slot renders an AppLogo followed by the text "RenewCMS"; assert neither is a
link.
2. **Sidebar collapse trigger toggles the rail and aria-expanded** — mount DashboardShell
expanded; activate UDashboardSidebarCollapse; assert the sidebar reaches its
:collapsed-size="3.5" state and the trigger's aria-expanded reflects it; activate it again; assert
the sidebar returns to :default-size="14" and aria-expanded flips back.
3. **UserMenu dropdown groups and order** — mount with username "marta" and
`useColorMode().preference` set to each of "system", "light", "dark" in turn; open the UserMenu
dropdown; assert the avatar shows initials "MA"; assert the trigger shows "marta"; assert the
first group is the account label "marta"; assert the second group has System, Light and Dark
checkbox items with exactly the current preference's item checked; assert the third, separate
group contains only "Log out".
4. **Selecting a color-mode item updates the preference** — Examples-driven: (system → light),
(light → dark), (dark → system). Open the dropdown, activate the target item, assert
`useColorMode().preference` is set to the target and its checkbox item is checked while the
previous one is not.
5. **Successful logout clears the session and navigates** — mock `POST /v1/auth/logout` resolving
200; open the UserMenu dropdown; activate "Log out"; assert the mock was called; assert the
session store's `clear()` is called once it resolves; assert the router navigates to /login.
6. **Collapsed sidebar hides wordmark/username text but keeps an accessible name** — mount
DashboardShell and collapse the sidebar to :collapsed-size="3.5"; assert the AppLogo icon is still
present but the "RenewCMS" text node is not rendered (or is visually hidden, e.g. sr-only) while
an accessible name for the logo (aria-label or sr-only text reading "RenewCMS") is still present
in the accessibility tree; assert the UserMenu trigger still renders the UAvatar but not the
visible "marta" text node, while the trigger's accessible name still includes "marta" (via
aria-label or a tooltip plus aria-label); activate the collapsed trigger and assert the same
dropdown (account label, color-mode group, Log out) opens as in the expanded state.
## Visual (manual verification — desktop and mobile, light and dark)
Reference: `docs/design/components.md`'s DashboardShell section and
`docs/design/source/RenewCMS Screens Back-office.dc.html`. Run `task visual:check -- <a verified
screen, e.g. home>` for each state and compare the sidebar header/footer against the board frame.
- [ ] Expanded sidebar: AppLogo plus "RenewCMS" wordmark in the header; UserMenu in the footer
shows the avatar and username, matching the board exactly at desktop and mobile.
- [ ] UserMenu dropdown: opens above the trigger (`side: 'top'`), left-aligned (`align: 'start'`),
with the account label, the System/Light/Dark checkbox group and Log out visually separated
as in the board.
- [ ] Color mode selection: choosing Light/Dark/System visibly re-themes the app and moves the
checkmark to the selected item.
- [ ] Collapsed sidebar (icon-only rail): the AppLogo icon and the avatar remain visible; the
"RenewCMS" wordmark and the username text are hidden; nothing overflows or clips awkwardly at
the :collapsed-size="3.5" width, matching the board's collapsed rail treatment.
- [ ] Keyboard/focus: Tab reaches UDashboardSidebarCollapse, then the UserMenu trigger; the
dropdown opens with Enter/Space, arrow keys move through the checkbox group, and Esc closes
it and returns focus to the trigger, in both the expanded and collapsed rail.
## Manual verification
- **Real POST /v1/auth/logout against a running server** — Vitest only mocks `useApi`; confirm the
real 200 round-trip against `task dev` with a live SQLite file, since these automated tests
never exercise the actual Go handler.
- **Real useColorMode persistence across reload** — confirm a selected preference survives a full
page reload via the plugin's `colorMode: true` storage, since Vitest only asserts the in-memory
preference value.
@@ -1,84 +0,0 @@
Feature: Deleting an article also deletes its images
As an authenticated RenewCMS user managing the CMS
I want deleting an article to also delete every image attached to it
So that removing an article doesn't leave orphaned image rows and files behind,
and so that an id that doesn't exist still answers 404 the same way every other
article write does
Background:
Given internal/domain/article.Article carries Images []*image.Image, populated by
ArticleRepository.Get via Preload("Images")
And internal/domain/image.Repository already exposes Delete(id uint32) error, which
on the real ImageRepository also removes the uploaded file from UPLOAD_DIR
And before this slice, DeleteArticleUseCase.DeleteArticle only called
articleRepository.Delete(id) and never touched image.Repository, so an article's
images were never deleted along with it
And this slice changes NewDeleteArticleUseCase to also take an image.Repository, and
changes DeleteArticleUseCase.DeleteArticle(id) to look up the article, delete every
image in its Images slice through image.Repository.Delete, and only then delete the
article itself through article.Repository.Delete
And this slice rewires api/dependecyInjection.go so
useCases.NewDeleteArticleUseCase(repos.ArticleRepo, repos.ImageRepo) supplies both
repositories
And DELETE /v1/article/{id} keeps sitting behind the jwtauth Verifier and
Authenticator group in api/router.go, unchanged from
features/write_not_found_errors.feature
And DELETE /v1/article/{id} keeps answering 204 with an empty body on success and 404
with body apperr.ArticleNotFoundErrorMessage for an id absent from the article
repository, backed by errors.Is(err, article.ErrArticleNotFound), unchanged from
features/write_not_found_errors.feature
And no image HTTP endpoint is mounted in api/router.go as of this slice, so cascading
image deletion is only observable through the image repository's state, not through
a separate HTTP call
And the use case deletes images in the order they appear in the article's Images
slice, and aborts on the first image.Repository.Delete error, leaving the article
and any not-yet-deleted images untouched, and answering the same generic 500 the
DeleteArticle handler already falls back to on any non-not-found error
Scenario: Deleting an article with images removes the article and every one of its images
Given a valid jwt cookie for a user with id 1
And the article repository contains an article with id 1 whose Images slice holds
image id 10 and image id 11
And the image repository contains images with id 10 and id 11
When the client sends DELETE /v1/article/1 with that cookie
Then the response status is 204
And the article repository no longer contains an article with id 1
And the image repository no longer contains an image with id 10 or id 11
Scenario: Deleting an article with no images still succeeds
Given a valid jwt cookie for a user with id 1
And the article repository contains an article with id 2 whose Images slice is empty
When the client sends DELETE /v1/article/2 with that cookie
Then the response status is 204
And the article repository no longer contains an article with id 2
And no call reaches the image repository's Delete method
Scenario: Deleting an unknown article still answers 404 and deletes no images
Given a valid jwt cookie for a user with id 1
And the article repository has no article with id 9999
When the client sends DELETE /v1/article/9999 with that cookie
Then the response status is 404
And the response body is the text "Article not found"
And no call reaches the image repository's Delete method
Scenario: Deleting an article still requires authentication
Given no jwt cookie is sent
And the article repository contains an article with id 1 whose Images slice holds
image id 10
When the client sends DELETE /v1/article/1 without a cookie
Then the response status is 401
And the article repository still contains the article with id 1
And the image repository still contains the image with id 10
Scenario: A failure deleting one of an article's images aborts the whole delete
Given a valid jwt cookie for a user with id 1
And the article repository contains an article with id 3 whose Images slice holds
image id 20 followed by image id 21
And the image repository contains images with id 20 and id 21
And the image repository's Delete fails for image id 20
When the client sends DELETE /v1/article/3 with that cookie
Then the response status is 500
And the response body is the text "Failed to delete article"
And the article repository still contains the article with id 3
And the image repository still contains the image with id 21
@@ -1,67 +0,0 @@
# QA procedure: delete_article_cascades_images
Package: `test` (black-box, extending `article_test.go`).
## Setup shared by every case
1. Call `validator.InitValidator()` once.
2. Reuse `mockArticleRepo` (`test/article_test.go`) and `mockImageRepo`
(`test/image_test.go`) as-is. Extend `mockArticleRepo` seeding so a seeded article's
`Images []*image.Image` can hold pointers into the same `mockImageRepo.images` map used
by the test, so deleting through the article side and asserting through the image side
observe the same state.
3. Add a call counter (or reuse the existing `failSwitch`/call-tracking pattern already in
`test/`) on `mockImageRepo.Delete` so a scenario can assert it was never called, and reuse
`mockImageRepo.fail` (the existing `failSwitch`) to make `Delete` fail for a specific
image id.
4. Wire the real use cases over the fakes: `useCases.NewCreateArticleUseCase`,
`useCases.NewGetArticleUseCase`, `useCases.NewListArticlesUseCase`,
`useCases.NewUpdateArticleUseCase`, and the new two-argument
`useCases.NewDeleteArticleUseCase(articleRepo, imageRepo)`. Build `article.NewHandler(...)`
with the same constructor shape it already has (the use case's internal dependency count
changes, not the handler's).
5. Build a test `jwtauth.New("HS256", []byte("test-secret"), nil)`.
6. Mount the routes on a fresh `chi.NewRouter()` mirroring `api/router.go`'s current shape:
`GET /` under `jwtauth.Verifier` only; `GET /{id}`, `POST /`, `DELETE /{id}`,
`PATCH /{id}`, `PATCH /{id}/publish`, `PATCH /{id}/unpublish` under `jwtauth.Verifier` +
`jwtauth.Authenticator`.
7. Mint a valid jwt cookie for user id 1: `token.Encode(map[string]any{"user_id": uint32(1)})`,
set as the `jwt` cookie on the relevant `httptest.NewRequest`.
## HTTP checks
8. Seed `imageRepo.images[10]` and `imageRepo.images[11]`, then seed
`articleRepo.articles[1] = article.Article{ID: 1, Title: "Backyard Renovation Update",
Images: []*image.Image{imageRepo.images[10], imageRepo.images[11]}}` (pointers into the
same map). Send `DELETE /v1/article/1` with the valid cookie -> status `204`; assert
`articleRepo.articles` no longer has key `1`; assert `imageRepo.images` no longer has
keys `10` or `11`.
9. Seed `articleRepo.articles[2] = article.Article{ID: 2, Title: "Draft: Kitchen Remodel"}`
with a nil/empty `Images` slice. Send `DELETE /v1/article/2` with the valid cookie ->
status `204`; assert `articleRepo.articles` no longer has key `2`; assert the image-delete
call counter is `0`.
10. Empty `articleRepo`, empty `imageRepo`. Send `DELETE /v1/article/9999` with the valid
cookie -> status `404`, body `"Article not found\n"`; assert the image-delete call
counter is `0`.
11. Seed `imageRepo.images[10]` and `articleRepo.articles[1]` with `Images` holding image id
10, per step 8's pattern. Send `DELETE /v1/article/1` with **no** cookie -> status `401`;
assert `articleRepo.articles[1]` is still present and `imageRepo.images[10]` is still
present.
12. Seed `imageRepo.images[20]` and `imageRepo.images[21]`, then seed
`articleRepo.articles[3] = article.Article{ID: 3, Title: "Kitchen Progress Photos",
Images: []*image.Image{imageRepo.images[20], imageRepo.images[21]}}` (image 20 before
image 21 in the slice). Arm `imageRepo.fail` so `Delete` returns an error only when
called with id `20` (leave id `21` unarmed). Send `DELETE /v1/article/3` with the valid
cookie -> status `500`, body `"Failed to delete article\n"`; assert
`articleRepo.articles[3]` is still present; assert `imageRepo.images[21]` is still
present (never reached because the delete aborted on image `20` first).
## Manual verification (not exercised by the Go test)
- Real cascading delete against a real SQLite file and real `UPLOAD_DIR`: confirm that after
`DELETE /v1/article/{id}` on a real running instance, the uploaded image files under
`UPLOAD_DIR` for that article are gone from disk and the `images` table no longer holds
those rows, and that no orphaned rows are left behind in the `article_images` join table.
Not exercised by `task test` (fakes only); requires `task dev` or a built `task build`
binary with a scratch DB/upload dir.
- SPA-visible behaviour: confirm the back-office article deletion flow (if/when one exists)
reflects that any images shown for that article are gone too. No such UI exists yet as of
this slice.
- No SMTP involvement.
@@ -0,0 +1,39 @@
Feature: Deleting an article never deletes images
As an authenticated RenewCMS user
I want deleting an article to leave the media library alone
So that an image used by other articles, or waiting in the library, is never lost
Background:
Given images belong to the library and internal/domain/article.Article carries no Images
And DeleteArticleUseCase depends only on article.Repository and calls its Delete
And api/dependecyInjection.go builds useCases.NewDeleteArticleUseCase(repos.ArticleRepo)
And DELETE /v1/article/{id} stays behind the same jwtauth group, answering 204 with an
empty body, 404 with apperr.ArticleNotFoundErrorMessage for errors.Is(err,
article.ErrArticleNotFound), and the generic 500 "Failed to delete article" otherwise
Scenario: Deleting an article leaves every image it used
Given a valid jwt cookie for user 1
And article 1 whose body contains the urls of images 10 and 11
And the image repository contains images 10 and 11
When the client sends DELETE /v1/article/1
Then the response status is 204
And the article repository no longer contains article 1
And the image repository still contains images 10 and 11 and Delete was never called
Scenario: Deleting an unknown article is 404 and touches no image
Given a valid jwt cookie for user 1 and no article 9999
When the client sends DELETE /v1/article/9999
Then the response status is 404 and the body is "Article not found"
And the image repository is untouched
Scenario: Deleting still requires authentication
Given no jwt cookie
When the client sends DELETE /v1/article/1
Then the response status is 401 and article 1 and image 10 still exist
Scenario: An article repository failure is 500 and everything stays
Given the article repository's Delete fails
When the client sends DELETE /v1/article/1 with a valid cookie
Then the response status is 500 and the body is "Failed to delete article"
And the image repository is untouched
@@ -0,0 +1,12 @@
# QA procedure: delete_article_keeps_images
Package: `test` (black-box). Wire `useCases.NewDeleteArticleUseCase(articleRepo)` (single argument) with the other article use cases and mount as in the retired `delete_article_cascades_images.qa.md`: `Verifier` plus `Authenticator`, `RequireCurrentToken`, `RequireVerifiedUser`, jwt cookie for user id 1. Seed images 10 and 11 in `mockImageRepo` and the article body with their urls. Call `validator.InitValidator()` first.
## HTTP checks
1. `DELETE /v1/article/1` with a valid cookie -> 204, `articleRepo` no longer holds article 1, `imageRepo.images` still holds 10 and 11 and `deleteCalls` is empty.
2. `DELETE /v1/article/9999` -> 404, body `"Article not found\n"`, image repo untouched.
3. `DELETE /v1/article/1` without cookie -> 401, article and images still present.
4. Article fake's `Delete` armed to fail -> 500, body `"Failed to delete article\n"`, image repo untouched.
## Manual verification
With a real SQLite file and `UPLOAD_DIR`, delete an article and confirm the image files and rows remain and still load. No SMTP.
+242
View File
@@ -0,0 +1,242 @@
Feature: Editor screen — load, edit and save an article's body
As a verified RenewCMS owner
I want /article/:id/edit to load an article, let me edit its body, save it, and warn me
before I lose unsaved work
So that I can safely write and revise an article's content, with clear feedback while
saving, near the length limit, offline, or when my session expires mid-edit
Background:
Given /article/:id/edit is a verified route (meta.auth "verified") rendered as EditorPage
inside DashboardShell, per docs/design/routes.md
And EditorPage calls GET /v1/article/{id} once per navigation to load the article, per
docs/design/screens/editor.md and features/public_article_read.feature
And the header shows breadcrumb "Articles › {article.title}" linking "Articles" to
/article (mobile top bar title "Edit article" instead), an ArticleStatusBadge size "md"
reflecting article.is_online ("Draft" or "Online"), a SaveStatus span, a Save button,
and a PublishControl button, per docs/design/components.md
And the article's title is never editable after creation, per
features/article_title_rules.feature; only the body is edited here
And the body is edited in ArticleEditor (modelValue bound to the fetched HTML body); any
change moves useArticleDraft's state from "clean" to "dirty", and PublishControl's label
switches from "Publish" (or "Unpublish", if online) to "Save and publish" while dirty and
the article is a draft; clicking PublishControl itself is out of scope for this slice and
is specified in a follow-on slice (editor_publish_and_delete)
And Save is enabled only when useArticleDraft's state is "dirty", the request is not already
in flight, the app is not offline, and the body's HTML length is at most 10000 characters;
it is disabled in every other case
And Save (a click, or Ctrl/⌘ S) sends PATCH /v1/article/{id} with JSON {"body": "..."},
the same contract features/edit_article_body.feature already gives the API: 200 with the
updated article.Article, 400 for a body over 10000 characters, 404 for an id absent from
the repository, 401 with no valid session
And a successful save (200) sets useArticleDraft's state to "saved" and records the save
time; SaveStatus shows "Saved at {HH:MM}" for the first hour and "Saved {n} min ago" after
an hour has passed, per docs/design/components.md
And a 500 response or a request that never reaches the server sets useArticleDraft's state
to "error"; SaveStatus shows "Save failed" with an inline Retry button (UButton size="xs"
variant="outline"); the edited body is kept exactly as typed, both in the editor and for
the next Retry
And a 404 response to a save (the article was deleted elsewhere) does not use the "error"
SaveStatus; it shows a toast "That article no longer exists.", per docs/design/states.md's
HTTP-status-to-copy table
And a 401 response to a save is handled by useApi's global handling
(features/api_client_global_error_handling.feature): before the redirect, useArticleDraft
mirrors the current dirty body to sessionStorage keyed by the article's id, so it survives
the redirect to /login?redirect=/article/{id}/edit&reason=expired
And CharacterCounter shows "{len} / 10 000" below the editor, using the body's HTML string
length (formatting and images count); at 9000 characters or more (90%, "Near the limit")
it adds a warning icon and stays enabled; above 10000 ("Too long") it adds an icon and the
text "{over} characters over. Shorten the text or remove an image. Formatting counts too.",
and disables both Save and PublishControl until the length is 10000 or fewer again
And a Preview switch, when on, replaces the editable ArticleEditor and its toolbar with a
read-only rendering of the title and body in the content type scale; switching it off
restores the editable surface with the same content, unchanged
And when navigator.onLine is false, or the browser fires a window "offline" event,
useArticleDraft's state becomes "offline"; SaveStatus shows the wifi-off icon and reads
"Waiting for connection"; Save and PublishControl are disabled with a tooltip explaining
why, and DashboardShell's existing OfflineBanner is shown; when the connection returns (a
window "online" event, or navigator.onLine true again), Save and PublishControl re-enable
according to the underlying dirty/saved/error state, which is unaffected by having been
offline
And navigating away (the breadcrumb "Articles" link, a sidebar nav link, the browser back
button, or closing the tab) while useArticleDraft's state is "dirty" opens ConfirmDialog
(neutral tone) titled "Leave without saving?", text 'Your changes to "{article.title}"
haven't been saved.', cancel "Discard changes", confirm "Keep editing"; "Discard changes"
proceeds with the navigation, discarding the edit; "Keep editing" closes the dialog and
keeps the user on the editor with the edit intact; navigating away while "clean" or
"saved" never opens this dialog
And an id absent from the repository (GET resolves 404) replaces the entire editor with an
error state: title "This article doesn't exist.", and a single action "All articles"
navigating to /article; no breadcrumb-title, SaveStatus, Save, PublishControl or
ArticleEditor renders in this state
And skeleton placeholders (for the title, content and details) replace the editor's content
only after 150 ms of GET /v1/article/{id} being unresolved, so a fast response never
flashes a skeleton, per the Skeleton component spec
Scenario: Skeletons appear only after 150 ms, never for a fast response
Given the user navigates to /article/12/edit for the first time in this session
When GET /v1/article/12 has not resolved 150 ms after the navigation
Then skeleton placeholders replace the title, content and details areas
When GET /v1/article/12 then resolves 200 with a draft article titled "How we price a
bathroom renovation"
Then the skeletons are replaced by the Saved state's header, editor and details
Given a second, separate navigation to /article/12/edit
When GET /v1/article/12 resolves in under 150 ms
Then no skeleton is ever shown, and the Saved state's content renders directly
Scenario Outline: Saved — a freshly loaded article, draft or online
Given GET /v1/article/12 resolves 200 with an article titled "How we price a bathroom
renovation", is_online <is_online>, body length 4318, updated_at "Today, 11:02"
When the user navigates to /article/12/edit
Then the breadcrumb reads "Articles › How we price a bathroom renovation"
And the ArticleStatusBadge reads "<badge>"
And SaveStatus reads "Saved at 11:02"
And the Save button is disabled
And PublishControl reads "<publish_label>"
And the character counter reads "4 318 / 10 000"
Examples:
| is_online | badge | publish_label |
| false | Draft | Publish |
| true | Online | Unpublish |
Scenario: Unsaved changes — any edit marks the article dirty
Given the user is on /article/12/edit in the Saved state, article "How we price a bathroom
renovation", draft
When the user types into the body
Then SaveStatus reads "Unsaved changes"
And the Save button becomes enabled
And PublishControl now reads "Save and publish"
Scenario: Saving — Save sends the PATCH and disables itself while in flight
Given the user is on /article/12/edit with unsaved changes to the body
When the user activates Save
Then PATCH /v1/article/12 is sent with JSON {"body": "<the edited body>"}
And SaveStatus reads "Saving…"
And the Save button is disabled
Scenario: Ctrl/⌘ S saves the same way as clicking Save
Given the user is on /article/12/edit with unsaved changes to the body
When the user presses Ctrl+S (or ⌘+S)
Then PATCH /v1/article/12 is sent with JSON {"body": "<the edited body>"}
And SaveStatus reads "Saving…"
Scenario: A successful save returns to the Saved state with the new time
Given the user is on /article/12/edit in the Saving state
When PATCH /v1/article/12 resolves 200 with the updated article
Then SaveStatus reads "Saved at {current time}"
And the Save button is disabled again
Scenario: SaveStatus switches to a relative time after an hour
Given the user is on /article/12/edit and PATCH /v1/article/12 resolved 200 at 11:02
When more than an hour has passed with no further edit or save
Then SaveStatus reads "Saved {n} min ago" instead of "Saved at 11:02"
Scenario Outline: Save failed — a 500 or a network failure keeps the changes and offers Retry
Given the user is on /article/12/edit with unsaved changes to the body "Revised opening
paragraph."
When the user activates Save
And PATCH /v1/article/12 <failure>
Then SaveStatus reads "Save failed" with a Retry button
And the editor still shows the body "Revised opening paragraph."
And no navigation occurs
Examples:
| failure |
| resolves with a 500 response |
| never reaches the server |
Scenario: Retry resends the same body and can recover
Given the user is on /article/12/edit in the Save failed state, with unsaved body "Revised
opening paragraph." and PATCH /v1/article/12 having failed with a 500
When the user activates Retry
Then PATCH /v1/article/12 is sent again with JSON {"body": "Revised opening paragraph."}
When it resolves 200 with the updated article
Then SaveStatus reads "Saved at {current time}"
Scenario: A save against an article deleted elsewhere shows a toast, not the error SaveStatus
Given the user is on /article/12/edit with unsaved changes to the body
When the user activates Save
And PATCH /v1/article/12 resolves 404
Then a toast reads "That article no longer exists."
And SaveStatus does not read "Save failed"
Scenario: Near the limit — the counter warns at 9000 characters without blocking Save
Given the user is on /article/12/edit with unsaved changes making the body's HTML length
9240 characters
Then the character counter reads "9 240 / 10 000" with a warning icon
And the Save button remains enabled
Scenario: Too long — over 10000 characters disables Save and Publish until shortened
Given the user is on /article/12/edit with unsaved changes making the body's HTML length
10214 characters
Then the character counter reads "10 214 / 10 000" with the text "214 characters over.
Shorten the text or remove an image. Formatting counts too."
And the Save button is disabled
And PublishControl is disabled
When the user shortens the body to 10000 characters or fewer
Then the character counter no longer shows the over-limit text
And the Save button is enabled again
Scenario: Preview shows the rendered title and body without the editing surface
Given the user is on /article/12/edit, article titled "How we price a bathroom renovation"
with some body content
When the user switches Preview on
Then the editing toolbar and the editable surface are replaced by a read-only rendering of
the title and body in the content type scale
When the user switches Preview off
Then the editable ArticleEditor and toolbar return, with the same body content unchanged
Scenario: Offline blocks Save and Publish, and recovers when the connection returns
Given the user is on /article/12/edit with unsaved changes to the body
When navigator.onLine becomes false
Then SaveStatus shows the wifi-off icon and reads "Waiting for connection"
And the Save button and PublishControl are disabled with a tooltip explaining why
When navigator.onLine becomes true again
Then the Save button re-enables, reflecting the still-unsaved change
And SaveStatus reads "Unsaved changes" again
Scenario: Leaving with unsaved changes prompts, and "Discard changes" proceeds
Given the user is on /article/12/edit with unsaved changes to the body
When the user activates the "Articles" breadcrumb link
Then ConfirmDialog opens, titled "Leave without saving?", text 'Your changes to "How we
price a bathroom renovation" haven't been saved.', cancel "Discard changes", confirm
"Keep editing"
When the user activates "Discard changes"
Then the app navigates to /article
And the edited body is not saved
Scenario: Leaving with unsaved changes, "Keep editing" stays on the page
Given the user is on /article/12/edit with unsaved changes to the body, and the "Leave
without saving?" dialog is open
When the user activates "Keep editing"
Then the dialog closes
And the user remains on /article/12/edit with the unsaved body intact
Scenario: Leaving a clean article never prompts
Given the user is on /article/12/edit in the Saved state, with no unsaved changes
When the user activates the "Articles" breadcrumb link
Then the app navigates to /article directly, with no ConfirmDialog
Scenario: Session expired mid-save keeps the draft and restores it after logging back in
Given the user is on /article/12/edit with unsaved changes to the body "Paragraph added
just before the session expired."
When the user activates Save
And PATCH /v1/article/12 resolves 401
Then the body "Paragraph added just before the session expired." is mirrored to
sessionStorage keyed by article id 12
And the app navigates to /login?redirect=/article/12/edit&reason=expired
When the user logs in again and is returned to /article/12/edit
And GET /v1/article/12 resolves 200 with the last-saved body (without that paragraph)
Then the editor shows the body "Paragraph added just before the session expired." restored
from sessionStorage, not the last-saved body from the GET
And SaveStatus reads "Unsaved changes"
Scenario: An unknown or deleted article id replaces the editor with an error state
Given GET /v1/article/9999 resolves 404
When the user navigates to /article/9999/edit
Then the editor shows a single error state: title "This article doesn't exist." and one
action "All articles"
And no breadcrumb-title, SaveStatus, Save, PublishControl or ArticleEditor renders
When the user activates "All articles"
Then the app navigates to /article
+129
View File
@@ -0,0 +1,129 @@
# QA: Editor screen — load, edit and save (core)
## Implementation note for coder (informational, not a QA assertion)
`docs/design/components.md`'s `ErrorView` only documents two fixed copies (`kind: 'not-found'` →
"Page not found" / Home, and `kind: 'error'` → the generic retry copy). The editor's own 404-on-
load state needs different copy ("This article doesn't exist." / "All articles" → /article),
per `docs/design/states.md`'s HTTP-status-to-copy table. Either widen `ErrorView` with an optional
title/description/action override, or add a third `kind`; this is a same-layer prop widening, not
a new component, so it doesn't need its own slice.
Known limitation, not a bug to silently fix: per `features/public_article_read.feature`,
`GET /v1/article/{id}` falls back to public online-only visibility on a malformed/expired jwt
(no 401). So if a session is already stale when the owner opens an *offline* article, the GET
answers 404 exactly like a truly deleted article — the editor cannot tell the two apart from this
response alone, and correctly shows the "This article doesn't exist." state.
## Automated (Vitest + Vue Test Utils, `task test:web`)
Mock `useApi`'s `request` for `GET /v1/article/{id}` and `PATCH /v1/article/{id}` per case; no
real backend, no httptest server. Mount EditorPage inside DashboardShell with a resolved verified
session (username "marta") and a test router at `/article/12/edit`. Use fake timers for the
150 ms skeleton delay and the relative-time SaveStatus format. Use `Object.defineProperty`/mocked
`navigator.onLine` and dispatched `window` `online`/`offline` events for the offline scenarios.
Fixture article (reused across cases unless a scenario overrides a field): id 12, title
"How we price a bathroom renovation", is_online false, body length 4318, created_at
"2026-03-12T09:14:00Z", updated_at "2026-09-26T11:02:00Z" (fixed `now`
"2026-09-26T11:02:00Z" unless a scenario advances it).
1. **Skeleton only after 150 ms** — mock `GET /v1/article/12` unresolved; assert no skeleton
before 150 ms; advance past it; assert skeleton placeholders for title/content/details;
resolve 200; assert the Saved state renders. Separately, resolve under 150 ms; assert no
skeleton ever renders.
2. **Saved state, draft and online** — Examples-driven on `is_online`: mock `GET
/v1/article/12` resolving 200 with the fixture at each `is_online` value; assert the
breadcrumb, ArticleStatusBadge ("Draft"/"Online"), SaveStatus "Saved at 11:02", Save
disabled, PublishControl ("Publish"/"Unpublish"), and character counter "4 318 / 10 000".
3. **Unsaved changes** — from the Saved state, type into the body; assert SaveStatus "Unsaved
changes", Save enabled, PublishControl now "Save and publish".
4. **Saving via click and via Ctrl/⌘ S** — from Unsaved changes, (a) click Save, (b) press
Ctrl+S; in each, assert `PATCH /v1/article/12` is called with the edited body, SaveStatus
"Saving…", Save disabled while unresolved.
5. **Successful save** — from Saving, resolve `PATCH` 200 with the updated article; assert
SaveStatus "Saved at {time}" and Save disabled again.
6. **Relative save time after an hour** — after a 200 save at 11:02, advance the fake clock past
one hour with no further edit; assert SaveStatus switches to "Saved {n} min ago".
7. **Save failed, Examples-driven** — (a) `PATCH` resolves 500, (b) `PATCH` rejects (network);
in each, assert SaveStatus "Save failed" with a visible Retry button, and the editor still
shows the typed body.
8. **Retry recovers** — from Save failed (500), click Retry; assert `PATCH` is called again with
the same body; resolve 200; assert SaveStatus "Saved at {time}".
9. **404 on save shows a toast, not the error SaveStatus** — from Unsaved changes, save; resolve
`PATCH` 404; assert a toast "That article no longer exists." appears and SaveStatus never
reads "Save failed".
10. **Near the limit** — set the body's HTML length to 9240 (via a fixture string of that
length); assert counter "9 240 / 10 000" with a warning icon and Save still enabled.
11. **Too long** — set the body's HTML length to 10214; assert counter "10 214 / 10 000" with
"214 characters over. Shorten the text or remove an image. Formatting counts too.", Save
disabled, PublishControl disabled; shorten to 10000; assert both re-enable and the over-limit
text disappears.
12. **Preview toggle** — from a loaded article with body content, switch Preview on; assert the
toolbar and editable surface are gone and a read-only rendering of title+body appears;
switch off; assert the editable surface returns with the same content.
13. **Offline blocks and recovers** — from Unsaved changes, set `navigator.onLine` false and
dispatch `window` `offline`; assert SaveStatus shows the wifi-off icon and reads "Waiting
for connection", Save and PublishControl disabled with a tooltip; set `navigator.onLine`
true and dispatch `online`; assert Save re-enables and SaveStatus reads "Unsaved changes"
again.
14. **Leave guard: Discard changes proceeds** — from Unsaved changes, click the "Articles"
breadcrumb link; assert ConfirmDialog opens with the exact title/text/button labels; click
"Discard changes"; assert the router navigates to `/article` and no further `PATCH` fires.
15. **Leave guard: Keep editing stays** — same setup; click "Keep editing"; assert the dialog
closes and the router does not navigate, and the unsaved body is still shown.
16. **No leave guard when clean** — from the Saved state, click the "Articles" breadcrumb link;
assert the router navigates to `/article` with no ConfirmDialog ever rendered.
17. **Session expiry mid-save mirrors and restores the draft** — from Unsaved changes with body
"Paragraph added just before the session expired.", save; resolve `PATCH` 401; assert
`sessionStorage` holds that body keyed by article id 12, and the router navigates to
`/login?redirect=/article/12/edit&reason=expired`. Then, simulating the return trip, mount
EditorPage again at `/article/12/edit` with `GET /v1/article/12` resolving 200 with a body
that lacks that paragraph; assert the rendered body is the restored sessionStorage draft
(with the paragraph) and SaveStatus reads "Unsaved changes".
18. **Not found on load** — mock `GET /v1/article/9999` resolving 404; mount at
`/article/9999/edit`; assert only the error state renders (title "This article doesn't
exist.", action "All articles"), with no breadcrumb-title/SaveStatus/Save/PublishControl/
ArticleEditor; click "All articles"; assert the router navigates to `/article`.
## Visual (manual verification — desktop and mobile, light and dark)
Reference: `docs/design/screens/editor.md` and `docs/design/source/RenewCMS Screens
Back-office.dc.html`, group "Editor". Run `task visual:check -- editor` for each state below and
compare against the board frame; add each state's mock setup to `web/visual/states.ts` first,
reusing the sample data below and a fixed `now` of "2026-09-26T11:02:00Z" (updated_at "Today,
11:02"; created_at "12 Mar 2026, 09:14"; id 12; title "How we price a bathroom renovation";
3 images).
- [ ] Loading: skeletons for title, content and details, shaped like the real layout.
- [ ] Saved: breadcrumb, "Draft" badge, "Saved at 11:02", disabled Save, "Publish", counter
"4 318 / 10 000", details panel (Created/Updated/ID/Images/Public API URL).
- [ ] Unsaved changes: "Unsaved changes" SaveStatus, enabled Save, "Save and publish".
- [ ] Saving: "Saving…" SaveStatus, disabled Save.
- [ ] Save failed: "Save failed" with Retry, per the SaveStatus error spec.
- [ ] Near the limit: counter "9 240 / 10 000" with the warning icon/style.
- [ ] Too long: counter "10 214 / 10 000" with the over-limit text and disabled Save/Publish.
- [ ] Preview: read-only rendered title and body in the content scale, toolbar hidden.
- [ ] Offline: SaveStatus shows the wifi-off icon and reads "Waiting for connection", disabled
Save/Publish, OfflineBanner visible.
- [ ] Not found (404): the standalone error state, no editor chrome.
- [ ] Mobile (all of the above at 390×844): sticky bottom bar for Save/PublishControl, details
panel as a slideover, single "Edit article" mobile top-bar title instead of the breadcrumb.
- [ ] Keyboard/focus: Tab reaches the breadcrumb, Save, Preview switch and PublishControl in a
sensible order; Ctrl/⌘ S saves from anywhere in the editor surface; the leave-guard
ConfirmDialog traps focus starting on "Discard changes" per ConfirmDialog's a11y spec, and
Esc behaves like dismissing (equivalent to "Keep editing"); the character-counter live
region announces only when crossing the warn/over thresholds, not on every keystroke.
- [ ] Motion: modal open/close and skeleton pulse follow the standard 240 ms / 1.6 s timings and
stop under reduced motion.
## Manual verification
- **Real GET/PATCH round trip against a running server** — Vitest only mocks `useApi`; confirm
the real 200/404/401/500 responses and the real `sessionStorage` restoration across an actual
session expiry (`JWT_SECRET`-signed cookie timing out) against `task dev` with a live SQLite
file, since automated tests never exercise the real Go handler, `UpdateArticleUseCase`, or a
real cookie's `exp` claim.
- **Real `beforeunload` prompt** — Vitest can assert `onBeforeRouteLeave`'s ConfirmDialog, but a
real browser tab-close prompt (native `beforeunload`) needs manual confirmation, since jsdom
doesn't model it.
+133
View File
@@ -0,0 +1,133 @@
Feature: Crop and resize step in the editor's image uploader
As a verified RenewCMS owner adding an image to an article
I want to crop and resize a JPEG, PNG or WEBP before it uploads
So that I control the framing and file size of images in my articles, without needing an
external editor
Background:
Given ImageUploader inserts a crop-and-resize step between the idle file picker and the
upload, for any JPEG, PNG or WEBP that already passed the browser validation described in
features/editor_image_upload.feature; that feature's idle, dragging-over, rejected,
uploading, inserted and failed states and its POST /v1/media/ contract are unchanged and
out of scope here
And the hash lookup from features/editor_image_upload.feature runs before this step opens,
so the step only opens for a file with no match, or after "Upload anyway"
And an SVG file skips this step entirely and uploads immediately, as before
And opening the step retitles the modal from "Add an image" to "Crop and resize", with the
description "{filename} · {size}" (e.g. "north-wall.jpg · 3.9 MB")
And the stage shows the chosen image at its natural pixel dimensions with a crop frame that
starts as the whole image: a rule-of-thirds grid (lines at 33.3 %/66.6 %), four 12×12 px
corner handles, and a mono pixel-size label in a dark pill at the frame's bottom-left
corner, tracking the frame's current size
And the frame is reachable by Tab (tabindex="0"), aria-label "Crop area. Arrow keys move it,
Shift and arrow keys resize it."; dragging the frame moves it, dragging a handle resizes
it, arrow keys nudge it by 1 px, and Shift+arrow keys resize it by 1 px
And above the frame, "Aspect ratio" is a radiogroup of five pills — Original, Free, 16:9,
4:3, 1:1 — next to "Rotate" and "Reset" actions; "Width" is a second radiogroup — Original,
1600 px (default), 1200 px, 800 px
And a mono line below reads "Uploads as {width} × {height} px · about {size}" (KB under
1 MB, MB at or above it), recomputed whenever the ratio, width, frame rect or rotation
changes
And the output width is min(the chosen width preset, the crop frame's own pixel width) —
never upscaled — and the output height keeps the crop frame's own aspect ratio; when the
crop is narrower than the chosen width, an info row reads "The crop is {crop width} px
wide, so it's uploaded at that size. Enlarging it would make it blurry."
And the footer offers "Choose another file" (discards this step and returns to the idle file
picker, with the tabs, with no adjustments carried over) and "Upload image" (uploads the cropped, resized
file through the unchanged POST /v1/media/ flow)
And "Rotate" turns the image 90° clockwise each activation, cycling 0°→90°→180°→270°→0°, and
width presets apply to the post-rotation image
And "Reset" returns the ratio to Original, the width to 1600 px, the crop frame to the whole
unrotated image, and the rotation to 0°, without closing the modal
Scenario: A raster file opens the crop-and-resize step instead of uploading immediately
Given ImageUploader is open in the idle state for article 12
When the user chooses a file named "north-wall.jpg", content type "image/jpeg", size 3.9 MB,
natural dimensions 4032 × 3024 px
Then no request is sent to POST /v1/media/
And the modal retitles to "Crop and resize" with the description "north-wall.jpg · 3.9 MB"
And the crop frame starts as the whole image, ratio "Original" is selected, and width
"1600 px" is selected
And the mono line reads "Uploads as 1600 × 1200 px · about 420 KB"
And the footer reads "Choose another file" and "Upload image"
Scenario: An SVG skips the crop step and uploads immediately
Given ImageUploader is open in the idle state for article 12
When the user chooses a file named "diagram.svg", content type "image/svg+xml", size 40 KB
Then POST /v1/media/ is sent immediately with that file
And the crop-and-resize step is never shown
Scenario Outline: Choosing an aspect ratio locks the frame to it
Given the crop-and-resize step is open for "north-wall.jpg" (4032 × 3024 px), ratio
"Original", width "1600 px"
When the user selects ratio "<ratio>"
Then the crop frame becomes <crop_width> × <crop_height> px, centered on the image
And dragging or resizing the frame afterwards keeps that aspect ratio
And the mono line reads "Uploads as <out_width> × <out_height> px · about {size}"
Examples:
| ratio | crop_width | crop_height | out_width | out_height |
| 16:9 | 4032 | 2268 | 1600 | 900 |
| 4:3 | 4032 | 3024 | 1600 | 1200 |
| 1:1 | 3024 | 3024 | 1600 | 1600 |
Scenario: Choosing a narrower width preset recomputes the output without upscaling
Given the crop-and-resize step is open for "north-wall.jpg", ratio "Original", width
"1600 px"
When the user selects width "800 px"
Then the mono line reads "Uploads as 800 × 600 px · about {size}", a smaller estimate than
before
Scenario: A crop narrower than the chosen width is uploaded at its own size, not upscaled
Given the crop-and-resize step is open for "north-wall.jpg", ratio "1:1", width "1600 px"
When the user resizes the crop frame down to 640 × 640 px
Then the mono line reads "Uploads as 640 × 640 px · about {size}"
And an info row reads "The crop is 640 px wide, so it's uploaded at that size. Enlarging it
would make it blurry."
Scenario: Free ratio removes the aspect-ratio constraint
Given the crop-and-resize step is open for "north-wall.jpg", ratio "Original"
When the user selects ratio "Free"
Then the crop frame can be dragged or resized to any width and height independently, no
longer snapping to a fixed ratio
Scenario: Arrow keys move the crop frame and Shift+arrow keys resize it
Given the crop-and-resize step is open for "north-wall.jpg" with the crop frame focused
When the user presses ArrowRight
Then the frame moves 1 px right and the mono line's size is unchanged
When the user presses Shift+ArrowRight
Then the frame's width grows by 1 px and the mono line updates to the new output size
Scenario: Rotate cycles the image in 90° steps and Reset returns to the opened defaults
Given the crop-and-resize step is open for "north-wall.jpg" at ratio "16:9", width "800 px"
When the user activates "Rotate"
Then the image and crop frame rotate 90° clockwise
When the user activates "Reset"
Then ratio returns to "Original", width returns to "1600 px", the frame returns to the
whole, unrotated image, and the mono line reads "Uploads as 1600 × 1200 px · about 420 KB"
Scenario: "Choose another file" returns to the file picker without uploading
Given the crop-and-resize step is open for "north-wall.jpg"
When the user activates "Choose another file"
Then no request is sent to POST /v1/media/
And the idle state is shown again, with the file picker available
Scenario: A newly chosen file opens a fresh crop step, not the previous file's adjustments
Given the user returned to idle via "Choose another file" from a crop step that had ratio
"16:9" and width "800 px"
When the user chooses a new file named "sunset.jpg", content type "image/jpeg", size 2.1 MB,
natural dimensions 3000 × 2000 px
Then the crop-and-resize step reopens with ratio "Original", width "1600 px", and the frame
as the whole new image
Scenario: "Upload image" uploads the cropped, resized file, not the original
Given the crop-and-resize step is open for "north-wall.jpg" with ratio "Original", width
"1600 px" and the mono line "Uploads as 1600 × 1200 px · about 420 KB"
When the user activates "Upload image"
Then POST /v1/media/ is sent with a single file under the field name "file" whose
pixel dimensions are 1600 × 1200 and whose size is about 420 KB, not the original
4032 × 3024, 3.9 MB file
And the uploading state shows "Uploading 0.0 of 420 KB"
When the upload reports 180 KB sent of 420 KB
Then the uploading state shows "north-wall.jpg 43%" and "Uploading 180 of 420 KB"
+86
View File
@@ -0,0 +1,86 @@
# QA: Crop and resize step in the editor's image uploader
## Automated (Vitest + Vue Test Utils, `task test:web`)
Mount EditorPage inside DashboardShell at `/article/12/edit` with the editor_core.qa.md fixture
article (id 12, "How we price a bathroom renovation", is_online false), GET already resolved
200. Reuse editor_image_upload.qa.md's fake-XHR setup for the upload itself. Stub the chosen
file's decoded natural size (e.g. mock `Image`/`createImageBitmap` or whatever the component
uses to read `naturalWidth`/`naturalHeight`) so tests control it deterministically, and stub the
crop/resize step's own output producer (whatever function turns the frame rect + width preset
into a Blob) as a spy, asserting it is called with the frame's rect in natural-image pixels and
the resolved output width/height, and stubbing its returned Blob's size — without asserting how
it renders internally (canvas/OffscreenCanvas is a coder implementation detail).
1. **A raster file opens "Crop and resize" instead of uploading** — choose `north-wall.jpg`
(image/jpeg, 3.9 MB, natural 4032×3024); assert no XHR is created; assert the modal title is
"Crop and resize", description "north-wall.jpg · 3.9 MB", ratio "Original" and width
"1600 px" selected, mono line "Uploads as 1600 × 1200 px · about 420 KB", footer "Choose
another file" / "Upload image".
2. **An SVG bypasses the step** — choose `diagram.svg` (image/svg+xml, 40 KB); assert an XHR to
`/v1/media/` is created immediately and the crop step never renders.
3. **Ratio presets lock the frame, Examples-driven (16:9 / 4:3 / 1:1)** — from the opened step,
select each ratio pill; assert the frame's reported rect and the mono line's output size match
the feature's Examples table.
4. **Width preset recomputes the output** — select width "800 px"; assert the mono line reads
"Uploads as 800 × 600 px" (assert dimensions exactly; assert only that the size figure changed
to a smaller value, not a specific number).
5. **A crop narrower than the width shows the info row and keeps its own size** — resize the
frame (via its resize API/spy) to 640×640 with ratio "1:1", width "1600 px"; assert the mono
line reads "Uploads as 640 × 640 px · about {size}" and the info row reads exactly "The crop
is 640 px wide, so it's uploaded at that size. Enlarging it would make it blurry."
6. **Free ratio removes the constraint** — select ratio "Free"; assert a subsequent resize call
with independent width/height is accepted without being coerced back to a ratio.
7. **Arrow and Shift+Arrow keys move/resize** — focus the frame; fire `ArrowRight`; assert the
frame's x increases by 1 px and the mono line's size is unchanged; fire `Shift+ArrowRight`;
assert the frame's width increases by 1 px and the mono line updates.
8. **Rotate cycles 90° and Reset restores defaults** — activate "Rotate"; assert the reported
rotation is 90°; activate "Reset"; assert ratio "Original", width "1600 px", the frame back to
the whole unrotated image, and the mono line "Uploads as 1600 × 1200 px · about 420 KB".
9. **"Choose another file" discards the step** — activate it; assert no XHR was created and the
idle state renders.
10. **A newly chosen file reopens at defaults** — from idle after "Choose another file" out of a
16:9/800px step, choose `sunset.jpg` (image/jpeg, 2.1 MB, natural 3000×2000); assert the new
crop step opens with ratio "Original", width "1600 px", frame as the whole new image (not the
previous file's ratio/width).
11. **"Upload image" sends the cropped/resized file** — from the default 1600×1200/420 KB step,
activate "Upload image"; assert the XHR is created with a file whose declared size is 420 KB
(not 3.9 MB); assert the uploading state shows "Uploading 0.0 of 420 KB"; fire an
`upload.progress` with `loaded: 180 * 1024, total: 420 * 1024`; assert "north-wall.jpg 43%"
and "Uploading 180 of 420 KB".
## Visual (manual verification via `task visual:check -- editor` — desktop and mobile, light and
dark)
Reference: `docs/design/screens/editor.md` states "Upload: crop and resize", "Upload: crop to a
ratio", "Upload: crop narrower than the width", and the updated "Upload: in progress"; board
`docs/design/source/RenewCMS Screens Back-office.dc.html`, group "Editor". Add each state's mock
setup to `web/visual/states.ts`, reusing editor_core.qa.md's fixture article (id 12, "How we
price a bathroom renovation", draft) and the sample file "north-wall.jpg · 3.9 MB".
- [ ] Upload: crop and resize — modal "Crop and resize" / "north-wall.jpg · 3.9 MB", ratio
"Original", width "1600 px", cancel "Choose another file", confirm "Upload image".
- [ ] Upload: crop to a ratio — same modal, ratio "16:9" selected, frame locked to that ratio.
- [ ] Upload: crop narrower than the width — ratio "1:1", width "1600 px", frame resized to
640×640, info row "The crop is 640 px wide, so it's uploaded at that size. Enlarging it
would make it blurry."
- [ ] Upload: in progress (updated) — modal "Add an image", uploading "north-wall.jpg 43%" /
"Uploading 180 of 420 KB", cancel "Cancel upload".
- [ ] Mobile (all of the above at 390×844): same modal layout constraints as other editor modals.
- [ ] Keyboard/focus: the crop frame is reachable by Tab; its `aria-label` is "Crop area. Arrow
keys move it, Shift and arrow keys resize it."; Arrow/Shift+Arrow move and resize it without
moving focus elsewhere; the aspect-ratio and width radiogroups follow standard roving-tabindex
radiogroup keyboard behavior (arrow keys between pills, one tab stop per group); "Rotate" and
"Reset" are reachable and named by their visible text.
- [ ] Motion: no auto-close or timed transition in this step; frame drag/resize follows pointer
with no easing delay (not part of the 10 % capture budget, spot-checked only).
## Manual verification
- **Real image decoding and resizing** — Vitest stubs `naturalWidth`/`naturalHeight` and the
output producer; confirm real JPEG/PNG/WEBP files of varying orientations and EXIF rotation
crop, rotate and resize correctly against `task dev` with a live server, since jsdom has no
real canvas/image pipeline.
- **Real POST of the resized file** — confirm the actual uploaded bytes decode to the expected
pixel dimensions server-side, complementing `features/upload_article_image.feature`'s
httptest coverage of the handler in isolation.
+90
View File
@@ -0,0 +1,90 @@
Feature: Removing an inline image from the article
As a verified RenewCMS owner writing an article
I want to take an image out of the article body, from a button or with Backspace or Delete
So that an unwanted image leaves the article without deleting the file from my library
Background:
Given this slice is SPA only for this file; the Go alias deletion is in
features/remove_legacy_article_image_alias.feature
And docs/design/screens/media-picker.md now covers this flow ("Remove image: confirm" and
"Removed"); it supersedes the earlier version of this feature, which had no design
coverage and used a red confirm that deleted through DELETE /v1/article/{id}/image/{imageId}
And removing an image is a body edit only: no API call of any kind is sent, before, during
or after the confirm, and the library and every other article are untouched
And ArticleEditor keeps its exposed insertImage(src, alt, imageId) and removeImage(imageId),
its "request-remove-image" event with the image id, and its Backspace and Delete handling,
which still intercepts the keys before Tiptap deletes the node
And an image already in a body from before data-image-id existed has no id, shows no
"Remove image" button and is not intercepted by Backspace or Delete (unchanged)
And selecting an image node that carries data-image-id shows a button "Remove image" at the
image's top-right corner (8 px from the top and right): trash-2 icon at 14 px, neutral,
28 px high, 12 px medium text, a 1 px accented border and the page background; deselecting
hides it
And EditorView reacts to "request-remove-image" by opening ConfirmDialog with tone "neutral",
title "Remove this image from the article?", description "It's removed from this article
only. The file stays in your library and in any other article that uses it.", confirmLabel
"Remove image" and cancelLabel "Cancel"; the confirm button is primary, not red
And the body of the confirm is a bordered row with a 56 × 42 px thumbnail of the image, its
filename, and "Stays in the library · {size}", for example "north-wall.jpg" and "Stays in
the library · 3.9 MB"
And the filename and size come from the images the SPA has seen this session, kept by image
id: those inserted from either tab and those loaded in the Library list
And confirming runs removeImage(imageId), moves useArticleDraft to "dirty", closes the
dialog and shows the toast; the action cannot fail, so there is no inline error
And a thumbnail uses the image's src from the node
Scenario: Selecting an inserted image reveals "Remove image"
Given the user is on /article/12/edit with an image in the body carrying data-image-id "1"
When the user clicks that image
Then a button "Remove image" with a trash-2 icon shows at the image's top-right corner
When the user clicks elsewhere in the editor
Then the button is no longer shown
Scenario: An image without data-image-id has no button
Given the body has an image with no data-image-id
When the user clicks it
Then no "Remove image" button shows and Backspace does nothing special to it
Scenario Outline: Either trigger opens the neutral confirm and sends nothing
Given the image with data-image-id "1" ("north-wall.jpg", 3.9 MB, inserted this session) is selected on /article/12/edit
When the user <triggers-removal>
Then a dialog titled "Remove this image from the article?" opens, with the description "It's removed from this article only. The file stays in your library and in any other article that uses it."
And its body shows the thumbnail, "north-wall.jpg" and "Stays in the library · 3.9 MB"
And its buttons read "Cancel" and a primary "Remove image"
And no request has been sent
And the image node is still in the editor's content (Tiptap's native deletion did not run)
Examples:
| triggers-removal |
| activates the "Remove image" button |
| presses Backspace with the image node selected |
| presses Delete with the image node selected |
Scenario: The confirm for an image the session has not seen
Given the image with data-image-id "7" was in the saved body and is not in the session's record
When the user activates "Remove image"
Then the body row shows the thumbnail and "Stays in the library" with no filename and no size
Scenario: Cancelling changes nothing
Given the confirm is open for image id 1
When the user activates "Cancel"
Then the dialog closes, no request has been sent, the image is still in the content, and the draft's dirty state is unchanged
Scenario: Confirming removes the image from the body only
Given the confirm is open for image id 1 on /article/12/edit, the draft in the Saved state
When the user activates "Remove image"
Then the dialog closes and the image leaves the editor's content
And SaveStatus reads "Unsaved changes" and Save is enabled
And a toast appears: color success, icon i-lucide-circle-check, title "Image removed", description "It's still in your library."
And no request of any kind has been sent
Scenario: A removal started by Backspace behaves like one started by the button
Given the confirm is open for image id 1, opened by Backspace, the draft in the Saved state
When the user activates "Remove image"
Then the outcome is the same as above
Scenario: The removed image can be picked again
Given image id 1 was removed from the body this session
When the user opens the Library tab
Then "north-wall.jpg" no longer carries "In this article"
+25
View File
@@ -0,0 +1,25 @@
# QA: Removing an inline image from the article
## Automated (Vitest + Vue Test Utils, `task test:web`)
Mount EditorPage at `/article/12/edit` with the `editor_core.qa.md` fixture article and a body of `<img src="/static/uploadedImages/1.jpg" data-image-id="1" alt="">`. Seed the session's image record with id 1 ("north-wall.jpg", 3.9 MB). Spy on `request` and on `XMLHttpRequest` and assert they are never called by any step below.
1. **Selecting reveals the button** - click the image; assert a button named "Remove image" with a trash-2 icon renders at the corner; click elsewhere; assert it is gone.
2. **No id, no button** - an image without `data-image-id`: no button, and a Backspace keydown does not open the dialog.
3. **Triggers, Examples-driven** - button click, Backspace keydown and Delete keydown each open the dialog with the exact title, description, "Cancel" and a primary (not error) "Remove image"; assert the body shows the thumbnail, "north-wall.jpg" and "Stays in the library · 3.9 MB"; assert no request; assert the node is still in the document.
4. **Unseen image** - id 7 not in the record; assert the row shows the thumbnail and "Stays in the library" only.
5. **Cancel changes nothing.**
6. **Confirm** - click "Remove image"; assert the dialog closes, the node is gone, SaveStatus "Unsaved changes", Save enabled, the toast (color success, icon `i-lucide-circle-check`, "Image removed" / "It's still in your library."), and zero requests.
7. **Backspace-opened confirm** gives the same outcome as 6.
8. **Removed image loses its tag** - open the Library after step 6; assert "north-wall.jpg" has no "In this article" tag.
## Visual: `task visual:check -- media-picker`
The states "Remove image: confirm" and "Removed" are in the `media-picker` group; the setups are in `editor_media_picker.qa.md`. The sample data is north-wall.jpg, image id 1, 3.9 MB. The "Remove image" button is visible in "Remove image: confirm" and "Inserted", so the setup must select the image node. The confirm's confirm button must not be error-coloured.
- [ ] Keyboard and focus: the button is reachable by Tab and activates with Enter or Space. Backspace or Delete with focus outside the editor does nothing. ConfirmDialog's focus trap and default focus on "Cancel" are unchanged.
## Manual verification
- **Real keyboard behaviour** in a real browser, including an IME: Backspace or Delete on a selected image opens the confirm instead of deleting the node (jsdom doesn't exercise ProseMirror's keymap precedence).
- **Save after removal** against `task dev`: remove an image, save, reload; the image is gone from the article and still listed in `/media`.
+191
View File
@@ -0,0 +1,191 @@
Feature: The editor's Upload tab uploads to the library
As a verified RenewCMS owner writing an article
I want the Upload tab of the "Add an image" dialog to check my file, spot duplicates,
upload to my library and insert the result at my cursor
So that I can add images to an article's body without leaving the editor, with clear
feedback when a file is rejected or the upload fails
Background:
Given this slice is SPA only for this file: the API from the media library slice is used
unchanged
And EditorView listens for ArticleEditor's "request-image" event and opens ImageUploader
(a UModal titled "Add an image") with the picker tabs, whose Library tab is specified in
features/editor_media_picker.feature
And dropping a file onto the editor surface opens ImageUploader on the Upload tab with that
file already provided, and no list request is sent until the Library tab is opened
And this file supersedes these statements of the earlier version: the upload goes to
POST /v1/media/ and no longer to POST /v1/article/{articleId}/image; the 201 body is the
library item { id, filename, url, size, content_type, width, height, sha256, uploaded_by,
created_at, used_in, duplicate }; there is no article id in any upload request and no 404
for a deleted article on upload
And ImageUploader validates a chosen or dropped file in the browser with validateImageFile
from web/src/lib/imageUpload.ts, size first (10485760 bytes allowed, one byte more is too
large), then MIME type and extension must both be allowed (png, jpeg, webp, svg), before
hashing or sending anything
And a file that passes validation is hashed with hashFile from web/src/lib/fileHash.ts (the
lib shared with MediaPage), and GET /v1/media/?hash=<sha256 hex> is sent through useApi;
when hashFile resolves null, or the lookup fails with 500 or a network error, the check
is skipped and the flow continues as if nothing matched
And a file with no match continues exactly as in features/editor_image_crop_resize.feature:
a JPEG, PNG or WEBP opens the crop and resize step, an SVG is uploaded immediately
And the upload is sent with XMLHttpRequest (not useApi) so progress is observable, as
multipart/form-data with the file under the field name "file" to POST /v1/media/, with the
jwt cookie
And a 201 inserts the item's url at the cursor through insertImage(item.url, "", item.id),
so the node carries data-image-id, and useArticleDraft moves to "dirty"
And closing the dialog while an upload is in flight aborts the XMLHttpRequest
And the tabs show only on the choose step (idle, the duplicate card and the Library tab);
the crop, uploading, rejected and failed steps keep the earlier look without tabs
And the footer on the Upload tab holds only the step's own actions ("Cancel" in idle);
there is no "Insert image" button on it
Rule: Opening
Scenario: The toolbar's image button opens on Upload when the library is empty
Given the user is on /article/12/edit with the editor focused
And GET /v1/media/?limit=24 resolves 200 with no item
When the user activates the toolbar's "Image" button
Then ImageUploader opens titled "Add an image" with the tabs "Upload" (icon upload) and "Library" (icon images)
And the Upload tab is selected and shows the image-plus icon, "Drop an image here, or choose a file" and "PNG, JPEG, WEBP, SVG · max 10 MB"
And its footer reads "Cancel" only
And no POST has been sent
Scenario: Dropping a file opens Upload with the file
Given the user is on /article/12/edit and ImageUploader is not open
When the user drops a file named "before.png", content type "image/png", size 3.9 MB, onto the editor surface
Then ImageUploader opens on the Upload tab
And GET /v1/media/?hash=<sha256 of the file> is sent, and no request to GET /v1/media/?limit=24 is sent
And when the lookup resolves 200 with no item the crop and resize step shows for "before.png"
And no POST /v1/media/ has been sent
Scenario: Dragging a file over the drop zone shows the dragging-over state
Given ImageUploader is open on the Upload tab in the idle state
When the user drags a file over the drop zone
Then the drop zone reads "Drop to upload"
Rule: Browser checks, nothing is sent
Scenario Outline: Choosing a file the browser can reject sends nothing
Given ImageUploader is open in the idle state
When the user chooses a file named "<filename>", content type "<content_type>", size <size>
Then no hash lookup and no POST /v1/media/ is sent
And the rejected state shows the title "\"<filename>\" can't be used"
And its text reads "<description>"
And its confirm action reads "Choose another file" and its cancel action reads "Cancel"
Examples:
| filename | content_type | size | description |
| plan.pdf | application/pdf | 1.2 MB | Use a PNG, JPEG, WEBP or SVG image, up to 10 MB. |
| disguised.png | application/pdf | 1.2 MB | Use a PNG, JPEG, WEBP or SVG image, up to 10 MB. |
| north-wall.tif | image/png | 14.2 MB | north-wall.tif is 14.2 MB. Images can be up to 10 MB. |
Scenario: "Choose another file" from the rejected state returns to idle
Given ImageUploader is in the rejected state for "plan.pdf"
When the user activates "Choose another file"
Then the idle state is shown again, with the tabs
Rule: Already in your library
Scenario: A file whose content exists shows the duplicate card and sends nothing
Given ImageUploader is open in the idle state
And GET /v1/media/?hash=<sha256 of north-wall.jpg> resolves 200 with the image "north-wall.jpg" (id 1, 4032 × 3024, uploaded 12 Sep 2026 by Marta Alves)
When the user chooses a valid file named "north-wall.jpg" of 3.9 MB
Then the Upload tab shows a card with an info border: a 72 × 54 thumbnail of the existing image, the title "Already in your library" and the text "north-wall.jpg matches an image uploaded on 12 Sep 2026 by Marta Alves."
And the card has the buttons "Use existing" (primary) and "Upload anyway", stacked and full width below md
And no POST /v1/media/ has been sent and the crop step has not opened
Scenario: Several matches name the oldest one
Given the hash lookup resolves 200 with several images
Then the card names the oldest match
Scenario: A match without a known uploader drops the "by" part
Given the matched image's uploaded_by is empty
Then the text reads "north-wall.jpg matches an image uploaded on 12 Sep 2026."
Scenario: "Use existing" goes to the alt text step for the existing image
Given the duplicate card is showing for image id 1
When the user activates "Use existing"
Then the Library tab is selected with "north-wall.jpg" selected, its panel visible with the empty "Alt text (optional)" field, and "Insert image" enabled
And no POST /v1/media/ has been sent
Scenario: "Upload anyway" continues to crop and upload
Given the duplicate card is showing for "north-wall.jpg" (4032 × 3024)
When the user activates "Upload anyway"
Then the crop and resize step opens for that file
And the hash lookup is not repeated
And uploading from that step sends POST /v1/media/ and follows the normal states
Scenario: "Upload anyway" for an SVG uploads immediately
Given the duplicate card is showing for "diagram.svg"
When the user activates "Upload anyway"
Then POST /v1/media/ is sent with that file
Scenario Outline: The duplicate check is skipped when it cannot run
Given ImageUploader is open in the idle state
When the user chooses a valid file and <condition>
Then the flow continues to the crop step (or the upload for an SVG) with no card
Examples:
| condition |
| crypto.subtle is undefined (an insecure context) |
| GET /v1/media/?hash= resolves with a 500 response |
| GET /v1/media/?hash= never reaches the server |
Rule: Uploading
Scenario: A valid upload shows progress and its cancel action reads "Cancel upload"
Given the crop step was confirmed (or an SVG chosen) for "north-wall.jpg", 3.9 MB
Then POST /v1/media/ is sent with the file under the field name "file"
And the uploading state shows "north-wall.jpg 0%" and "Uploading 0.0 of 3.9 MB", and its cancel action reads "Cancel upload"
When the upload reports 2.4 MB sent of 3.9 MB
Then it shows "north-wall.jpg 62%" and "Uploading 2.4 of 3.9 MB"
Scenario: Closing the dialog during an upload cancels it
Given ImageUploader is uploading "north-wall.jpg"
When the user activates "Cancel upload" (or otherwise closes the dialog)
Then the in-flight XMLHttpRequest is aborted and the dialog closes
And the editor's body and its dirty or clean state are unchanged
Scenario: A successful upload inserts the image at the cursor and marks the draft dirty
Given the user is on /article/12/edit in the Saved state and "north-wall.jpg" is uploading
When POST /v1/media/ resolves 201 with the item { id: 13, url: "/static/uploadedImages/13.jpg", filename: "north-wall.jpg" }
Then the uploading state briefly shows "Image added"
And the image "/static/uploadedImages/13.jpg" is inserted at the cursor with alt "" and data-image-id 13
And SaveStatus reads "Unsaved changes" and Save is enabled
And a toast appears: color success, icon i-lucide-circle-check, title "Image added", description "Save to keep it in the article."
And the dialog closes 600 ms after the response
Scenario Outline: A server answer for a file that passed the browser checks
Given ImageUploader is uploading "<file>" of <size>
When POST /v1/media/ resolves <status>
Then the <state> state shows the title "<title>"
And its text reads "<text>"
And its confirm action reads "<confirm>"
And no image is inserted and the editor's body is unchanged
Examples:
| file | size | status | state | title | text | confirm |
| notes.pdf | 210 KB | 415 | rejected | "notes.pdf" can't be used | Use a PNG, JPEG, WEBP or SVG image, up to 10 MB. | Choose another file |
| north-wall.tif | 14.2 MB | 413 | rejected | "north-wall.tif" can't be used | north-wall.tif is 14.2 MB. Images can be up to 10 MB. | Choose another file |
| broken.png | 3.0 MB | 400 | rejected | "broken.png" can't be used | Use a PNG, JPEG, WEBP or SVG image, up to 10 MB. | Choose another file |
| north-wall.jpg | 3.9 MB | 500 | failed | Upload failed | The server didn't accept the file. Your article hasn't changed. | Try again |
| north-wall.jpg | 3.9 MB | 429 | failed | Upload failed | The server didn't accept the file. Your article hasn't changed. | Try again |
| north-wall.jpg | 3.9 MB | none (network) | failed | Upload failed | The server didn't accept the file. Your article hasn't changed. | Try again |
Scenario: "Try again" re-attempts the upload with the same file
Given ImageUploader is in the failed state for "north-wall.jpg" after a 500
When the user activates "Try again"
Then POST /v1/media/ is sent again with that same file and no new hash lookup, and the uploading state shows
Rule: Sessions
Scenario Outline: Session errors are global
When <call> resolves <status>
Then the user is sent where useApi sends a <status> from /article/12/edit, and no local copy shows
Examples:
| call | status |
| POST /v1/media/ (XHR) | 401 |
| POST /v1/media/ (XHR) | 403 |
| GET /v1/media/?hash= | 401 |
+33
View File
@@ -0,0 +1,33 @@
# QA: The editor's Upload tab uploads to the library
## Automated (Vitest + Vue Test Utils, `task test:web`)
Mock `XMLHttpRequest` (a fake with `open`, `setRequestHeader`, `send`, `abort`, firing `upload.progress`, `load`, `error`) for `POST /v1/media/`. Mock useApi's `request` for `GET /v1/media/` (list and `?hash=`), reusing the mock from `api_client_global_error_handling.qa.md`. Stub `hashFile` where a hash is needed, and add one test with `crypto.subtle` deleted. Mount EditorPage inside DashboardShell at `/article/12/edit` with the `editor_core.qa.md` fixture article, GET already resolved 200. Assert URLs by parsing the query, not by string equality.
1. **Toolbar button, empty library** - `GET /v1/media/?limit=24` resolves `{items: [], next_cursor: null, counts: {all: 0, unused: 0, duplicates: 0}}`; click "Image"; assert the dialog "Add an image", both tabs, the Upload tab selected, the drop zone copy, footer "Cancel" only, no XHR.
2. **Drop opens Upload with the file** - dispatch `drop` with `before.png` (image/png, 3.9 MB); assert the Upload tab, a `?hash=` request, no `?limit=24` list request, then the crop step after an empty lookup, and no XHR.
3. **Dragging over shows "Drop to upload"**.
4. **Rejected, Examples-driven** - `plan.pdf`, `disguised.png`, `north-wall.tif`; assert no `?hash=` request and no XHR, plus the exact title, text, confirm and cancel.
5. **"Choose another file" returns to idle**, with the tabs back.
6. **Duplicate card** - the hash lookup resolves one item (id 1, "north-wall.jpg", `created_at` 12 Sep 2026, `uploaded_by` "Marta Alves"); assert the card copy and buttons, no XHR, and no crop step.
7. **Several matches name the oldest**, and **no uploader drops the "by" part**.
8. **"Use existing"** - assert the Library tab is selected, image 1 selected, the alt field empty, "Insert image" enabled, and no XHR.
9. **"Upload anyway"** - assert the crop step opens (raster) with no second `?hash=` request; for an SVG assert the XHR is created at once.
10. **Check skipped** - Examples: `hashFile` resolves null, lookup 500, lookup rejects; assert the crop step opens with no card.
11. **Uploading and progress** - confirm the crop step; assert the XHR is `POST /v1/media/` with field `file`, cancel "Cancel upload", and `loaded: 2.4 * 1024 * 1024, total: 3.9 * 1024 * 1024` gives "north-wall.jpg 62%" and "Uploading 2.4 of 3.9 MB".
12. **Closing during an upload aborts** - `abort` called, dialog closed, body and dirty state unchanged.
13. **201 inserts** - resolve the XHR with the item (id 13, url `/static/uploadedImages/13.jpg`); assert `insertImage` was called with (url, "", 13), SaveStatus "Unsaved changes", Save enabled, the toast (color success, icon `i-lucide-circle-check`, "Image added" / "Save to keep it in the article."), and after 600 ms of fake timers the dialog closes.
14. **Server answers, Examples-driven** - 415, 413, 400 give the rejected copy; 500, 429 and a network `error` give "Upload failed"; assert no `insertImage` call and the body unchanged.
15. **"Try again" resends the same file** with no new `?hash=` request.
16. **Sessions** - Examples from the feature; assert the same redirect `useApi` performs, with no local copy.
## Visual
The Upload tab states are drawn in the `media-picker` group; see `editor_media_picker.qa.md`. The editor-group state 'Upload: choose' awaits the user's editor board update: the user refreshes the editor board themselves, and until then `task visual:check -- editor` is expected to fail on that state. The states "Upload: in progress" and "Upload: rejected" and the crop and resize states are unchanged. `web/visual/states.ts` line 2309 mocks `POST /v1/article/12/image` and must mock `POST /v1/media/` with the item shape, and every editor upload state needs a `GET /v1/media/?limit=24` mock.
## Manual verification
- **Real round trip against `task dev`** with a live SQLite file: a real upload through the SPA (201, 413, 415, 400, 401), then the image shows in `/media`.
- **Real OS drag and drop** of an image onto the editor in a real browser.
- **Real `crypto.subtle`** in a secure context (localhost or HTTPS), including the duplicate card for a file already in the library, and the skipped check on plain HTTP.
- **Keyboard and focus**: the drop zone is reachable by Tab and opens the file chooser with Enter or Space. Focus moves into the dialog and is trapped. Esc during "Upload: in progress" aborts and closes. Tabs are reachable and arrow keys move between them.
+221
View File
@@ -0,0 +1,221 @@
Feature: The editor's Library tab, picking an image from the media library
As a verified RenewCMS owner writing an article
I want to browse my library from the "Add an image" dialog and insert an existing image
with alt text
So that I can reuse an image without uploading it again
Background:
Given this slice is SPA only for this feature: the API from the media library slice is used
unchanged, and the Go change to remove the legacy alias is specified in
features/remove_legacy_article_image_alias.feature
And the screen is docs/design/screens/media-picker.md, drawn by docs/design/source/MediaFrame.dc.html,
inside ImageUploader (UModal "Add an image") on /article/:id/edit
And the dialog has a title "Add an image", an x to close, and two tabs under the title,
"Upload" (icon upload) and "Library" (icon images), 36 px high on desktop and 44 px on
mobile with a 2 px primary underline on the selected one; it is 640 px wide on desktop and
a bottom sheet on mobile
And the footer reads "Cancel", and on the Library tab also a primary "Insert image" that is
disabled until an image is selected
And the Library tab calls GET /v1/media/ through useApi with limit=24, with q only while a
search is set and cursor only when loading more (no filter and no sort parameter), and the
Upload tab is specified in features/editor_image_upload.feature
And the response is { items, next_cursor, counts }, newest first; sizes read "8 KB" and
"3.9 MB", dimensions read "2400 × 1600" (an SVG reads "Vector"), dates are absolute
And the 12-image fixture, ids 1 to 12, is the one in features/media_browse.feature, and the
picker mocks use next_cursor "c24" and counts { all: 48, unused: 2, duplicates: 2 }
And an image is "in this article" when an image node with its id as data-image-id is in
the editor's current content, unsaved insertions included, when the dialog opens;
in the examples below images 1 (north-wall.jpg) and 4 (logo-renew.svg) are in the article
And the search field reads "Search by filename" (32 px high on desktop, 44 px with 16 px
text on mobile), with a search icon and, once it has text, an x that clears it
And the grid has 4 columns on desktop and 3 on mobile with a 12 px gap (8 px between
columns on mobile), square tiles with a 1 px border, and the filename under each tile in
12 px toned text with an ellipsis; it scrolls inside the dialog, 300 px high with nothing
selected, 190 px on desktop and 120 px on mobile with one selected
And every tile is one button whose accessible name reads like the Media page's, for example
"north-wall.jpg, 3.9 MB, used in 2 articles" or "window-frame.jpg, 1.8 MB, unused"
And skeleton tiles show only after 150 ms: 8 on desktop and 9 on mobile for a first load
or a search, one row (4 or 3) at the end for "Load more"
And a 401 or 403 on any of these calls is handled globally by useApi, with no local copy
Rule: Which tab opens
Scenario: The library has images, so Library opens
Given GET /v1/media/?limit=24 resolves 200 with the 12-image fixture
When the user activates the toolbar's "Image" button
Then the Library tab is selected and the footer reads "Cancel" and a disabled "Insert image"
And nothing is drawn in the grid for the first 150 ms, then 8 skeleton tiles show until the response arrives
Scenario: The library is empty, so Upload opens
Given GET /v1/media/?limit=24 resolves 200 with no item and no search set
When the dialog opens
Then the Upload tab is selected, in its idle state
When the user selects the Library tab
Then the empty panel shows
Scenario: A dropped file opens Upload and sends no list request
When the user drops "before.png" onto the editor
Then the Upload tab is selected and no GET /v1/media/?limit=24 is sent
When the user selects the Library tab
Then GET /v1/media/?limit=24 is sent
Rule: Browsing
Scenario: Library, nothing selected
Given the first page resolved with the 12-image fixture
Then the line "Newest first · 48 images" shows under the search field
And 12 tiles show in fixture order, 4 per row on desktop and 3 on mobile, each with its filename
And the tiles of "north-wall.jpg" and "logo-renew.svg" carry a sand "In this article" tag (bottom-left, 18 px high, 11 px text)
And no other tile carries it
And "Load more" shows below the grid, and "Insert image" is disabled
Scenario: A search is active, so the count is not shown
Given the user typed "wall" and the response resolved with 2 items
Then the line reads "Newest first"
Scenario: Load more is hidden on the last page
Given the response has next_cursor null
Then "Load more" is not shown
Scenario Outline: A tile's accessible name
Given the first page resolved with the 12-image fixture
Then the tile for "<filename>" is named "<name>"
Examples:
| filename | name |
| north-wall.jpg | north-wall.jpg, 3.9 MB, used in 2 articles |
| kitchen-before.webp | kitchen-before.webp, 1.1 MB, used in 1 article |
| window-frame.jpg | window-frame.jpg, 1.8 MB, unused |
Rule: Selection
Scenario Outline: A tile is selected by pointer or keyboard
Given the first page resolved with the 12-image fixture
When the user <action> on the tile of "kitchen-after.webp"
Then that tile has a 2 px primary outline (2 px offset) and a 20 px primary check at its top-right
And "Insert image" is enabled
Examples:
| action |
| clicks |
| presses Enter |
| presses Space |
Scenario: The selection panel
Given "kitchen-after.webp" is selected
Then the grid shrinks and a panel shows below it, under a 1 px top border
And the panel has a 56 px thumbnail, the filename "kitchen-after.webp", "2400 × 1600 · 1.2 MB", and a field "Alt text (optional)"
And the field's placeholder reads "e.g. North wall of the kitchen before plastering"
And its help reads "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."
And "Load more" is hidden while an image is selected
Scenario: Selection is single
Given "kitchen-after.webp" is selected and the alt text reads "A kitchen"
When the user selects "window-frame.jpg"
Then only "window-frame.jpg" is selected and the alt text field is empty
Scenario: Activating the selected tile again keeps it selected
Given "kitchen-after.webp" is selected
When the user activates its tile
Then it stays selected
Scenario: An SVG's panel reads "Vector"
When the user selects "logo-renew.svg"
Then the panel reads "Vector · 8 KB"
Scenario: An image already in the article can be selected and inserted again
When the user selects "north-wall.jpg", which carries "In this article"
Then "Insert image" is enabled
Rule: Insert
Scenario: Insert with alt text
Given the user is on /article/12/edit in the Saved state with "kitchen-after.webp" (id 2, url "/static/uploadedImages/2.webp") selected
And the alt text reads "A kitchen with new oak worktops and white tiles"
When the user activates "Insert image"
Then insertImage is called with "/static/uploadedImages/2.webp", "A kitchen with new oak worktops and white tiles" and image id 2
And the image is in the editor's content at the cursor, with data-image-id 2
And SaveStatus reads "Unsaved changes" and Save is enabled
And a toast appears: color success, icon i-lucide-circle-check, title "Image added", description "Save to keep it in the article."
And the dialog closes at once
And no POST, PATCH or DELETE has been sent
Scenario: Empty alt text inserts a decorative image
Given "kitchen-after.webp" is selected and the alt text is empty
When the user activates "Insert image"
Then insertImage is called with alt ""
Scenario: Alt text lives only in the article
Given "kitchen-after.webp" is selected with alt text "A kitchen"
When the user activates "Insert image"
Then no request carries the alt text and the library item is unchanged
Scenario Outline: Leaving without inserting changes nothing
Given "kitchen-after.webp" is selected with alt text "A kitchen"
When the user <action>
Then the dialog closes, the editor's content and dirty state are unchanged, and no toast shows
Examples:
| action |
| activates "Cancel" |
| activates the x |
| presses Escape |
Rule: Search
Scenario: Typing searches after a debounce
Given the Library tab shows the 12-image fixture
When the user types "wall"
Then after a 120 ms debounce GET /v1/media/ is sent with q=wall and limit=24 and no cursor
And skeleton tiles show after 150 ms, and any selection is cleared
Scenario: The x in the field clears the search
Given the search field holds "wall" with results shown
When the user activates the x in the field
Then the field is empty and GET /v1/media/ is sent with limit=24 and no q
Scenario: No results
Given GET /v1/media/?q=wall&limit=24 resolves 200 with no item
Then the search icon shows with the title `No images match "wall"`, the text "Check the spelling, or search for a shorter part of the filename." and a "Clear search" button
And the search field still shows "wall" above it, and "Insert image" is disabled
When the user activates "Clear search"
Then the field is emptied and the list is requested again with no q
Rule: Load more
Scenario: Loading more shows progress and appends
Given the first page resolved with 12 images, next_cursor "c24"
When the user activates "Load more"
Then GET /v1/media/ is sent with limit=24 and cursor=c24
And the button reads "Loading…" with a loader-circle and is disabled, and one row of skeleton tiles shows at the end
And focus stays on the button
When the request resolves 200 with 12 more images
Then the new tiles are appended after the first 12, and focus moves to the first new tile
Scenario: The cursor and the search combine
Given the search "wall" is active and the page has next_cursor "c24"
When the user activates "Load more"
Then GET /v1/media/ is sent with q=wall, limit=24 and cursor=c24
Rule: Empty and failed
Scenario: Empty library
Given the Library tab is selected and GET /v1/media/?limit=24 resolved with no item
Then the images icon shows with "Your library is empty", "Images you upload appear here, ready to use in any article." and a primary "Upload an image"
And "Insert image" is disabled
When the user activates "Upload an image"
Then the Upload tab is selected
Scenario Outline: The library fails to load
Given GET /v1/media/ <failure>
When the Library tab loads
Then an error alert shows in the dialog: icon circle-x, title "Couldn't load your library", text "Check your connection and try again.", and a "Try again" button
And "Insert image" is disabled
When the user activates "Try again"
Then the same request is sent again with a skeleton, and on 200 the tiles replace the alert
Examples:
| failure |
| resolves with a 500 response |
| never reaches the server |
+54
View File
@@ -0,0 +1,54 @@
# QA: The editor's Library tab
## Automated (Vitest + Vue Test Utils, `task test:web`)
Mock `request` for `GET /v1/media/` by parsed query. Use the 12-image fixture from `media_browse.feature` as `items`, with `next_cursor: "c24"` and `counts: {all: 48, unused: 2, duplicates: 2}`. Mount EditorPage at `/article/12/edit` with a body containing `<img data-image-id="1">` and `<img data-image-id="4">`. Use fake timers for the 150 ms and 120 ms steps.
1. **Opens on Library with images** - first response has items; assert Library selected and skeleton tiles only after 150 ms.
2. **Opens on Upload when empty** - empty first response; assert Upload selected; then click Library and assert the empty panel.
3. **Drop sends no list request** - drop a file; assert no `?limit=24` request until Library is clicked.
4. **Nothing selected** - assert the line, 12 tiles in order, the "In this article" tag on exactly ids 1 and 4, "Load more", "Insert image" disabled.
5. **Active search hides the count** - the line reads "Newest first".
6. **Last page** - `next_cursor: null` hides "Load more".
7. **Accessible names** - the three Examples.
8. **Selection** - click, Enter and Space each select; check, outline, "Insert image" enabled.
9. **Panel copy** - kitchen-after.webp panel, placeholder and help text exact; "Load more" hidden; SVG reads "Vector · 8 KB".
10. **Single selection resets alt**; reactivating keeps it selected.
11. **Insert** - alt "A kitchen with new oak worktops and white tiles" gives `insertImage("/static/uploadedImages/2.webp", alt, 2)`, SaveStatus "Unsaved changes", the toast, the dialog closed, no non-GET request. Empty alt gives `""`.
12. **Cancel, x and Escape** change nothing.
13. **Search** - type "wall"; at 119 ms no request, at 120 ms the request has `q=wall&limit=24` and no cursor; the selection is cleared. The field's x and "Clear search" send a request with no `q`.
14. **No results** and **Empty** copy; "Upload an image" switches to the Upload tab.
15. **Load more** - request has `cursor=c24`; button "Loading…" and disabled; skeleton row of 4 (3 below md); focus on the button, then on the first new tile after resolve; combined `q` and `cursor`.
16. **Failed to load, Examples 500 and network** - alert copy; "Try again" repeats the request; success replaces the alert.
## Visual: `task visual:check -- media-picker`
Add a setup in `web/visual/states.ts` for each of the 13 states in `docs/design/screens/media-picker.md`, from the board's script (`RenewCMS Screens Back-office.dc.html` lines 239 to 253). Every capture must be within 10 % at 1440×900 and 390×844, light and dark. The sample data to reuse:
- Library mock: the 12-image fixture, `counts.all` 48, `next_cursor` non-null; images 1 and 4 in the article. The dialog is opened on the editor "How we price a bathroom renovation".
- "Upload tab": Upload selected, idle drop zone.
- "Upload tab: already in your library": a chosen file named `north-wall.jpg`; the hash lookup returns id 1 (12 Sep 2026, Marta Alves); the thumbnail is 72 × 54.
- "Library: loading": skeleton tiles.
- "Library: nothing selected": the 12 tiles, tags on ids 1 and 4, "Load more".
- "Library: selected": id 2 (kitchen-after.webp, 2400 × 1600 · 1.2 MB), empty alt.
- "Library: alt text entered": id 2 with alt "A kitchen with new oak worktops and white tiles".
- "Library: loading more": 12 tiles plus one skeleton row, button "Loading…".
- "Library: empty": a mock with zero items. "Library: no results": search "wall" and zero items.
- "Library: failed to load": a 500.
- "Inserted": the editor with an image (id 1 as the board draws it) and the toast "Image added" / "Save to keep it in the article.".
- "Remove image: confirm": the confirm over the editor, image id 1 (north-wall.jpg, 3.9 MB). See `editor_image_removal.qa.md`.
- "Removed": the editor without the image and the toast "Image removed" / "It's still in your library.".
Clock-sensitive: none. Dates are absolute. Nothing is skipped.
Layout facts the mocks must hit (from the frame): the dialog is 640 px at 40 px from the top; the tabs row has a 20 px gap and 24 px side padding; the body has 16 px top padding and 24 px side padding; the search field is 32 px (44 px on mobile); the grid gap is 12 px (8 px between columns on mobile).
Manual checks the screenshots can't cover:
- [ ] Focus order is tabs, search, tiles, "Load more", footer. Enter and Space select a tile. Focus returns to the toolbar's image button when the dialog closes.
- [ ] Hover on a tile and on "Load more", and the focus ring.
- [ ] Motion: the dialog follows the standard 240 ms timing.
- [ ] A real library of more than 24 images through `task dev`: "Load more" and the cursor.
- [ ] A screen reader reads the tile names and the alt text help.
## Manual verification
Real `GET /v1/media/` with `q` and `cursor` against `task dev` with a live SQLite file.
+8 -7
View File
@@ -9,9 +9,10 @@ Feature: A logged-in user fetches their own public profile without triggering th
without being throttled like a login attempt without being throttled like a login attempt
Background: Background:
Given the existing PublicUser struct and newPublicUser(u user.User) converter in Given the public user struct and its converter, shared by the auth and user handlers from a
api/handlers/auth/verificationHandler.go, exactly the JSON shape POST /v1/auth/verify already package under api/pkg (features/user_display_name.feature), exactly the JSON shape
returns: id, username, email, is_verified, created_at, updated_at POST /v1/auth/verify returns: id, username, email, is_verified, created_at, updated_at,
display_name and role
And this slice adds GET /v1/auth/me, handled by a new MeHandler (api/handlers/auth/meHandler.go) And this slice adds GET /v1/auth/me, handled by a new MeHandler (api/handlers/auth/meHandler.go)
built with NewMeHandler(container.GetUserUseCase), the same GetUserUseCase every other built with NewMeHandler(container.GetUserUseCase), the same GetUserUseCase every other
protected handler already gets from api/dependecyInjection.go; no new use case or domain protected handler already gets from api/dependecyInjection.go; no new use case or domain
@@ -42,23 +43,23 @@ Feature: A logged-in user fetches their own public profile without triggering th
Scenario: A verified user fetches their own profile Scenario: A verified user fetches their own profile
Given a user repository containing user id 7, username "alice", email "alice@example.com", Given a user repository containing user id 7, username "alice", email "alice@example.com",
is_verified true, TokenVersion 0 is_verified true, role "owner", TokenVersion 0
And a valid jwt cookie for user id 7 encoding token_version 0 And a valid jwt cookie for user id 7 encoding token_version 0
When the client sends GET /v1/auth/me with that cookie When the client sends GET /v1/auth/me with that cookie
Then the response status is 200 Then the response status is 200
And the response header Cache-Control is "no-store" And the response header Cache-Control is "no-store"
And the response body is the user as JSON with id 7, username "alice", email And the response body is the user as JSON with id 7, username "alice", email
"alice@example.com", is_verified true "alice@example.com", is_verified true, role "owner"
Scenario: An unverified user still fetches their own profile, with is_verified false, not a 403 Scenario: An unverified user still fetches their own profile, with is_verified false, not a 403
Given a user repository containing user id 8, username "bob", email "bob@example.com", Given a user repository containing user id 8, username "bob", email "bob@example.com",
is_verified false, TokenVersion 0 is_verified false, role "owner", TokenVersion 0
And a valid jwt cookie for user id 8 encoding token_version 0 And a valid jwt cookie for user id 8 encoding token_version 0
When the client sends GET /v1/auth/me with that cookie When the client sends GET /v1/auth/me with that cookie
Then the response status is 200 Then the response status is 200
And the response header Cache-Control is "no-store" And the response header Cache-Control is "no-store"
And the response body is the user as JSON with id 8, username "bob", email "bob@example.com", And the response body is the user as JSON with id 8, username "bob", email "bob@example.com",
is_verified false is_verified false, role "owner"
Scenario: No jwt cookie at all is refused Scenario: No jwt cookie at all is refused
Given a user repository containing user id 7, username "alice", is_verified true, TokenVersion 0 Given a user repository containing user id 7, username "alice", is_verified true, TokenVersion 0
+6 -6
View File
@@ -37,13 +37,13 @@ wiring pattern in `test/stale_token_invalidation_http_test.go`.
## HTTP-level checks ## HTTP-level checks
8. Seed `mockUserRepo` with user id 7, username "alice", email "alice@example.com", 8. Seed `mockUserRepo` with user id 7, username "alice", email "alice@example.com",
`IsVerified: true`, `TokenVersion: 0`. Mint a cookie for user 7 with `token_version: 0`. `IsVerified: true`, `Role: owner`, `TokenVersion: 0`. Mint a cookie for user 7 with
`GET /v1/auth/me` → assert status `200`, `Cache-Control` header equals `"no-store"`, and the `token_version: 0`. `GET /v1/auth/me` → assert status `200`, `Cache-Control` header equals
decoded JSON body has `id: 7`, `username: "alice"`, `email: "alice@example.com"`, `"no-store"`, and the decoded JSON body has `id: 7`, `username: "alice"`,
`is_verified: true`. `email: "alice@example.com"`, `is_verified: true`, `role: "owner"`.
9. Seed user id 8, username "bob", email "bob@example.com", `IsVerified: false`, 9. Seed user id 8, username "bob", email "bob@example.com", `IsVerified: false`, `Role: owner`,
`TokenVersion: 0`. Mint a matching cookie. `GET /v1/auth/me` → assert status `200` (not 403), `TokenVersion: 0`. Mint a matching cookie. `GET /v1/auth/me` → assert status `200` (not 403),
`Cache-Control: no-store`, and `is_verified: false` in the body. `Cache-Control: no-store`, `is_verified: false` and `role: "owner"` in the body.
10. No `jwt` cookie at all against the router from step 6 → assert status `401` (produced by 10. No `jwt` cookie at all against the router from step 6 → assert status `401` (produced by
`jwtauth.Authenticator` itself; don't assert an exact body for this case, same rationale as `jwtauth.Authenticator` itself; don't assert an exact body for this case, same rationale as
`features/account_verification.qa.md` step 15). `features/account_verification.qa.md` step 15).
+125
View File
@@ -0,0 +1,125 @@
Feature: Home screen
As a logged-in RenewCMS owner
I want /home to summarize how many articles I have, how many are online or drafts, and my five
most recently updated articles, all from the single GET /v1/article/ call the route already
makes
So that I land somewhere useful after logging in, instead of an empty dashboard or a screen that
silently fails
Background:
Given /home is a verified route (meta.auth "verified") rendered as HomePage inside
DashboardShell, per docs/design/routes.md
And HomePage calls GET /v1/article/ once per navigation; there is no separate stats endpoint,
so the three stat tiles and the recent list are both derived from that one response
And the PageHeader shows breadcrumb "Home" (mobile title "Home") and a primary action "New
article" opening NewArticleModal
And a "Connect your website" card is always rendered on the page, in every state (Loading,
Default, Empty and Error alike): icon plug, title "Connect your website", text "Your site
reads published articles from RenewCMS. Share this guide with whoever builds it.", and a
link "Open the guide" navigating to /integration
And a greeting reading "{greeting}, {name}" sits above the subtitle in every state
(Loading, Default, Empty and Error alike); name is the session's display name when it is
not empty and the session's username otherwise; it is computed from that name and
the device's local hour via Date.getHours(), needs no request of its own since the session
is already resolved by the app-boot flow before HomePage ever renders, and so never has its
own loading or error state
And hours 0 through 11 give the greeting "Good morning", hours 12 through 17 give "Good
afternoon", and hours 18 through 23 give "Good evening"
And once the list resolves with at least one article, the subtitle reads "Here's where things
stand on your site.", three stat tiles show the total article count labelled "articles", the
online count labelled "online" and the draft count labelled "drafts", and a recent list shows
the 5 most recently updated articles, each with its title, an ArticleStatusBadge (online or
draft) and its updated date, linking to /article/:id/edit
And while the list request is in flight, skeleton placeholders replace the stat tiles and the
recent list rows, but only after 150 ms, so a fast response never flashes a skeleton
And when the list resolves with zero articles, the subtitle reads "Welcome to RenewCMS.", and
the stat tiles and recent list are replaced by an empty state: icon file-text, title "Write
your first article", text "It starts as a draft, so nothing appears on your site until you
publish it.", and a single action "New article" that opens NewArticleModal
And when the list request fails with a 500 or a network error, the breadcrumb, greeting and
subtitle stay visible, the subtitle stays "Here's where things stand on your site.", and the
stat tiles and recent list are replaced by an inline role="alert" banner: icon circle-x,
title "Couldn't load your articles", text "Check your connection and try again.", and a
single action "Try again"
Scenario: Skeletons appear only after 150 ms, never for a fast response
Given the user navigates to /home for the first time in this session
When GET /v1/article/ has not resolved 150 ms after the navigation
Then skeleton placeholders replace the three stat tiles and the five recent-list rows
And the recent list container is aria-busy="true"
When GET /v1/article/ then resolves 200 with a non-empty list of articles
Then the skeletons are replaced by the Default state's stat tiles and recent list
Given a second, separate navigation to /home
When GET /v1/article/ resolves in under 150 ms with a non-empty list of articles
Then no skeleton is ever shown, and the Default state's content renders directly
Scenario: Default — the list loaded with a mix of online and draft articles
Given GET /v1/article/ resolves 200 with 6 articles, 4 online and 2 drafts, most recently
updated first: "How we price a bathroom renovation" (online), "Winter checklist for timber
windows" (online), "Choosing tiles for a small bathroom" (draft), "A guide to underfloor
heating" (online), "When to reseal a stone worktop" (draft), and "Small bathroom lighting
ideas" (online, least recently updated)
When the user navigates to /home
Then the subtitle reads "Here's where things stand on your site."
And the stat tiles read "6" "articles", "4" "online" and "2" "drafts"
And the recent list shows exactly the first 5 articles above, in that order, each with its
ArticleStatusBadge and updated date, and each row links to its /article/:id/edit
And "Small bathroom lighting ideas" does not appear in the recent list
And the "Connect your website" card's "Open the guide" link navigates to /integration, and
the header's "New article" action opens NewArticleModal
Scenario: Empty, first run — zero articles
Given GET /v1/article/ resolves 200 with zero articles
When the user navigates to /home
Then the subtitle reads "Welcome to RenewCMS."
And no stat tiles are shown
And an empty state is shown in place of the recent list: icon file-text, title "Write your
first article", text "It starts as a draft, so nothing appears on your site until you
publish it.", and a single action "New article"
When the user activates "New article"
Then NewArticleModal opens
Scenario Outline: Error — a 500 or a network failure shows the same inline alert
Given GET /v1/article/ <failure>
When the user navigates to /home
Then the breadcrumb, greeting and subtitle remain visible, and the subtitle stays "Here's
where things stand on your site."
And no stat tiles or recent list are shown
And an inline alert with role="alert" is shown in their place: icon circle-x, title
"Couldn't load your articles", text "Check your connection and try again.", and a single
action "Try again"
Examples:
| failure |
| fails with a 500 response |
| never reaches the server |
Scenario: Retry re-issues the request and recovers into the Default state
Given the user is on /home in the Error state, because GET /v1/article/ failed
When the user activates "Try again"
Then GET /v1/article/ is called again
When it resolves 200 with 6 articles, 4 online and 2 drafts
Then the Alert is replaced by the stat tiles reading "6" "articles", "4" "online", "2" "drafts",
and the recent list
Scenario: The list is fetched exactly once per navigation
Given the user navigates to /home
Then GET /v1/article/ is called exactly once
And both the stat tiles and the recent list are derived from that single response, with no
second request made for either
Scenario Outline: The greeting matches the hour of day
Given the session's username is "marta" and it has no display name
And the device's local hour is <hour>
When the user views /home
Then the greeting above the subtitle reads "<greeting>, marta"
Examples:
| hour | greeting |
| 0 | Good morning |
| 11 | Good morning |
| 12 | Good afternoon |
| 17 | Good afternoon |
| 18 | Good evening |
| 23 | Good evening |
+101
View File
@@ -0,0 +1,101 @@
# QA: Home screen
## Implementation note for coder (informational, not a QA assertion)
The greeting requires `useApi.getMe()` and the `Session` type/store
(`web/src/composables/useApi.ts`, `web/src/stores/session.ts`) to also expose `username`, which
`GET /v1/auth/me` already returns in its JSON body. Today `getMe()` only extracts `is_verified` and
discards the rest, and `Session` is just `{ verified: boolean }`. Widen `MeResult` and `Session` to
carry `username: string` as well; this is a same-layer frontend response-type widening (the wire
contract doesn't change), not a backend change.
## Automated (Vitest + Vue Test Utils, `task test:web`)
Mock `useApi`'s `GET /v1/article/` call per case; no real backend, no httptest server. Mount
HomePage inside DashboardShell with a resolved session (username "marta") and a test router at
/home.
1. **Skeleton only after 150 ms** — mock `GET /v1/article/` with an unresolved promise; assert no
skeleton is present before 150 ms elapse (use fake timers); advance past 150 ms; assert skeleton
placeholders replace the stat tiles and the 5 recent-list rows, and the list container has
aria-busy="true"; resolve the promise with 200 and a non-empty list; assert the skeletons are
gone and the Default content is shown. Separately, mock a promise that resolves in under 150 ms;
assert no skeleton ever renders.
2. **Default state** — mock `GET /v1/article/` resolving 200 with the 6-article fixture (4 online,
2 drafts, ordered most-recently-updated first as in the feature); assert subtitle "Here's where
things stand on your site."; assert stat tiles "6" "articles", "4" "online", "2" "drafts"; assert
the recent list shows exactly the first 5 articles in order, each with its ArticleStatusBadge and
updated date, each row linking to /article/:id/edit; assert the 6th (least recently updated)
article is absent from the recent list; assert the PageHeader's "New article" action opens
NewArticleModal.
3. **Empty, first run** — mock `GET /v1/article/` resolving 200 with `[]`; assert subtitle "Welcome
to RenewCMS."; assert no stat tiles render; assert an empty state renders in place of the recent
list with icon file-text, title "Write your first article", text "It starts as a draft, so
nothing appears on your site until you publish it.", and action "New article"; click it; assert
NewArticleModal opens.
4. **Error state** — Examples-driven: (a) `GET /v1/article/` resolves 500, (b) it rejects with a
network error. In each: assert the breadcrumb, greeting and subtitle remain visible and the
subtitle stays "Here's where things stand on your site."; assert no stat tiles or recent list
render; assert an inline alert with role="alert" renders in their place, with icon circle-x,
title "Couldn't load your articles", text "Check your connection and try again.", and a single
action "Try again"; assert the alert text is identical between the 500 case and the network-
failure case — there is no separate wording per cause.
5. **Retry recovers into Default** — start from the Error state (mocked 500); click "Try again"; assert
`GET /v1/article/` is called a second time; resolve it 200 with the 6-article fixture; assert the
Alert is replaced by the stat tiles "6"/"4"/"2" and the recent list.
6. **Single request per navigation** — mock `GET /v1/article/` resolving 200 with the 6-article
fixture; mount /home; assert the mock was called exactly once, and both the stat tiles and the
recent list read from that one resolved value (no second call fires for either).
7. **Greeting matches the hour of day, at every state, for the session username** — stub the clock
(e.g. `vi.setSystemTime` or a mocked `Date.now`/`Date.prototype.getHours`) to each boundary hour
in turn (0, 11, 12, 17, 18, 23) and mount with session username "marta"; assert the greeting
above the subtitle reads exactly "Good morning, marta" for hours 0 and 11, "Good afternoon,
marta" for hours 12 and 17, and "Good evening, marta" for hours 18 and 23. Then, fixing the hour
at 9 ("Good morning, marta"), assert the same exact greeting text is shown above the subtitle in
all four states: while `GET /v1/article/` is unresolved past 150 ms (Loading), once it resolves
with the 6-article fixture (Default), once it resolves with `[]` (Empty), and once it rejects
with a 500 (Error).
8. **"Connect your website" card renders in every state** — assert the static card (icon plug,
title "Connect your website", text "Your site reads published articles from RenewCMS. Share
this guide with whoever builds it.", link "Open the guide" navigating to /integration) is
present and identical while `GET /v1/article/` is unresolved past 150 ms (Loading), once it
resolves with the 6-article fixture (Default), once it resolves with `[]` (Empty), and once it
rejects with a 500 (Error). The card is not part of the PageHeader's actions.
## Visual (manual verification — desktop and mobile, light and dark)
Reference: `docs/design/screens/home.md` and `docs/design/source/RenewCMS Screens Back-office.dc.html`,
group "Home". Run `task visual:check -- home` for each state and compare against the board frame.
- [ ] Loading state: skeleton stat tiles and 5 skeleton recent rows, shaped like the real layout,
matching the board.
- [ ] Default state: stat tiles, recent list with ArticleStatusBadge per row, PageHeader primary
action "New article", breadcrumb "Home", and the "Connect your website" card below — matches
the board exactly at desktop and mobile.
- [ ] Empty, first run state: the empty state replaces the stats and recent list, matching the
board's icon tile, title "Write your first article", text, and single "New article" action.
- [ ] Error state: the inline alert's icon (circle-x), title "Couldn't load your articles", text
"Check your connection and try again.", and "Try again" action match the board; the
breadcrumb, greeting and subtitle stay visible above it.
- [ ] "Connect your website" card: icon plug, title, text and "Open the guide" link match the
board, and the card renders identically in every state (Loading, Default, Empty, Error).
- [ ] Greeting placement: the greeting sits above the subtitle in the PageHeader area (not the note
board's fixture text, since the greeting is new content — position and type scale should read
as a lightweight line above the description, not competing with the h1).
- [ ] Keyboard/focus: Tab order reaches "New article" in the header, then the "Connect your
website" card's "Open the guide" link, before the recent list; the Error state's "Try again"
button is reachable and, on activation, focus stays sensible (not lost) while the request
re-runs; the recent list's rows are reachable and each activates its /article/:id/edit link
with Enter.
- [ ] Motion: the skeleton pulse runs at 1.6 s and stops under reduced motion, per the Skeleton
component spec.
## Manual verification
- **Real GET /v1/article/ against a running server** — Vitest only mocks `useApi`; confirm the real
200/500 round-trip and the real article ordering (by updated_at) against `task dev` with a live
SQLite file, since these automated tests never exercise the actual Go handler or the
`ListArticles` use case.
- **Real session username on a live app-boot** — confirm `GET /v1/auth/me`'s `username` field flows
through the real session store into the greeting, since Vitest only ever supplies a mocked
session.
+2 -2
View File
@@ -17,8 +17,8 @@ Feature: Allowed image types and the size limit are a domain rule
the matching sentinel and calling the repository not at all when either check fails the matching sentinel and calling the repository not at all when either check fails
And ImageRepository.Create no longer rejects an unrecognized content type itself; it And ImageRepository.Create no longer rejects an unrecognized content type itself; it
only maps an already-allowed content type to a file extension only maps an already-allowed content type to a file extension
And no image HTTP endpoint is mounted in api/router.go as of this slice, so this And the HTTP mapping of these sentinels is 413, 415 and 400, specified in
behavior is observable only through CreateImageUseCase features/media_library.feature
Scenario Outline: CreateImage accepts every allowed content type within the size limit Scenario Outline: CreateImage accepts every allowed content type within the size limit
Given an empty image repository fake Given an empty image repository fake
+63
View File
@@ -0,0 +1,63 @@
Feature: Integration screen
As a verified RenewCMS owner
I want /integration to show my site's base API URL and ready-to-use endpoint examples
So that I, or the developer who builds my public site, can wire it up without reading the
source
Background:
Given /integration is a verified route (meta.auth "verified") rendered as IntegrationPage
inside DashboardShell, per docs/design/routes.md
And the screen makes no /v1 calls; api: none (static)
And the PageHeader shows title "Connect your website", description "A guide for the developer
who builds your public site.", breadcrumb "Integration" (mobile title "Integration"), and no
actions
And an introductory paragraph reads "RenewCMS is headless: it stores and publishes your
articles but doesn't show them to visitors. Your website fetches published articles from the
two addresses below and displays them in its own design."
And a "Base URL" row shows window.location.origin in a monospace box, with a "Copy" button
(icon copy) beside it
And two EndpointCard entries follow, in this order:
| method | path | description |
| GET | /v1/article/ | Lists every online article. |
| GET | /v1/article/{id} | Returns one online article. Drafts and unknown ids both return 404. |
And each EndpointCard's fetch example uses the current origin as the base of its URL:
| path | fetch example |
| /v1/article/ | const res = await fetch('{origin}/v1/article/')\nconst articles = await res.json() |
| /v1/article/{id} | const res = await fetch('{origin}/v1/article/12')\nif (res.status === 404) return notFound()\nconst article = await res.json() |
And each EndpointCard has fetch, curl and Response tabs, with fetch active by default, and its
CodeBlock is labelled "JavaScript" with its own ghost "Copy" button
And the curl tab's content is a plain curl command built from the current origin (e.g.
"curl {origin}/v1/article/" and "curl {origin}/v1/article/12"), and the Response tab's
content is a JSON sample built from the real domain Article fields; neither tab is active by
default, and neither is visually checked, since the fetch tab is the one shown in the board
And three info notes follow the endpoint cards, in this order:
- "Anonymous callers only ever get online articles. Drafts stay private until you publish
them."
- "Images in body use paths like /static/uploadedImages/<uuid>.png. Prefix them with the
base URL before rendering."
- "Browsers can only call the API from origins listed in the server's CORS setting. Ask
whoever runs the server to add your site's address."
Scenario: Default — the page loads with the app's own origin
Given the app is served from origin "{origin}"
When the user navigates to /integration
Then the Base URL row shows exactly "{origin}"
And the Base URL "Copy" button reads "Copy", not "Copied"
And both EndpointCards' fetch examples use "{origin}" as the base of their URL
Scenario: Copied — the Base URL copy button
Given the user is on /integration, served from origin "{origin}"
When the user activates the Base URL row's "Copy" button
Then "{origin}" is written to the clipboard
And the button's icon changes to check and its text changes to "Copied"
And the change is announced to assistive technology
When 2 seconds elapse without a further click
Then the button reverts to icon copy and text "Copy"
Scenario: Each EndpointCard's own Copy button is independent of the Base URL's
Given the user is on /integration
When the user activates the "/v1/article/" EndpointCard's "JavaScript" code block's "Copy"
button
Then that card's own code is written to the clipboard, and only that button reads "Copied"
And the Base URL row's "Copy" button and the other EndpointCard's "Copy" button are unaffected
+66
View File
@@ -0,0 +1,66 @@
# QA: Integration screen
## Automated (Vitest + Vue Test Utils, `task test:web`)
Mount IntegrationPage inside DashboardShell with a resolved verified session and a test router at
/integration. Stub `window.location.origin` (or the equivalent composable/helper the coder uses to
read it) to a fixed value for the test, and stub `navigator.clipboard.writeText` per case. No
`/v1` mocks are needed; the screen makes no calls.
1. **Default** — mount at /integration with origin stubbed to a fixed value (e.g.
`https://cms.renew.example`, matching the design board's sample so the assertions read the same
as the visual reference); assert breadcrumb "Integration"; assert the PageHeader title
"Connect your website" and description "A guide for the developer who builds your public
site."; assert the intro paragraph text; assert the Base URL row shows exactly the stubbed
origin; assert the Base URL "Copy" button reads "Copy"; assert both EndpointCards render in
order (GET /v1/article/, GET /v1/article/{id}) with their descriptions and their fetch examples
containing the stubbed origin; assert the fetch tab is active by default on both cards; assert
the three info notes render in order.
2. **Copied** — from Default, use fake timers; click the Base URL row's "Copy" button; assert
`navigator.clipboard.writeText` was called with the stubbed origin; assert the button's icon is
check and its text is "Copied"; assert the change is exposed to assistive technology (e.g. an
aria-live region or a status role holds "Copied"); advance the fake timer by 2 s; assert the
button reverts to icon copy and text "Copy".
3. **EndpointCard's own Copy button is independent** — from Default, click the "/v1/article/"
card's "JavaScript" CodeBlock's "Copy" button; assert `navigator.clipboard.writeText` was called
with that card's exact code string; assert only that button reads "Copied"; assert the Base URL
button still reads "Copy" and the other card's Copy button still reads "Copy". This behavior is
Vitest-only; it has no visual-check state of its own (see Visual below).
4. **curl and Response tabs render, unchecked visually** — from Default, switch the "/v1/article/"
card to its curl tab; assert its content is a plain curl command built from the stubbed origin
(e.g. "curl https://cms.renew.example/v1/article/"); switch to its Response tab; assert its
content is a JSON sample built from the real domain Article fields. Neither tab's content is
asserted pixel-for-pixel anywhere, since the design board only ever shows the fetch tab active.
## Visual (`task visual:check -- integration`, desktop and mobile, light and dark)
Reference: `docs/design/screens/integration.md` and
`docs/design/source/RenewCMS Screens Back-office.dc.html`, group "Integration"; layout detail from
`docs/design/source/AppFrame.dc.html`'s `isInteg` block.
The visual-check setup for this screen serves the SPA under `https://cms.renew.example` via
Playwright request routing, so the real `window.location.origin` the running app reads matches the
board's sample text exactly; no production test hook or origin stub is needed in app code.
- [ ] Default state: PageHeader ("Connect your website" / description), intro paragraph, Base URL
row with monospace text and a "Copy" button (icon copy), two EndpointCards in order with
their GET badge, path, description, fetch/curl/Response tabs (fetch active), JavaScript
CodeBlock and its own "Copy" button, and the three info notes below — matches the board
exactly at desktop and mobile, light and dark. Sample data for the mocked run: origin
`https://cms.renew.example`, served as above.
- [ ] Copied state: the Base URL button shows the check icon and "Copied" text, in the success
color, matching the board's `copied: true` frame. This state is timer-driven, not
date-driven, so it is not clock-sensitive and gets a real visual check, not a skip.
- [ ] Keyboard/focus (manual, not a screenshot check): Tab order reaches the Base URL "Copy"
button, then each EndpointCard's tab strip (fetch/curl/Response, reachable and operable with
arrow keys per UTabs), then that card's own CodeBlock "Copy" button, then the pre's
`tabindex="0"` for scrolling; Enter/Space activates each Copy button.
- [ ] Hover (manual): ghost Copy buttons show a hover state consistent with other ghost buttons
elsewhere in the app (UserMenu, ArticleTable row menu).
## Manual verification
- Confirm the real running app's `window.location.origin` (e.g. `https://your-domain.example` in
production, or `http://localhost:8080` under `task dev`) renders correctly in the Base URL row
and in both fetch examples, since Vitest only ever exercises a stubbed origin, and
`visual:check` only ever exercises the routed `https://cms.renew.example` origin.
+189
View File
@@ -0,0 +1,189 @@
Feature: A verified user can invite another person by email, and the users list shows users and open invites
As a member of the shared RenewCMS workspace
I want to invite someone by email and see who has an account or a pending invite
So that they can later create their own account with exactly the same access, while
registration stays closed to everyone who was not invited
Background:
Given the workspace is shared: every verified user sees the same articles and the same list,
roles are owner and admin (features/user_roles.feature), and there is no way to remove a user
And POST /v1/user/invite and GET /v1/user/ are mounted in NewUserRouter, inside the group that
requires a valid jwt cookie, a current token_version and a verified user
And POST /v1/user/invite additionally requires the owner role (403
apperr.OwnerRequiredErrorMessage for an admin); GET /v1/user/ is open to every verified user
And wherever a scenario has verified user id 7 post an invite, user 7 is the owner
And an invite has an id, an email stored in lower case, a hashed code, an expires_at equal to
its creation time plus 3 days, an invited_by user id, a nullable accepted_at and a created_at
And the raw invite code is a uuid, hashed with the same hash.Hasher used for verification codes,
and only the hash is stored
And an invite's status is derived and never stored: pending when accepted_at is empty and
expires_at is in the future, expired when accepted_at is empty and expires_at is in the past,
accepted when accepted_at is set
And the users list item shape is: id, kind ("user" or "invite"), status, created_at, plus
username, display_name, email and role for a user, plus email for an invite; neither the
code, its hash, invited_by nor password fields ever appear
And error responses are plain text from http.Error, success responses are JSON
And the invite email uses the template "invitation" with data Host (the configured PublicURL),
VerificationCode (the raw code), Email (the invited address) and InvitedBy (the inviter's
display name, or their username when the display name is empty)
And the email subject is "<InvitedBy> invited you to RenewCMS"
And the link in the email is <Host>/invite/accept?c=<raw code>
And POST /v1/user/invite is rate-limited per client IP with the auth rate limiter
(AUTH_RATE_LIMIT_MAX_ATTEMPTS, AUTH_RATE_LIMIT_WINDOW_SECONDS), independently counted from
/login and /password-reset
Scenario: A verified user invites a new address
Given a user repository containing verified user id 7, who is the owner, username "marta", display_name ""
And an empty invite repository
And a valid jwt cookie for user id 7
When the client sends POST /v1/user/invite with body {"email": "Sam.Oliveira@Renew.example"}
Then the response status is 201
And the response body is a JSON object with exactly the keys id, kind, email, status, created_at
and expires_at, with kind "invite", email "sam.oliveira@renew.example" and status "pending"
And the response body contains no key named code, hashed_code, verification_code or password
And the invite repository holds one invite with email "sam.oliveira@renew.example",
invited_by 7, accepted_at empty and expires_at 3 days after created_at
And the stored code is the hash of the raw code, not the raw code
And exactly one email was sent to "sam.oliveira@renew.example" with template "invitation"
And that email's Host is the configured PublicURL, its VerificationCode is the raw code,
its Email is "sam.oliveira@renew.example" and its InvitedBy is "marta"
Scenario: The email names the inviter by display name when there is one
Given verified user id 7, username "ines", display_name "Ines Duarte"
When the client sends POST /v1/user/invite with body {"email": "lea.martin@renew.example"}
Then the response status is 201
And the email's InvitedBy is "Ines Duarte"
Scenario Outline: An invalid email is rejected before anything is stored or sent
Given verified user id 7 and a valid jwt cookie for user id 7
When the client sends POST /v1/user/invite with body <body>
Then the response status is <status>
And the invite repository is still empty
And no email was sent
Examples:
| body | status |
| {"email": "sam.oliveira@renew"} | 400 |
| {"email": ""} | 400 |
| {} | 400 |
| {"email": "not-an-email"} | 400 |
| not json | 400 |
Scenario: An address that already has an account is refused
Given verified user id 7 and a user "jonas" with email "Jonas@Renew.example"
When the client sends POST /v1/user/invite with body {"email": "jonas@renew.example"}
Then the response status is 409
And the response body is "This address already has an account."
And the invite repository is still empty
And no email was sent
Scenario: An address with a live pending invite is refused
Given verified user id 7 and a pending invite for "sam.oliveira@renew.example" expiring in 2 days
When the client sends POST /v1/user/invite with body {"email": "sam.oliveira@renew.example"}
Then the response status is 409
And the response body is "There's already a pending invite for this address."
And the invite repository still holds only the original invite, unchanged
And no email was sent
Scenario: An expired invite is replaced by a new one
Given verified user id 7 and an expired invite for "p.huber@gmail.com" that expired 1 hour ago
When the client sends POST /v1/user/invite with body {"email": "p.huber@gmail.com"}
Then the response status is 201
And the invite repository holds exactly one invite for "p.huber@gmail.com", pending, with a
new code, and the expired one no longer exists
And exactly one email was sent to "p.huber@gmail.com"
Scenario: A failed email removes the invite
Given verified user id 7 and the mail repository is set to fail its next Send
When the client sends POST /v1/user/invite with body {"email": "lea.martin@renew.example"}
Then the response status is 500
And the response body is "Couldn't send the invite. Try again in a moment."
And the invite repository is empty
When the failure is cleared and the client sends the same request again
Then the response status is 201
Scenario: A failed email does not restore a replaced expired invite
Given an expired invite for "p.huber@gmail.com" and the mail repository set to fail its next Send
When the client sends POST /v1/user/invite with body {"email": "p.huber@gmail.com"}
Then the response status is 500
And the invite repository holds no invite for "p.huber@gmail.com"
Scenario Outline: Only an authenticated, verified, current-token user can use the endpoints
Given the request is made <credentials>
When the client sends <method> <path>
Then the response status is <status>
And no invite was created and no email was sent
Examples:
| credentials | method | path | status |
| with no jwt cookie | POST | /v1/user/invite | 401 |
| with a jwt cookie of an unverified user | POST | /v1/user/invite | 403 |
| with a jwt cookie whose token_version is stale | POST | /v1/user/invite | 401 |
| with a jwt cookie of a verified admin | POST | /v1/user/invite | 403 |
| with no jwt cookie | GET | /v1/user/ | 401 |
| with a jwt cookie of an unverified user | GET | /v1/user/ | 403 |
Scenario: The invite endpoint is rate-limited
Given AUTH_RATE_LIMIT_MAX_ATTEMPTS is 2 for a window covering the whole test
When the client at IP "203.0.113.20" sends 2 valid POST /v1/user/invite requests
And then sends a 3rd
Then the 3rd response is 429 with body apperr.TooManyRequestsErrorMessage and a Retry-After header
And no invite was created and no email was sent for the 3rd request
And GET /v1/user/ from the same client is not rejected with 429
Scenario: The list shows users and open invites, newest first
Given verified user id 7 "marta" created 12 Mar 2026
And user "jonas" created 2 Apr 2026
And user "ines" with display_name "Ines Duarte" created 18 Jun 2026
And an expired invite for "p.huber@gmail.com" created 3 Aug 2026
And a pending invite for "sam.oliveira@renew.example" created 27 Sep 2026
And an accepted invite for "jonas@renew.example" created 1 Apr 2026
When the client sends GET /v1/user/ with a valid jwt cookie for user id 7
Then the response status is 200
And the response body is a JSON array of exactly 5 items in this order: the pending invite for
"sam.oliveira@renew.example", the expired invite for "p.huber@gmail.com", user "ines", user
"jonas", user "marta"
And the accepted invite is not listed
And the invite items have exactly the keys id, kind, email, status, created_at, with kind
"invite" and status "pending" or "expired"
And the user items have exactly the keys id, kind, username, display_name, email, role, status,
created_at, with kind "user" and status "accepted"
And each user item has its own email and a role
And no item has a key named password, password_reset_code,
verification_code, verification_expiration, password_reset_expiration, token_version,
code, hashed_code, invited_by or accepted_at
Scenario: With nobody invited the list contains only the registered user
Given only verified user id 7 "marta"
When the client sends GET /v1/user/ with a valid jwt cookie for user id 7
Then the response status is 200
And the response body is a JSON array of exactly one item, kind "user", username "marta",
status "accepted"
Scenario: An invite turns from pending to expired with time, without any stored status
Given an invite created 3 days and 1 minute ago that has not been accepted
When the client sends GET /v1/user/
Then that invite's status is "expired"
Scenario: Registration stays closed for uninvited people
Given a user repository containing one verified user
And a pending invite for "sam.oliveira@renew.example"
When the client sends POST /v1/auth/register with username "sam", password "hunter2example12",
email "sam.oliveira@renew.example"
Then the response status is 403
And the response body is exactly apperr.RegistrationClosedErrorMessage
And no user was created and no email was sent
Scenario: Registration on an empty instance is unchanged
Given the user repository is empty
When the client sends POST /v1/auth/register with username "bob", password "hunter2example12",
email "bob@example.com"
Then the response status is 200
And a verification email is sent with template "verification"
And no invite exists
Scenario: Inviting someone never changes GET /v1/auth/registration
Given a user repository containing one verified user
When a pending invite exists
Then GET /v1/auth/registration still reports registration closed
+103
View File
@@ -0,0 +1,103 @@
# QA procedure: invitations
Package: `test` (black-box). New fakes must have unique type names across the package:
`mockInviteRepo` (implements `invite.Repository` with an in-memory slice and a `failSwitch`),
plus a `fixedClock` only if the use case takes one. Reuse `mockUserRepo` and `stubHasher`
(`user_test.go`) and `mockMailRepo` (`mail_test.go`; `SentEmails` entries expose `Address`,
`Template`, `Data`; `fail.failNext("Send")`).
## Setup shared by every case
1. Call `validator.InitValidator()` once.
2. Use cases: `useCases.NewCreateInviteUseCase(userRepo, inviteRepo, &stubHasher{}, mailRepo,
"https://cms.example.com")` and `useCases.NewListUsersAndInvitesUseCase(userRepo, inviteRepo)`
(final names are the coder's; constructors take only domain interfaces).
3. Handler: `user.NewHandler(updateProfile, createInvite, listUsersAndInvites)` mounted on a fresh
`chi.NewRouter()` mirroring `NewUserRouter`: `jwtauth.Verifier` + `jwtauth.Authenticator` with
`jwtauth.New("HS256", []byte("test-secret"), nil)`, `RequireCurrentToken(getUser)`,
`RequireVerifiedUser(getUser)`, then `POST /invite` and `GET /`. `POST /invite` is also wrapped
in `RequireOwner(getUser)`, placed before the limiter. For the rate-limit case
wrap only `POST /invite` in `RequireOwner(getUser)` + `TrustedProxyRealIP(nil)` +
`NewRateLimiter(2, time.Minute)`.
Requests via `httptest`; jwt cookie built with the `user_id` and `token_version` claims as in
`test/verified_account_required_http_test.go`. No live server, no real SQLite, no real SMTP.
4. Seed users: verified id 7 "marta" with `Role: owner`; unverified id 8 for the 403 cases. Time is real: build
invites with `ExpiresAt`/`CreatedAt` relative to `time.Now()` and compare with a 5 s tolerance.
## POST /v1/user/invite
5. Body `{"email":"Sam.Oliveira@Renew.example"}`, cookie for 7 -> `201`. Decode into
`map[string]json.RawMessage`: the key set is exactly `id`, `kind`, `email`, `status`,
`created_at`, `expires_at`, with `kind`="invite", `email`="sam.oliveira@renew.example",
`status`="pending"; none of `code`, `hashed_code`, `verification_code`, `password`.
`inviteRepo` holds one invite: lower-case email, `InvitedBy==7`, `AcceptedAt` nil,
`abs(ExpiresAt - (CreatedAt+72h)) < 5s`, stored code == `"hashed:"+rawCode` (stubHasher) where
`rawCode` is taken from the mail data; the stored code is not equal to `rawCode`.
6. `mailRepo.SentEmails` has exactly one entry: `Address`, `Template=="invitation"`, data of the
invitation mail type with `Host=="https://cms.example.com"`, `Email` the invited address,
`InvitedBy=="marta"` and a uuid-shaped `VerificationCode`.
7. Inviter with `DisplayName:"Ines Duarte"` -> `InvitedBy=="Ines Duarte"`. Inviter with an
empty display name -> username.
8. Table for 400 (`{"email":"sam.oliveira@renew"}`, `{"email":""}`, `{}`, `{"email":"not-an-email"}`,
`not json`): status `400`, `inviteRepo` empty, `SentEmails` empty.
9. Existing user with email `"Jonas@Renew.example"`, invite `jonas@renew.example` -> `409`, body exactly the new
apperr constant "This address already has an account.", no invite, no mail. This case pins that
the match is case-insensitive.
10. Seed a pending invite (expires in 2 days) for the address -> `409`, body "There's already a pending
invite for this address.", the seeded invite unchanged (same code hash and expiry), no mail.
11. Seed an expired invite (expired 1 h ago) -> `201`; `inviteRepo` has exactly one invite for the address, with
a different code hash and an expiry about 3 days out; one mail sent.
12. `mailRepo.fail.failNext("Send")` -> `500`, body "Couldn't send the invite. Try again in a moment.",
`inviteRepo` empty. Repeat the same request without re-arming -> `201`. With a seeded expired invite and a
failing send -> `500` and no invite for that address remains.
13. Auth table (`POST`): no cookie -> `401`; cookie of unverified user 8 -> `403`; cookie with stale
`token_version` -> `401`; cookie of a verified admin (seeded with `Role: admin`) -> `403`, plain
text body exactly `apperr.OwnerRequiredErrorMessage`. Each asserts no invite and no mail.
14. Rate limit: limiter of 2 per minute, `RemoteAddr` `203.0.113.20:1234`, three valid POSTs -> `201`,
`201`, `429`; third body is exactly `apperr.TooManyRequestsErrorMessage`, has `Retry-After`, and adds no
invite or mail. `GET /` from the same address afterwards is not `429`.
## GET /v1/user/
15. Seed per the feature scenario (three users, an expired, a pending and an accepted invite, with the
stated `CreatedAt` values). `200`; decode as `[]map[string]json.RawMessage`. Assert length 5, order
(pending sam, expired p.huber, ines, jonas, marta), key sets exactly as specified: `id`, `kind`,
`username`, `display_name`, `email`, `role`, `status`, `created_at` for user items and `id`, `kind`,
`email`, `status`, `created_at` for invite items, accepted invite absent, and none of the forbidden
keys anywhere. Also assert the raw body string contains each accepted user's own email address.
16. Only user 7 -> array with exactly one `kind:"user"` item, status `accepted`.
17. Invite created 3 days + 1 minute ago -> `status:"expired"`; created 2 days ago -> `pending`;
with `AcceptedAt` set -> not listed.
18. Auth table (`GET`): no cookie -> `401`; unverified -> `403`.
## Use-case level (no HTTP)
19. `CreateInvite` on a repository holding a user with the same email -> `errors.Is(err, invite.ErrEmailHasAccount)`;
live pending invite -> `errors.Is(err, invite.ErrPendingInvite)` (sentinel names are the coder's).
A mail failure wraps the mail repository error and the `Delete` of the invite is called
(if `Delete` also fails, both errors are joined, as `CreateUser` does).
## Mailer (real embedded templates, no SMTP)
20. `mailer.MailRepository{}.Render("invitation", data)` with `Host:"https://cms.example.com"`,
`VerificationCode:"abc-123"`, `Email:"lea@example.com"`, `InvitedBy:"Ines Duarte"` returns subject
`"Ines Duarte invited you to RenewCMS"` and a body containing
`https://cms.example.com/invite/accept?c=abc-123`, `lea@example.com` and `Ines Duarte`.
An `InvitedBy` of `<b>x</b>` is HTML-escaped in body. Subjects for `verification` and `password-reset` are
unchanged, and an unknown template still gets the default subject.
21. `internal/infrastructure/mailer/templates/invitation.html` is byte-identical to
`docs/design/source/emails/invitation.html` (read both files and compare).
## Regression: registration (extends registration_gate_and_verification_email.qa.md)
22. With one verified user and a pending invite for `sam.oliveira@renew.example`, `POST /v1/auth/register` with that
email -> `403`, body exactly `apperr.RegistrationClosedErrorMessage`, no user created, no mail sent.
23. Empty user repository -> `POST /v1/auth/register` still `200` with a `jwt` cookie and one `verification`
mail, and `inviteRepo` untouched. `GET /v1/auth/registration` still reports closed when a verified user
and a pending invite exist.
## Manual verification (not exercised by the Go tests)
- Start the app once against a fresh SQLite file: the `invites` table exists (model registered in
`AutoMigrate` in `api/dependecyInjection.go`) and inviting persists across a restart.
- Send a real invitation through a real or sandboxed SMTP server: the subject line, the rendering in a mail
client (light and dark) and that the link `{PUBLIC_URL}/invite/accept?c=...` carries the raw code.
The screen the link opens is not designed and is out of scope, so the link will not resolve in the SPA yet.
- SPA copy for the 429 ("Too many invites. Wait a moment, then try again.") is a note for the later SPA
slice and is not tested here. The SPA keys list rows by kind and id, since a user and an invite can share
a numeric id.
- Layering check by review: use cases import only `internal/domain/*`; the mailer subject logic lives in
`internal/infrastructure/mailer`.
+205
View File
@@ -0,0 +1,205 @@
Feature: The owner can cancel a pending invite and renew a pending or expired one
As the owner of the shared RenewCMS workspace
I want to cancel an invite I no longer want, or renew one that is stale or expired
So that only the people I currently intend to invite can create an account
Background:
Given the invite domain, the invitation email and the roles are those of features/invitations.feature
and features/user_roles.feature
And DELETE /v1/user/invite/{id} and POST /v1/user/invite/{id}/renew are mounted in NewUserRouter,
in the same group as POST /v1/user/invite: valid jwt cookie, current token_version, verified user,
owner role, trusted-proxy real IP, then the auth rate limiter
And the checks run in this order: 401, 403 unverified, 403 not owner, 429, 400 invalid id, 404, 409,
then the action
And user 7 "marta" is the verified owner and user 9 "jonas" is a verified admin
And error responses are plain text from http.Error, and the messages are:
| case | status | body |
| unknown invite | 404 | Invite not found |
| invite already accepted | 409 | This invite has already been accepted. |
| id is not a uint32 | 400 | apperr.IdUint32ErrorMessage |
| not the owner | 403 | Only the owner can do this. |
| no valid session | 401 | apperr.UnauthorizedErrorMessage |
| rate limited | 429 | apperr.TooManyRequestsErrorMessage |
| renew email not sent | 500 | Couldn't send the invite. Try again in a moment. |
And the renew response has the same shape as the create response: exactly the keys id, kind
("invite"), email, status, created_at and expires_at
Rule: Cancelling an invite
Scenario: The owner cancels a pending invite
Given an invite id 3 for "sam.oliveira@renew.example", pending, created by user 7
And a valid jwt cookie for user 7
When the client sends DELETE /v1/user/invite/3
Then the response status is 204
And the response body is empty
And the invite repository no longer holds invite 3
And no email was sent
And GET /v1/user/ no longer lists the invite
Scenario: A cancelled invite's link stops working
Given invite 3 was cancelled by the owner
When the client sends GET /v1/auth/invite?c=<the code from that invite>
Then the response status is 404
And the response body is "This invite link doesn't work."
And accepting the invite with that code returns 404, creates no user and sets no cookie
Scenario: A cancelled address can be invited again
Given invite 3 for "sam.oliveira@renew.example" was cancelled
When the owner sends POST /v1/user/invite for that address
Then the response status is 201
Scenario: The owner cancels an expired invite
Given invite 4 is expired
When the owner sends DELETE /v1/user/invite/4
Then the response status is 204
And the invite repository no longer holds invite 4
Scenario: Other invites and users are untouched
Given invites 3 and 4 and users 7 and 9
When the owner cancels invite 3
Then invite 4 and users 7 and 9 are unchanged
Scenario: An unknown invite is not found
When the owner sends DELETE /v1/user/invite/999
Then the response status is 404
And the response body is "Invite not found"
Scenario: Cancelling twice is not found
Given the owner cancelled invite 3
When the owner sends DELETE /v1/user/invite/3 again
Then the response status is 404
Scenario: An accepted invite cannot be cancelled
Given invite 5 was accepted and its user exists
When the owner sends DELETE /v1/user/invite/5
Then the response status is 409
And the response body is "This invite has already been accepted."
And invite 5 and its user remain
Rule: Renewing an invite
Scenario: The owner renews an expired invite
Given invite 4 for "lea.martin@renew.example", created 5 days ago, expired 2 days ago,
invited_by 7, stored code hash "hashed:OLD-CODE"
And a valid jwt cookie for user 7
When the client sends POST /v1/user/invite/4/renew
Then the response status is 200
And the response has Cache-Control "no-store"
And the response id is 4, kind "invite", email "lea.martin@renew.example" and status "pending"
And created_at is now and expires_at is 3 days after created_at, each within 5 seconds
And the response body has no key named code, hashed_code, invited_by or accepted_at
And the invite repository holds exactly one invite for that address, with id 4, a new code hash,
invited_by 7 and accepted_at empty
Scenario: The owner renews a pending invite
Given invite 3 is pending
When the owner sends POST /v1/user/invite/3/renew
Then the response status is 200
And invite 3 has a new code hash and created_at now
Scenario: A renewed invite moves to the top of the users list
Given invite 3 is pending and older than invite 6
When the owner renews invite 3
Then GET /v1/user/ lists invite 3 before invite 6
Scenario: The old link is dead and the new link works
Given invite 4 was renewed and the raw code in the new email is NEW-CODE
When the client sends GET /v1/auth/invite?c=<the old code>
Then the response status is 404
And accepting with the old code returns 404 and creates no user
And GET /v1/auth/invite?c=NEW-CODE returns 200 with {"email": "lea.martin@renew.example"}
And this holds when the renewed invite was pending as well as expired
Scenario: Renewing sends the invitation email again
When the owner renews invite 4
Then exactly one email was sent, with template "invitation"
And its Host is the configured PublicURL, its Email is the invited address, its InvitedBy is
the acting owner's display name or, when empty, username
And its VerificationCode is the new raw code
And the link in it is <Host>/invite/accept?c=<new raw code>
And the invite's invited_by is unchanged
Scenario: An unknown or cancelled invite is not found
When the owner sends POST /v1/user/invite/999/renew
Then the response status is 404
And the response body is "Invite not found"
And renewing a cancelled invite also returns 404
Scenario: An accepted invite cannot be renewed
Given invite 5 was accepted
When the owner sends POST /v1/user/invite/5/renew
Then the response status is 409
And the response body is "This invite has already been accepted."
And invite 5 is unchanged and no email was sent
Scenario: A failed email leaves the invite as it was
Given expired invite 4 and an email repository whose next send fails
When the owner sends POST /v1/user/invite/4/renew
Then the response status is 500
And the response body is "Couldn't send the invite. Try again in a moment."
And invite 4 keeps its old code hash, expires_at and created_at, and is still expired
And a pending invite whose renew mail fails keeps its old link valid
And a retry of the same request returns 200
Rule: Only the owner can manage invites
Scenario Outline: Access is checked on both endpoints
Given invite 3 is pending
When <caller> sends <method> <path>
Then the response status is <status>
And invite 3 is unchanged
And no email was sent
Examples:
| caller | method | path | status |
| a client with no cookie | DELETE | /v1/user/invite/3 | 401 |
| a client with no cookie | POST | /v1/user/invite/3/renew | 401 |
| a stale token_version | DELETE | /v1/user/invite/3 | 401 |
| a stale token_version | POST | /v1/user/invite/3/renew | 401 |
| an unverified user | DELETE | /v1/user/invite/3 | 403 |
| an unverified user | POST | /v1/user/invite/3/renew | 403 |
| verified admin 9 | DELETE | /v1/user/invite/3 | 403 |
| verified admin 9 | POST | /v1/user/invite/3/renew | 403 |
Scenario: An admin is refused with the owner message, even on an unknown id
When admin 9 sends DELETE /v1/user/invite/999
Then the response status is 403
And the response body is "Only the owner can do this."
Scenario Outline: An id that is not a uint32 is rejected
When the owner sends <method> <path>
Then the response status is 400
And the response body is apperr.IdUint32ErrorMessage
Examples:
| method | path |
| DELETE | /v1/user/invite/abc |
| DELETE | /v1/user/invite/-1 |
| DELETE | /v1/user/invite/4294967296 |
| POST | /v1/user/invite/abc/renew |
| POST | /v1/user/invite/-1/renew |
| POST | /v1/user/invite/4294967296/renew|
Rule: Rate limiting
Scenario: Requests over the limit are refused
Given the auth rate limiter allows 2 requests per window
When the owner sends three valid requests to DELETE or renew from IP 203.0.113.40
Then the third response is 429 with apperr.TooManyRequestsErrorMessage and a Retry-After header
And the third request changes nothing and sends no email
And GET /v1/user/ from the same address is not 429
Scenario: An admin does not use up the quota
When admin 9 sends three requests from one IP
Then all three responses are 403, not 429
Scenario: The counter is shared with inviting
Given the auth rate limiter allows 2 requests per window
When the owner sends POST /v1/user/invite, then renews an invite, then sends DELETE /v1/user/invite/3
Then the DELETE returns 429
Rule: Existing behaviour is unchanged
Scenario: The invitation and acceptance features still hold
Then every scenario of features/invitations.feature and features/accept_invitation.feature still passes
+71
View File
@@ -0,0 +1,71 @@
# QA procedure: invite management
Package: `test` (black-box). Reuse `mockUserRepo`, `stubHasher`, `mockMailRepo` and `mockInviteRepo`.
Extend `mockInviteRepo` with the new renew method and a `failSwitch` entry for it (unique type names
across the package). No live server, no real SQLite (except case 27), no real SMTP.
## Setup shared by every case
1. Call `validator.InitValidator()` once.
2. Use cases over domain interfaces only: `CreateInvite`, `ListUsersAndInvites`, `GetInvite`, the accept
use case, plus the new cancel and renew use cases (final names are the coder's).
3. Handler built with `NewHandler(...)` on a fresh `chi.NewRouter()` mirroring `NewUserRouter`:
`jwtauth.Verifier` + `jwtauth.Authenticator` (`jwtauth.New("HS256", []byte("test-secret"), nil)`),
`RequireCurrentToken`, `RequireVerifiedUser`, `GET /`, then a group with `RequireOwner`,
`TrustedProxyRealIP(nil)` and `NewRateLimiter` containing `POST /invite`, `DELETE /invite/{id}` and
`POST /invite/{id}/renew`. Mount `GET /invite` and `POST /invite/accept` from the auth handler for the
old-link cases.
4. Seed users: owner 7 "marta", unverified 8, admin 9. Invite hashes are `"hashed:"+raw`. Times are
relative to `time.Now()`, compared with a 5 s tolerance.
## DELETE /v1/user/invite/{id}
5. Pending invite, owner cookie -> `204`, empty body, invite gone, no mail, absent from `GET /`.
6. After cancel: `GET /invite?c=<code>` -> `404`; accept -> `404`, no user, no cookie; re-invite the address -> `201`.
7. Expired invite -> `204`.
8. Unknown id -> `404` "Invite not found"; second delete -> `404`.
9. Accepted invite -> `409` "This invite has already been accepted."; invite and user remain.
10. Other invites and users unchanged after a cancel.
11. Repository delete failure -> `500`, invite still present.
## POST /v1/user/invite/{id}/renew
12. Expired invite -> `200`, `Cache-Control: no-store`; key set exactly `id`, `kind`, `email`, `status`,
`created_at`, `expires_at`; no `code`, `hashed_code`, `invited_by`, `accepted_at`.
13. Stored invite: same id, new hash, `invited_by` 7, `accepted_at` nil, `created_at` about now,
`expires_at` = `created_at` + 72h.
14. Pending invite renews with `200`, new hash.
15. Mail: exactly one entry, template `invitation`, `Host`, `Email`, `InvitedBy` by display name or username
of the acting owner, `VerificationCode` = raw new code.
16. `GET /` lists the renewed invite first.
17. Old code: `GET /invite` and accept -> `404`, no user; new code -> `200` with the email. Control checks before
the renew show the old code worked. Same for pending.
18. Unknown id -> `404`; cancelled id -> `404`.
19. Accepted -> `409`, all fields unchanged, no mail.
20. `mailRepo.fail.failNext("Send")` -> `500` "Couldn't send the invite. Try again in a moment."; invite hash,
expiry and created_at unchanged; retry -> `200`.
21. Renew persistence failure -> `500`, no mail, invite unchanged.
## Access and ids (table over both endpoints)
22. No cookie -> `401`; stale `token_version` -> `401`; unverified -> `403`; admin -> `403` with body
`apperr.OwnerRequiredErrorMessage`; admin on an unknown id -> `403`. Each: invite unchanged, no mail.
23. Ids `abc`, `-1`, `4294967296` -> `400` `apperr.IdUint32ErrorMessage` on both endpoints.
## Rate limit
24. Limiter of 2, `RemoteAddr` `203.0.113.40:1234`: third request -> `429`, `apperr.TooManyRequestsErrorMessage`,
`Retry-After`, no change, no mail. `GET /` from the same address is not `429`.
25. Admin's three requests -> `403`, `403`, `403`.
26. Shared counter: `POST /invite`, renew, then `DELETE` -> `429`.
## Use case and persistence
27. Use case level:
- unknown id -> `errors.Is(err, ErrInviteNotFound)`; accepted -> the accepted sentinel (name is the coder's);
- success returns the same id, a new hash, `CreatedAt` about now, `ExpiresAt` = `CreatedAt` + `invite.Lifetime`;
- mail failure wraps `ErrInviteEmailNotSent` and restores the prior values;
- the mail logic is shared with `CreateInvite`.
28. Persistence on in-memory SQLite: the renew method updates hash, expiry and created_at by id, returns
`ErrInviteNotFound` when the row is missing or already accepted.
## Manual
Renew against a real or sandboxed SMTP server: one mail arrives, the new link works, the old mail's link is dead.
Persistence across a restart on a fresh SQLite file. Review layering and that no comments were introduced.
## Out of scope
SPA handling of 404, 409 and 429 on these endpoints: this slice is API-only.
+102
View File
@@ -0,0 +1,102 @@
Feature: Log-in card sizing, alert placement and focus behavior match the Auth board
As the maintainer of RenewCMS
I want AuthShell's card padding, control heights, "Forgot password?" styling, field-error
presentation, theme select and h1 focus timing built exactly to the AuthCard board
(docs/design/source/AuthCard.dc.html) instead of Nuxt UI's untouched defaults
So that /login (and every other AuthShell-based public screen) matches the design board pixel
for pixel, at desktop and mobile, in light and dark
This complements features/auth_shell_login_conformance.feature, which covers AppLogo, the
UPageCard title/description wiring, the muted-background breakpoint and the neutral/error input
edge. This feature covers what that one doesn't: exact card/control measurements, the "Forgot
password?" link's own styling, the field-error icon and halo behavior, the theme select's
chevron, where the alert sits relative to the card, and when the h1 receives focus.
Background:
Given AuthShell is the layout for every public route, per docs/design/routes.md
And the card's padding, control heights and title size come from
docs/design/source/AuthCard.dc.html's renderVals(): pad "40px" and control height "40px"
from the sm breakpoint up; pad "8px 20px 0" (with a separate footer padding of
"0 20px 24px") and control height "44px" below sm; the title is always "font:600 20px/28px"
And the Password UFormField's "Forgot password?" link is styled color var(--ui-text-toned)
(muted), text-decoration underline, underline-offset 3px, per AuthCard.dc.html's f.link span
And a field error renders with the i-lucide-circle-alert icon in var(--ui-error), and the
field's edge/shadow is computed error-first, so an errored field that is also focused shows
only the single error-colored inset ring, never a focus ring stacked under or around it
And AuthShell's notice slot (the alert) renders inside the card's own layout, after the
title/description block and before the form — not as a sibling element above the card
And the footer's UColorModeSelect renders with no chevron/dropdown-arrow icon, as the last
(right-hand) child of the footer's space-between row, per AuthCard.dc.html's theme span
And on first paint, AuthShell's h1 (tabindex="-1") does not receive focus; focus moves to it
only when the title changes while AuthShell stays mounted (an in-app navigation between
public screens, e.g. /login to /register/reset/request), per components.md's AuthShell a11y
line ("On route change, focus moves to the h1")
And the h1 never shows a visible focus outline, since it is only ever focused programmatically
and is not part of the visible keyboard-tab order
Scenario: Card padding and control heights at sm and up
Given the user is on /login at a viewport of sm or wider
When AuthShell and the login form render
Then the card's own padding is 40px on every side
And the Username input, the Password input and the submit button are each 40px tall
And input text renders at 14px
Scenario: Card padding and control heights below sm
Given the user is on /login at a viewport below sm
When AuthShell and the login form render
Then the card's own padding is 8px top, 20px left and right, 0 bottom
And the footer (outside the card) has its own padding of 0 top, 20px left and right, 24px bottom
And the Username input, the Password input and the submit button are each 44px tall
And input text renders at 16px
Scenario: "Forgot password?" is underlined and muted
Given the user is on /login
When the Password field renders
Then the "Forgot password?" link uses the muted text color (--ui-text-toned)
And the link is underlined with a 3px underline offset
And the link carries no other emphasis (not bold, not the primary color)
Scenario: A field error shows the circle-alert icon with no extra focus halo
Given the user is on /login
When the user submits with Username "ma" and Password empty (the Validation errors state)
Then the Username field's error message is preceded by the i-lucide-circle-alert icon in the
error color
And the Password field's error message is preceded by the same icon in the same color
When the user tabs into the still-errored Username field so it is both errored and focused
Then the field shows exactly one inset ring, in the error color
And no second, differently colored focus ring is layered under or around it
Scenario: The theme select is right-aligned in the footer with no chevron
Given the user is on /login
When AuthShell's footer renders
Then the UColorModeSelect is the last (right-most) element in the footer's row
And it renders only its mode icon and label ("System", "Light" or "Dark")
And it renders no trailing chevron or dropdown-arrow icon
Scenario Outline: The alert renders inside the card, under the description
Given the user is redirected to <path>
When /login renders with its <state> alert
Then the alert is a child of the same card element that contains the title and description,
not a sibling positioned above the card
And the alert sits after the title/description block and before the Username field
And the alert's background uses UAlert's soft variant, which is dark-tinted automatically in
dark mode
Examples:
| path | state |
| /login?redirect=/article/12/edit&reason=expired | Session expired |
| /login?reason=password-changed | Password changed |
Scenario: The h1 is not focused on first load
Given the user navigates directly to /login (a fresh page load)
When AuthShell mounts and the h1 renders
Then the h1 does not receive focus
And focus remains on the document body (or wherever the browser places it on load)
Scenario: Focus moves to the h1 only on an in-app navigation between public screens
Given the user is on /login with AuthShell already mounted
When the user follows the "Forgot password?" link to /register/reset/request without a full
page reload
Then AuthShell's h1 receives focus once ResetRequestPage's title renders
And the h1 shows no visible outline when it receives this focus
Loaded 100 of 540 files, more files were not shown because too many files have changed in this diff. Show more