Compare commits
37
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8ad3941f6d | ||
|
|
d275ba3c14 | ||
|
|
3e01c29657 | ||
|
|
acd392c29d | ||
|
|
514a082c96 | ||
|
|
844842fdae | ||
|
|
7e9bd9ba30 | ||
|
|
68401d66e0 | ||
|
|
daf497576f | ||
|
|
0490a4c494 | ||
|
|
2c8f39273c | ||
|
|
721311a643 | ||
|
|
7f1e8e572d | ||
|
|
02a0a36dc3 | ||
|
|
5a430c08f4 | ||
|
|
54e8fd5fed | ||
|
|
70460e4170 | ||
|
|
834493a4f5 | ||
|
|
a49eec909c | ||
|
|
e10a5e57e2 | ||
|
|
ff0854f331 | ||
|
|
b3793d5dbb | ||
|
|
008b0dfbb9 | ||
|
|
67d456baf6 | ||
|
|
0d99544579 | ||
|
|
95ae043d3e | ||
|
|
e0fa433ff9 | ||
|
|
142325730d | ||
|
|
1ece778caf | ||
|
|
153fd8719a | ||
|
|
461e93e3b5 | ||
|
|
162fea4afb | ||
|
|
b146dfead7 | ||
|
|
27dadbbfa6 | ||
|
|
6dc47789ef | ||
|
|
65ced64568 | ||
|
|
c40522a09f |
No files matched your search
@@ -0,0 +1,17 @@
|
|||||||
|
.git
|
||||||
|
.gitignore
|
||||||
|
.dockerignore
|
||||||
|
.env
|
||||||
|
docker.env
|
||||||
|
tmp/
|
||||||
|
bin/
|
||||||
|
data/
|
||||||
|
node_modules
|
||||||
|
web/node_modules
|
||||||
|
internal/infrastructure/assets/dist
|
||||||
|
.task/
|
||||||
|
.claude/
|
||||||
|
.idea
|
||||||
|
.vscode
|
||||||
|
*.db
|
||||||
|
*.exe
|
||||||
@@ -14,3 +14,5 @@ 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
|
||||||
|
RENEWCMS_CONTAINER=false
|
||||||
+7
-1
@@ -4,7 +4,7 @@
|
|||||||
|
|
||||||
# DB
|
# DB
|
||||||
*.db
|
*.db
|
||||||
data/
|
/data/
|
||||||
|
|
||||||
# Build
|
# Build
|
||||||
bin
|
bin
|
||||||
@@ -12,6 +12,7 @@ dist/
|
|||||||
|
|
||||||
# Environment
|
# Environment
|
||||||
.env
|
.env
|
||||||
|
docker.env
|
||||||
|
|
||||||
# Generated files
|
# Generated files
|
||||||
tmp/
|
tmp/
|
||||||
@@ -20,5 +21,10 @@ build-errors.log
|
|||||||
uploadedImages/
|
uploadedImages/
|
||||||
*.exe
|
*.exe
|
||||||
|
|
||||||
|
# AI fest
|
||||||
.claude/
|
.claude/
|
||||||
CLAUDE.md
|
CLAUDE.md
|
||||||
|
.codex/
|
||||||
|
.agents/
|
||||||
|
AGENTS.md
|
||||||
|
codex-workflow.md
|
||||||
+30
@@ -0,0 +1,30 @@
|
|||||||
|
FROM oven/bun:1-alpine AS web
|
||||||
|
WORKDIR /src/web
|
||||||
|
COPY web/package.json web/bun.lock ./
|
||||||
|
RUN bun install --frozen-lockfile
|
||||||
|
COPY web/ ./
|
||||||
|
RUN bun run build-only
|
||||||
|
|
||||||
|
FROM golang:1.27.1-alpine AS server
|
||||||
|
ARG VERSION=dev
|
||||||
|
ENV CGO_ENABLED=0
|
||||||
|
WORKDIR /src
|
||||||
|
COPY go.mod go.sum ./
|
||||||
|
RUN go mod download
|
||||||
|
COPY . .
|
||||||
|
COPY --from=web /src/internal/infrastructure/assets/dist ./internal/infrastructure/assets/dist
|
||||||
|
RUN go build -trimpath -ldflags "-s -w -X main.version=${VERSION}" -o /out/renewcms ./cmd/server
|
||||||
|
|
||||||
|
FROM alpine:3.22
|
||||||
|
RUN addgroup -S -g 10001 renewcms \
|
||||||
|
&& adduser -S -u 10001 -G renewcms -H -s /sbin/nologin renewcms \
|
||||||
|
&& mkdir /data \
|
||||||
|
&& chown renewcms:renewcms /data
|
||||||
|
COPY --from=server /out/renewcms /usr/local/bin/renewcms
|
||||||
|
ENV RENEWCMS_CONTAINER=true
|
||||||
|
USER renewcms
|
||||||
|
WORKDIR /data
|
||||||
|
VOLUME /data
|
||||||
|
EXPOSE 8080
|
||||||
|
HEALTHCHECK --interval=30s --timeout=5s --start-period=10s --retries=3 CMD ["wget", "-qO-", "http://127.0.0.1:8080/healthz"]
|
||||||
|
ENTRYPOINT ["/usr/local/bin/renewcms"]
|
||||||
@@ -15,6 +15,20 @@ 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)**.
|
||||||
|
|
||||||
|
### Run with Docker
|
||||||
|
|
||||||
|
```sh
|
||||||
|
cp docker.env.example docker.env # fill in PUBLIC_URL, JWT_SECRET and SMTP_*
|
||||||
|
docker compose pull
|
||||||
|
docker compose up -d # http://localhost:8080
|
||||||
|
```
|
||||||
|
|
||||||
|
Upgrade with `docker compose pull && docker compose up -d`. The image `git.floriansylvain.fr/fsylvain/renewcms` is published by the maintainer with `task docker:publish` (no CI). Tags: `vX.Y.Z`, `X.Y.Z`, `X.Y` and `latest` for a stable release; `vX.Y.Z-<pre>`, `X.Y.Z-<pre>` and the moving `beta` or `rc` for a pre-release (`latest` never moves for those, so the default is `beta` for now). To build from source use the override described in **[docs/docker.md](docs/docker.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).
|
||||||
@@ -31,6 +45,7 @@ task dev # API with hot reload + Vite HMR → http://localhost:51
|
|||||||
|---|---|
|
|---|---|
|
||||||
| [docs/development.md](docs/development.md) | Dev setup, how Vite and the API fit together, tests, lint, `task` commands |
|
| [docs/development.md](docs/development.md) | Dev setup, how Vite and the API fit together, tests, lint, `task` commands |
|
||||||
| [docs/deployment.md](docs/deployment.md) | Building release binaries, running as a service, HTTPS, backups, upgrades |
|
| [docs/deployment.md](docs/deployment.md) | Building release binaries, running as a service, HTTPS, backups, upgrades |
|
||||||
|
| [docs/docker.md](docs/docker.md) | Running RenewCMS in Docker: image, Compose, data volume, backups, reverse proxy, tags, upgrades, publishing |
|
||||||
| [docs/configuration.md](docs/configuration.md) | Every environment variable |
|
| [docs/configuration.md](docs/configuration.md) | Every environment variable |
|
||||||
| [docs/architecture.md](docs/architecture.md) | Backend layering and how the SPA is embedded |
|
| [docs/architecture.md](docs/architecture.md) | Backend layering and how the SPA is embedded |
|
||||||
|
|
||||||
|
|||||||
+151
-2
@@ -122,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
|
||||||
@@ -147,6 +170,132 @@ tasks:
|
|||||||
cmds:
|
cmds:
|
||||||
- ./bin/{{.BINARY}}{{exeExt}}
|
- ./bin/{{.BINARY}}{{exeExt}}
|
||||||
|
|
||||||
|
docker:build:
|
||||||
|
desc: Build the Docker image tagged with the git describe version and latest
|
||||||
|
cmds:
|
||||||
|
- docker build --build-arg VERSION={{.VERSION}} -t renewcms:{{.VERSION}} -t renewcms:latest .
|
||||||
|
|
||||||
|
docker:run:
|
||||||
|
desc: Run the image once on a named volume, reading docker.env, on http://localhost:8080
|
||||||
|
cmds:
|
||||||
|
- docker run --rm --name renewcms -p 8080:8080 --env-file docker.env -e DB_FILE=/data/renewcms.db -e UPLOAD_DIR=/data/uploads -v renewcms-data:/data --stop-timeout 15 renewcms:latest
|
||||||
|
|
||||||
|
docker:up:
|
||||||
|
desc: Build from the local sources and start the Compose service in the background
|
||||||
|
env:
|
||||||
|
VERSION: '{{.VERSION}}'
|
||||||
|
cmds:
|
||||||
|
- docker compose -f docker-compose.yml -f docker-compose.build.yml up -d --build
|
||||||
|
|
||||||
|
docker:pull:
|
||||||
|
desc: Pull the published image (RENEWCMS_IMAGE, default the beta tag)
|
||||||
|
cmds:
|
||||||
|
- docker compose pull
|
||||||
|
|
||||||
|
docker:upgrade:
|
||||||
|
desc: Pull the published image and recreate the Compose service on it
|
||||||
|
cmds:
|
||||||
|
- docker compose pull
|
||||||
|
- docker compose up -d
|
||||||
|
|
||||||
|
docker:down:
|
||||||
|
desc: Stop and remove the Compose service (the data volume is kept)
|
||||||
|
cmds:
|
||||||
|
- docker compose down
|
||||||
|
|
||||||
|
docker:logs:
|
||||||
|
desc: Follow the Compose service logs
|
||||||
|
cmds:
|
||||||
|
- docker compose logs -f renewcms
|
||||||
|
|
||||||
|
docker:publish:
|
||||||
|
desc: 'Build and push the multi-arch image to the registry. Usage, task docker:publish [-- --dry-run]'
|
||||||
|
vars:
|
||||||
|
REGISTRY_IMAGE:
|
||||||
|
sh: echo "${REGISTRY_IMAGE-git.floriansylvain.fr/fsylvain/renewcms}"
|
||||||
|
cmds:
|
||||||
|
- cmd: |
|
||||||
|
IMAGE='{{.REGISTRY_IMAGE}}'
|
||||||
|
V='{{.VERSION}}'
|
||||||
|
ARGS='{{.CLI_ARGS}}'
|
||||||
|
fail() { echo "docker:publish refused: $1" >&2; exit 1; }
|
||||||
|
DRY=no
|
||||||
|
case "$ARGS" in
|
||||||
|
"") ;;
|
||||||
|
"--dry-run") DRY=yes ;;
|
||||||
|
*) fail "unknown argument '$ARGS' (only --dry-run is accepted)" ;;
|
||||||
|
esac
|
||||||
|
[ -n "$IMAGE" ] || fail "REGISTRY_IMAGE is empty"
|
||||||
|
case "$V" in
|
||||||
|
v*) ;;
|
||||||
|
*) fail "VERSION '$V' must be an exact tag vX.Y.Z or vX.Y.Z-<pre>" ;;
|
||||||
|
esac
|
||||||
|
R="${V#v}"
|
||||||
|
CORE="${R%%-*}"
|
||||||
|
PRE=""
|
||||||
|
[ "$CORE" = "$R" ] || PRE="${R#*-}"
|
||||||
|
MAJOR="${CORE%%.*}"
|
||||||
|
REST="${CORE#*.}"
|
||||||
|
MINOR="${REST%%.*}"
|
||||||
|
PATCH="${REST#*.}"
|
||||||
|
for N in "$MAJOR" "$MINOR" "$PATCH"; do
|
||||||
|
case "$N" in
|
||||||
|
""|*[!0-9]*) fail "VERSION '$V' must be an exact tag vX.Y.Z or vX.Y.Z-<pre>" ;;
|
||||||
|
esac
|
||||||
|
done
|
||||||
|
[ "$CORE" = "$MAJOR.$MINOR.$PATCH" ] || fail "VERSION '$V' must be an exact tag vX.Y.Z or vX.Y.Z-<pre>"
|
||||||
|
if [ "$R" != "$CORE" ]; then
|
||||||
|
case "$PRE" in
|
||||||
|
""|*[!0-9A-Za-z.-]*) fail "VERSION '$V' has an invalid pre-release part" ;;
|
||||||
|
esac
|
||||||
|
PRENAME="${PRE%%[!A-Za-z]*}"
|
||||||
|
[ -n "$PRENAME" ] || fail "VERSION '$V' pre-release must start with letters, for example -beta or -rc.1"
|
||||||
|
fi
|
||||||
|
if [ "$DRY" = no ]; then
|
||||||
|
[ -z "$(git status --porcelain)" ] || fail "the work tree has uncommitted changes"
|
||||||
|
[ "$(git describe --tags --exact-match 2>/dev/null)" = "$V" ] || fail "VERSION '$V' is not an exact git tag on HEAD (an override is accepted only with --dry-run)"
|
||||||
|
fi
|
||||||
|
TAGS="$V $R"
|
||||||
|
if [ -n "$PRE" ]; then
|
||||||
|
TAGS="$TAGS $PRENAME"
|
||||||
|
else
|
||||||
|
TAGS="$TAGS $MAJOR.$MINOR latest"
|
||||||
|
fi
|
||||||
|
ARGS_TAGS=""
|
||||||
|
LIST=""
|
||||||
|
for T in $TAGS; do
|
||||||
|
ARGS_TAGS="$ARGS_TAGS -t $IMAGE:$T"
|
||||||
|
LIST="$LIST, $T"
|
||||||
|
done
|
||||||
|
echo "image: $IMAGE"
|
||||||
|
echo "tags: ${LIST#, }"
|
||||||
|
if [ "$DRY" = yes ]; then
|
||||||
|
echo "dry run: building for the host platform only, loading locally, pushing nothing"
|
||||||
|
docker buildx build --load --build-arg VERSION="$V" $ARGS_TAGS .
|
||||||
|
exit 0
|
||||||
|
fi
|
||||||
|
BUILDER="$(docker buildx inspect 2>&1)" || fail "docker buildx is not available or no builder is selected (see docs/docker.md, Maintainer: publishing)"
|
||||||
|
STORE="$(docker info 2>&1)"
|
||||||
|
case "$BUILDER" in
|
||||||
|
*linux/amd64*) ;;
|
||||||
|
*) fail "the selected buildx builder does not support linux/amd64 (see docs/docker.md, Maintainer: publishing)" ;;
|
||||||
|
esac
|
||||||
|
case "$BUILDER" in
|
||||||
|
*linux/arm64*) ;;
|
||||||
|
*) fail "the selected buildx builder does not support linux/arm64: enable QEMU/binfmt (see docs/docker.md, Maintainer: publishing)" ;;
|
||||||
|
esac
|
||||||
|
case "$BUILDER" in
|
||||||
|
*"Driver:"*"docker-container"*|*"Driver:"*"kubernetes"*|*"Driver:"*"remote"*) ;;
|
||||||
|
*)
|
||||||
|
case "$STORE" in
|
||||||
|
*io.containerd.snapshotter*) ;;
|
||||||
|
*) fail "the selected builder uses the plain docker driver without the containerd image store, which cannot build multi-platform images: run 'docker buildx create --use' (see docs/docker.md, Maintainer: publishing)" ;;
|
||||||
|
esac
|
||||||
|
;;
|
||||||
|
esac
|
||||||
|
docker buildx build --platform linux/amd64,linux/arm64 --build-arg VERSION="$V" $ARGS_TAGS --push .
|
||||||
|
silent: true
|
||||||
|
|
||||||
clean:
|
clean:
|
||||||
desc: Remove build output, the built SPA and tmp/
|
desc: Remove build output, the built SPA and tmp/
|
||||||
cmds:
|
cmds:
|
||||||
|
|||||||
+175
-22
@@ -1,20 +1,30 @@
|
|||||||
package api
|
package api
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
domainAPIKey "RenewCMS/internal/domain/apikey"
|
||||||
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"
|
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/markdown"
|
||||||
"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"
|
"fmt"
|
||||||
|
"log"
|
||||||
|
"net/http"
|
||||||
"os"
|
"os"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
|
"runtime"
|
||||||
|
"sync"
|
||||||
|
"time"
|
||||||
|
|
||||||
"github.com/glebarez/sqlite"
|
"github.com/glebarez/sqlite"
|
||||||
"github.com/go-chi/jwtauth/v5"
|
"github.com/go-chi/jwtauth/v5"
|
||||||
@@ -22,6 +32,8 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
type UseCases struct {
|
type UseCases struct {
|
||||||
|
apiKeyAuthOnce sync.Once
|
||||||
|
apiKeyAuthMiddleware func(http.Handler) http.Handler
|
||||||
Token *jwtauth.JWTAuth
|
Token *jwtauth.JWTAuth
|
||||||
CreateArticleUseCase *useCases.CreateArticleUseCase
|
CreateArticleUseCase *useCases.CreateArticleUseCase
|
||||||
GetArticleUseCase *useCases.GetArticleUseCase
|
GetArticleUseCase *useCases.GetArticleUseCase
|
||||||
@@ -38,29 +50,64 @@ type UseCases struct {
|
|||||||
UpdateUserProfileUseCase *useCases.UpdateUserProfileUseCase
|
UpdateUserProfileUseCase *useCases.UpdateUserProfileUseCase
|
||||||
ListUsersUseCase *useCases.ListUsersUseCase
|
ListUsersUseCase *useCases.ListUsersUseCase
|
||||||
CreateInviteUseCase *useCases.CreateInviteUseCase
|
CreateInviteUseCase *useCases.CreateInviteUseCase
|
||||||
|
CancelInviteUseCase *useCases.CancelInviteUseCase
|
||||||
|
RenewInviteUseCase *useCases.RenewInviteUseCase
|
||||||
ListUsersAndInvitesUseCase *useCases.ListUsersAndInvitesUseCase
|
ListUsersAndInvitesUseCase *useCases.ListUsersAndInvitesUseCase
|
||||||
GetInviteUseCase *useCases.GetInviteUseCase
|
GetInviteUseCase *useCases.GetInviteUseCase
|
||||||
AcceptInviteUseCase *useCases.AcceptInviteUseCase
|
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
|
||||||
|
CreateAPIKeyUseCase *useCases.CreateAPIKeyUseCase
|
||||||
|
ListAPIKeysUseCase *useCases.ListAPIKeysUseCase
|
||||||
|
RevokeAPIKeyUseCase *useCases.RevokeAPIKeyUseCase
|
||||||
|
AuthenticateAPIKeyUseCase *useCases.AuthenticateAPIKeyUseCase
|
||||||
}
|
}
|
||||||
|
|
||||||
type Repositories struct {
|
type Repositories struct {
|
||||||
ArticleRepo domainArticle.Repository
|
ArticleRepo domainArticle.Repository
|
||||||
UserRepo domainUser.Repository
|
UserRepo domainUser.Repository
|
||||||
ImageRepo domainImage.Repository
|
ImageRepo domainImage.Repository
|
||||||
InviteRepo domainInvite.Repository
|
InviteRepo domainInvite.Repository
|
||||||
MailRepo domainMail.Repository
|
APIKeyRepo domainAPIKey.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
|
||||||
}
|
}
|
||||||
|
|
||||||
const sqliteBusyTimeoutMs = 5000
|
const (
|
||||||
|
sqliteBusyTimeoutMs = 5000
|
||||||
|
updateStatusFileName = "update-status.json"
|
||||||
|
updateJobFileName = "update-job.json"
|
||||||
|
updateHelperFileName = "update-helper.json"
|
||||||
|
updatesDirName = "updates"
|
||||||
|
backupsDirName = "backups"
|
||||||
|
)
|
||||||
|
|
||||||
func SQLiteDSN(dbName string) string {
|
func SQLiteDSN(dbName string) string {
|
||||||
return fmt.Sprintf("%s?_pragma=busy_timeout(%d)", dbName, sqliteBusyTimeoutMs)
|
return fmt.Sprintf("%s?_pragma=busy_timeout(%d)", dbName, sqliteBusyTimeoutMs)
|
||||||
}
|
}
|
||||||
|
|
||||||
func getDb(dbName string) *gorm.DB {
|
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())
|
||||||
}
|
}
|
||||||
@@ -69,54 +116,121 @@ func getDb(dbName string) *gorm.DB {
|
|||||||
panic("Unable to open the database: " + err.Error())
|
panic("Unable to open the database: " + err.Error())
|
||||||
}
|
}
|
||||||
|
|
||||||
if err := db.AutoMigrate(&models.Article{}, &models.User{}, &models.Invite{}); err != nil {
|
if err := db.AutoMigrate(&models.Article{}, &models.Image{}, &models.User{}, &models.Invite{}, &models.APIKey{}); 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),
|
||||||
InviteRepo: persistence.NewInviteRepository(db),
|
InviteRepo: persistence.NewInviteRepository(db),
|
||||||
MailRepo: mailer.NewMailRepository(settings.Smtp),
|
APIKeyRepo: persistence.NewAPIKeyRepository(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.NewContainerHelperDetector(update.NewFileHelperDetector(filepath.Join(dataDir, updateHelperFileName)), settings.Container),
|
||||||
|
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)),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func getUseCases(repos *Repositories, settings config.Settings) *UseCases {
|
func getUseCases(repos *Repositories, settings config.Settings) *UseCases {
|
||||||
hasher := hashing.NewBcryptHasher()
|
hasher := hashing.NewBcryptHasher()
|
||||||
|
renderer := markdown.NewConverter()
|
||||||
|
keyGenerator := hashing.NewSHA256KeyGenerator()
|
||||||
|
|
||||||
return &UseCases{
|
return &UseCases{
|
||||||
Token: jwtauth.New("HS256", []byte(settings.JWTSecret), nil),
|
Token: jwtauth.New("HS256", []byte(settings.JWTSecret), nil),
|
||||||
CreateArticleUseCase: useCases.NewCreateArticleUseCase(repos.ArticleRepo),
|
CreateArticleUseCase: useCases.NewCreateArticleUseCase(repos.ArticleRepo, renderer),
|
||||||
GetArticleUseCase: useCases.NewGetArticleUseCase(repos.ArticleRepo),
|
GetArticleUseCase: useCases.NewGetArticleUseCase(repos.ArticleRepo, renderer),
|
||||||
ListArticlesUseCase: useCases.NewListArticlesUseCase(repos.ArticleRepo),
|
ListArticlesUseCase: useCases.NewListArticlesUseCase(repos.ArticleRepo, renderer),
|
||||||
UpdateArticleUseCase: useCases.NewUpdateArticleUseCase(repos.ArticleRepo),
|
UpdateArticleUseCase: useCases.NewUpdateArticleUseCase(repos.ArticleRepo, renderer),
|
||||||
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),
|
||||||
VerifyUserUseCase: useCases.NewVerifyUserUseCase(repos.UserRepo, hasher),
|
VerifyUserUseCase: useCases.NewVerifyUserUseCase(repos.UserRepo, hasher),
|
||||||
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, repos.APIKeyRepo, time.Now),
|
||||||
UpdateUserProfileUseCase: useCases.NewUpdateUserProfileUseCase(repos.UserRepo),
|
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),
|
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),
|
ListUsersAndInvitesUseCase: useCases.NewListUsersAndInvitesUseCase(repos.UserRepo, repos.InviteRepo),
|
||||||
GetInviteUseCase: useCases.NewGetInviteUseCase(repos.InviteRepo, hasher),
|
GetInviteUseCase: useCases.NewGetInviteUseCase(repos.InviteRepo, hasher),
|
||||||
AcceptInviteUseCase: useCases.NewAcceptInviteUseCase(repos.UserRepo, 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, settings.Container, 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),
|
||||||
|
CreateAPIKeyUseCase: useCases.NewCreateAPIKeyUseCase(repos.APIKeyRepo, keyGenerator, time.Now),
|
||||||
|
ListAPIKeysUseCase: useCases.NewListAPIKeysUseCase(repos.APIKeyRepo, repos.UserRepo, time.Now),
|
||||||
|
RevokeAPIKeyUseCase: useCases.NewRevokeAPIKeyUseCase(repos.APIKeyRepo, repos.UserRepo, time.Now),
|
||||||
|
AuthenticateAPIKeyUseCase: useCases.NewAuthenticateAPIKeyUseCase(repos.APIKeyRepo, keyGenerator, repos.UserRepo, 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)
|
||||||
}
|
}
|
||||||
@@ -130,3 +244,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},
|
||||||
|
})
|
||||||
|
}
|
||||||
@@ -0,0 +1,176 @@
|
|||||||
|
package apikey
|
||||||
|
|
||||||
|
import (
|
||||||
|
"RenewCMS/api/pkg/apperr"
|
||||||
|
"RenewCMS/api/pkg/claims"
|
||||||
|
validator "RenewCMS/api/pkg/validator"
|
||||||
|
domain "RenewCMS/internal/domain/apikey"
|
||||||
|
"RenewCMS/internal/domain/user"
|
||||||
|
"RenewCMS/internal/infrastructure/useCases"
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"net/http"
|
||||||
|
"strconv"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/go-chi/chi/v5"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Handler struct {
|
||||||
|
CreateUseCase *useCases.CreateAPIKeyUseCase
|
||||||
|
ListUseCase *useCases.ListAPIKeysUseCase
|
||||||
|
RevokeUseCase *useCases.RevokeAPIKeyUseCase
|
||||||
|
}
|
||||||
|
|
||||||
|
type CreateAPIKeyRequest struct {
|
||||||
|
Name string `json:"name" validate:"required,max=60"`
|
||||||
|
ExpiresAt *time.Time `json:"expires_at"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type createdKeyResponse struct {
|
||||||
|
ID uint32 `json:"id"`
|
||||||
|
Name string `json:"name"`
|
||||||
|
Prefix string `json:"prefix"`
|
||||||
|
Key string `json:"key"`
|
||||||
|
CreatedAt time.Time `json:"created_at"`
|
||||||
|
ExpiresAt *time.Time `json:"expires_at"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type keyListItem struct {
|
||||||
|
ID uint32 `json:"id"`
|
||||||
|
UserID uint32 `json:"user_id"`
|
||||||
|
Name string `json:"name"`
|
||||||
|
Prefix string `json:"prefix"`
|
||||||
|
Status domain.Status `json:"status"`
|
||||||
|
CreatedAt time.Time `json:"created_at"`
|
||||||
|
LastUsedAt *time.Time `json:"last_used_at"`
|
||||||
|
ExpiresAt *time.Time `json:"expires_at"`
|
||||||
|
RevokedAt *time.Time `json:"revoked_at"`
|
||||||
|
CreatedByName *string `json:"created_by_name,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewHandler(create *useCases.CreateAPIKeyUseCase, list *useCases.ListAPIKeysUseCase, revoke *useCases.RevokeAPIKeyUseCase) *Handler {
|
||||||
|
return &Handler{CreateUseCase: create, ListUseCase: list, RevokeUseCase: revoke}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *Handler) Create(w http.ResponseWriter, r *http.Request) {
|
||||||
|
var request CreateAPIKeyRequest
|
||||||
|
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.CreateUseCase.CreateAPIKey(useCases.CreateAPIKeyCommand{
|
||||||
|
UserID: userId,
|
||||||
|
Name: request.Name,
|
||||||
|
ExpiresAt: request.ExpiresAt,
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
if errors.Is(err, domain.ErrExpiryNotInFuture) {
|
||||||
|
http.Error(w, apperr.APIKeyExpiryErrorMessage, http.StatusBadRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
http.Error(w, "Internal server error", http.StatusInternalServerError)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
body, err := json.Marshal(createdKeyResponse{
|
||||||
|
ID: created.Key.ID,
|
||||||
|
Name: created.Key.Name,
|
||||||
|
Prefix: created.Key.Prefix,
|
||||||
|
Key: created.RawKey,
|
||||||
|
CreatedAt: created.Key.CreatedAt,
|
||||||
|
ExpiresAt: created.Key.ExpiresAt,
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
http.Error(w, "Internal server error", http.StatusInternalServerError)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
w.Header().Set("Cache-Control", "no-store")
|
||||||
|
w.WriteHeader(http.StatusCreated)
|
||||||
|
_, _ = w.Write(body)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *Handler) List(w http.ResponseWriter, r *http.Request) {
|
||||||
|
userId, ok := claims.UserId(r)
|
||||||
|
if !ok {
|
||||||
|
http.Error(w, apperr.UnauthorizedErrorMessage, http.StatusUnauthorized)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
entries, err := h.ListUseCase.ListAPIKeys(userId)
|
||||||
|
if err != nil {
|
||||||
|
if errors.Is(err, user.ErrUserNotFound) {
|
||||||
|
http.Error(w, apperr.UnauthorizedErrorMessage, http.StatusUnauthorized)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
http.Error(w, "Internal server error", http.StatusInternalServerError)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
items := make([]keyListItem, 0, len(entries))
|
||||||
|
for _, entry := range entries {
|
||||||
|
key := entry.Key
|
||||||
|
item := keyListItem{
|
||||||
|
ID: key.ID,
|
||||||
|
UserID: key.UserID,
|
||||||
|
Name: key.Name,
|
||||||
|
Prefix: key.Prefix,
|
||||||
|
Status: entry.Status,
|
||||||
|
CreatedAt: key.CreatedAt,
|
||||||
|
LastUsedAt: key.LastUsedAt,
|
||||||
|
ExpiresAt: key.ExpiresAt,
|
||||||
|
RevokedAt: key.RevokedAt,
|
||||||
|
}
|
||||||
|
if entry.ListsCreator {
|
||||||
|
item.CreatedByName = &entry.CreatorName
|
||||||
|
}
|
||||||
|
items = append(items, item)
|
||||||
|
}
|
||||||
|
|
||||||
|
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)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *Handler) Revoke(w http.ResponseWriter, r *http.Request) {
|
||||||
|
id, err := strconv.ParseUint(chi.URLParam(r, "id"), 10, 32)
|
||||||
|
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
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := h.RevokeUseCase.RevokeAPIKey(userId, uint32(id)); err != nil {
|
||||||
|
switch {
|
||||||
|
case errors.Is(err, domain.ErrAPIKeyNotFound):
|
||||||
|
http.Error(w, apperr.APIKeyNotFoundErrorMessage, http.StatusNotFound)
|
||||||
|
case errors.Is(err, user.ErrUserNotFound):
|
||||||
|
http.Error(w, apperr.UnauthorizedErrorMessage, http.StatusUnauthorized)
|
||||||
|
default:
|
||||||
|
http.Error(w, "Internal server error", http.StatusInternalServerError)
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
w.WriteHeader(http.StatusNoContent)
|
||||||
|
}
|
||||||
@@ -12,6 +12,7 @@ import (
|
|||||||
"log"
|
"log"
|
||||||
"net/http"
|
"net/http"
|
||||||
"strconv"
|
"strconv"
|
||||||
|
"time"
|
||||||
|
|
||||||
"github.com/go-chi/chi/v5"
|
"github.com/go-chi/chi/v5"
|
||||||
)
|
)
|
||||||
@@ -41,6 +42,53 @@ func NewHandler(create *useCases.CreateArticleUseCase, get *useCases.GetArticleU
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type articleResponse struct {
|
||||||
|
ID uint32 `json:"id"`
|
||||||
|
Title string `json:"title"`
|
||||||
|
Body json.RawMessage `json:"body"`
|
||||||
|
BodyFormat domain.BodyFormat `json:"body_format"`
|
||||||
|
IsOnline bool `json:"is_online"`
|
||||||
|
CreatedAt time.Time `json:"created_at"`
|
||||||
|
UpdatedAt time.Time `json:"updated_at"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func toArticleResponse(article domain.Article, format domain.BodyFormat) (articleResponse, error) {
|
||||||
|
body := json.RawMessage(article.Body)
|
||||||
|
if format != domain.BodyFormatJSON {
|
||||||
|
encoded, err := json.Marshal(article.Body)
|
||||||
|
if err != nil {
|
||||||
|
return articleResponse{}, err
|
||||||
|
}
|
||||||
|
body = encoded
|
||||||
|
}
|
||||||
|
return articleResponse{
|
||||||
|
ID: article.ID,
|
||||||
|
Title: article.Title,
|
||||||
|
Body: body,
|
||||||
|
BodyFormat: format,
|
||||||
|
IsOnline: article.IsOnline,
|
||||||
|
CreatedAt: article.CreatedAt,
|
||||||
|
UpdatedAt: article.UpdatedAt,
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func encodeArticle(article domain.Article, format domain.BodyFormat) ([]byte, error) {
|
||||||
|
response, err := toArticleResponse(article, format)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return json.Marshal(response)
|
||||||
|
}
|
||||||
|
|
||||||
|
func parseBodyFormat(w http.ResponseWriter, r *http.Request) (domain.BodyFormat, bool) {
|
||||||
|
format, err := domain.ParseBodyFormat(r.URL.Query().Get("format"))
|
||||||
|
if err != nil {
|
||||||
|
http.Error(w, apperr.ArticleBodyFormatErrorMessage, http.StatusBadRequest)
|
||||||
|
return "", false
|
||||||
|
}
|
||||||
|
return format, true
|
||||||
|
}
|
||||||
|
|
||||||
func parseArticleId(r *http.Request) (uint32, error) {
|
func parseArticleId(r *http.Request) (uint32, error) {
|
||||||
id, err := strconv.ParseUint(chi.URLParam(r, "id"), 10, 32)
|
id, err := strconv.ParseUint(chi.URLParam(r, "id"), 10, 32)
|
||||||
return uint32(id), err
|
return uint32(id), err
|
||||||
@@ -53,11 +101,16 @@ func (h *Handler) GetArticle(w http.ResponseWriter, r *http.Request) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
format, ok := parseBodyFormat(w, r)
|
||||||
|
if !ok {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
var article domain.Article
|
var article domain.Article
|
||||||
if h.callerIsVerified(r) {
|
if h.callerIsVerified(r) {
|
||||||
article, err = h.GetUseCase.GetArticle(id)
|
article, err = h.GetUseCase.GetArticle(id, format)
|
||||||
} else {
|
} else {
|
||||||
article, err = h.GetUseCase.GetOnlineArticle(id)
|
article, err = h.GetUseCase.GetOnlineArticle(id, format)
|
||||||
}
|
}
|
||||||
if err != nil {
|
if err != nil {
|
||||||
if errors.Is(err, domain.ErrArticleNotFound) {
|
if errors.Is(err, domain.ErrArticleNotFound) {
|
||||||
@@ -68,7 +121,7 @@ func (h *Handler) GetArticle(w http.ResponseWriter, r *http.Request) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
articleJson, err := json.Marshal(article)
|
articleJson, err := encodeArticle(article, format)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
http.Error(w, "Failed to encode response", http.StatusInternalServerError)
|
http.Error(w, "Failed to encode response", http.StatusInternalServerError)
|
||||||
return
|
return
|
||||||
@@ -80,6 +133,11 @@ func (h *Handler) GetArticle(w http.ResponseWriter, r *http.Request) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (h *Handler) PostArticle(w http.ResponseWriter, r *http.Request) {
|
func (h *Handler) PostArticle(w http.ResponseWriter, r *http.Request) {
|
||||||
|
format, ok := parseBodyFormat(w, r)
|
||||||
|
if !ok {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
var localArticle PostArticle
|
var localArticle PostArticle
|
||||||
if err := json.NewDecoder(r.Body).Decode(&localArticle); err != nil {
|
if err := json.NewDecoder(r.Body).Decode(&localArticle); err != nil {
|
||||||
http.Error(w, apperr.BodyErrorMessage, http.StatusBadRequest)
|
http.Error(w, apperr.BodyErrorMessage, http.StatusBadRequest)
|
||||||
@@ -92,8 +150,9 @@ func (h *Handler) PostArticle(w http.ResponseWriter, r *http.Request) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
createdArticle, err := h.CreateUseCase.CreateArticle(useCases.CreateArticleCommand{
|
createdArticle, err := h.CreateUseCase.CreateArticle(useCases.CreateArticleCommand{
|
||||||
Title: localArticle.Title,
|
Title: localArticle.Title,
|
||||||
Body: localArticle.Body,
|
Body: localArticle.Body,
|
||||||
|
Format: format,
|
||||||
})
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
if errors.Is(err, domain.ErrInvalidTitle) {
|
if errors.Is(err, domain.ErrInvalidTitle) {
|
||||||
@@ -104,16 +163,7 @@ func (h *Handler) PostArticle(w http.ResponseWriter, r *http.Request) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
articleJson, err := json.Marshal(createdArticle)
|
writeArticleJsonResponse(w, http.StatusCreated, createdArticle, format)
|
||||||
if err != nil {
|
|
||||||
http.Error(w, "Failed to encode response", http.StatusInternalServerError)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
w.WriteHeader(http.StatusCreated)
|
|
||||||
if _, err := w.Write(articleJson); err != nil {
|
|
||||||
log.Printf("Failed to write response: %v", err)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func writeArticleErrorResponse(w http.ResponseWriter, err error) {
|
func writeArticleErrorResponse(w http.ResponseWriter, err error) {
|
||||||
@@ -124,13 +174,16 @@ func writeArticleErrorResponse(w http.ResponseWriter, err error) {
|
|||||||
http.Error(w, "Internal server error", http.StatusInternalServerError)
|
http.Error(w, "Internal server error", http.StatusInternalServerError)
|
||||||
}
|
}
|
||||||
|
|
||||||
func writeArticleJsonResponse(w http.ResponseWriter, article domain.Article) {
|
func writeArticleJsonResponse(w http.ResponseWriter, status int, article domain.Article, format domain.BodyFormat) {
|
||||||
articleJson, err := json.Marshal(article)
|
articleJson, err := encodeArticle(article, format)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
http.Error(w, "Failed to encode response", http.StatusInternalServerError)
|
http.Error(w, "Failed to encode response", http.StatusInternalServerError)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if status != http.StatusOK {
|
||||||
|
w.WriteHeader(status)
|
||||||
|
}
|
||||||
if _, err := w.Write(articleJson); err != nil {
|
if _, err := w.Write(articleJson); err != nil {
|
||||||
log.Printf("Failed to write response: %v", err)
|
log.Printf("Failed to write response: %v", err)
|
||||||
}
|
}
|
||||||
@@ -143,13 +196,18 @@ func (h *Handler) setIsOnline(w http.ResponseWriter, r *http.Request, isOnline b
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
updatedArticle, err := h.UpdateUseCase.UpdateIsOnline(id, isOnline)
|
format, ok := parseBodyFormat(w, r)
|
||||||
|
if !ok {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
updatedArticle, err := h.UpdateUseCase.UpdateIsOnline(id, isOnline, format)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
writeArticleErrorResponse(w, err)
|
writeArticleErrorResponse(w, err)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
writeArticleJsonResponse(w, updatedArticle)
|
writeArticleJsonResponse(w, http.StatusOK, updatedArticle, format)
|
||||||
}
|
}
|
||||||
|
|
||||||
type UpdateArticleBody struct {
|
type UpdateArticleBody struct {
|
||||||
@@ -163,6 +221,11 @@ func (h *Handler) UpdateArticleBody(w http.ResponseWriter, r *http.Request) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
format, ok := parseBodyFormat(w, r)
|
||||||
|
if !ok {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
var localArticle UpdateArticleBody
|
var localArticle UpdateArticleBody
|
||||||
if err := json.NewDecoder(r.Body).Decode(&localArticle); err != nil {
|
if err := json.NewDecoder(r.Body).Decode(&localArticle); err != nil {
|
||||||
http.Error(w, apperr.BodyErrorMessage, http.StatusBadRequest)
|
http.Error(w, apperr.BodyErrorMessage, http.StatusBadRequest)
|
||||||
@@ -174,13 +237,13 @@ func (h *Handler) UpdateArticleBody(w http.ResponseWriter, r *http.Request) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
updatedArticle, err := h.UpdateUseCase.UpdateBody(id, localArticle.Body)
|
updatedArticle, err := h.UpdateUseCase.UpdateBody(id, localArticle.Body, format)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
writeArticleErrorResponse(w, err)
|
writeArticleErrorResponse(w, err)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
writeArticleJsonResponse(w, updatedArticle)
|
writeArticleJsonResponse(w, http.StatusOK, updatedArticle, format)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (h *Handler) PublishArticle(w http.ResponseWriter, r *http.Request) {
|
func (h *Handler) PublishArticle(w http.ResponseWriter, r *http.Request) {
|
||||||
@@ -206,19 +269,34 @@ func (h *Handler) callerIsVerified(r *http.Request) bool {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (h *Handler) ListArticles(w http.ResponseWriter, r *http.Request) {
|
func (h *Handler) ListArticles(w http.ResponseWriter, r *http.Request) {
|
||||||
|
format, ok := parseBodyFormat(w, r)
|
||||||
|
if !ok {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
var articles []domain.Article
|
var articles []domain.Article
|
||||||
var err error
|
var err error
|
||||||
if h.callerIsVerified(r) {
|
if h.callerIsVerified(r) {
|
||||||
articles, err = h.ListUseCase.ListAllArticles()
|
articles, err = h.ListUseCase.ListAllArticles(format)
|
||||||
} else {
|
} else {
|
||||||
articles, err = h.ListUseCase.ListOnlineArticles()
|
articles, err = h.ListUseCase.ListOnlineArticles(format)
|
||||||
}
|
}
|
||||||
if err != nil {
|
if err != nil {
|
||||||
http.Error(w, "Failed to retrieve articles", http.StatusInternalServerError)
|
http.Error(w, "Failed to retrieve articles", http.StatusInternalServerError)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
articlesJson, err := json.Marshal(articles)
|
responses := make([]articleResponse, 0, len(articles))
|
||||||
|
for _, article := range articles {
|
||||||
|
response, err := toArticleResponse(article, format)
|
||||||
|
if err != nil {
|
||||||
|
http.Error(w, "Failed to encode response", http.StatusInternalServerError)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
responses = append(responses, response)
|
||||||
|
}
|
||||||
|
|
||||||
|
articlesJson, err := json.Marshal(responses)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
http.Error(w, "Failed to encode response", http.StatusInternalServerError)
|
http.Error(w, "Failed to encode response", http.StatusInternalServerError)
|
||||||
return
|
return
|
||||||
|
|||||||
@@ -1,121 +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
|
|
||||||
DeleteUseCase *useCases.DeleteImageUseCase
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewHandler(create *useCases.CreateImageUseCase, get *useCases.GetArticleUseCase, update *useCases.UpdateArticleUseCase, deleteUseCase *useCases.DeleteImageUseCase) *Handler {
|
|
||||||
return &Handler{
|
|
||||||
CreateUseCase: create,
|
|
||||||
GetUseCase: get,
|
|
||||||
UpdateUseCase: update,
|
|
||||||
DeleteUseCase: deleteUseCase,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
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{"id": newImage.ID, "location": newImage.Path})
|
|
||||||
if err != nil {
|
|
||||||
writeInternalServerError(w)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
w.WriteHeader(http.StatusCreated)
|
|
||||||
_, _ = w.Write(responseJson)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (h *Handler) DeleteImage(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
|
|
||||||
}
|
|
||||||
|
|
||||||
imageId, err := strconv.ParseUint(chi.URLParam(r, "imageId"), 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
|
|
||||||
}
|
|
||||||
|
|
||||||
if err := h.DeleteUseCase.DeleteImage(uint32(imageId)); err != nil {
|
|
||||||
if errors.Is(err, domainImage.ErrImageNotFound) {
|
|
||||||
http.Error(w, apperr.ImageNotFoundErrorMessage, http.StatusNotFound)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
writeInternalServerError(w)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
w.WriteHeader(http.StatusNoContent)
|
|
||||||
}
|
|
||||||
@@ -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)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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"
|
||||||
|
|
||||||
|
|||||||
@@ -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)
|
||||||
|
}
|
||||||
@@ -10,11 +10,16 @@ import (
|
|||||||
"encoding/json"
|
"encoding/json"
|
||||||
"errors"
|
"errors"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
"strconv"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
|
"github.com/go-chi/chi/v5"
|
||||||
)
|
)
|
||||||
|
|
||||||
type InviteHandler struct {
|
type InviteHandler struct {
|
||||||
CreateInviteUseCase *useCases.CreateInviteUseCase
|
CreateInviteUseCase *useCases.CreateInviteUseCase
|
||||||
|
CancelInviteUseCase *useCases.CancelInviteUseCase
|
||||||
|
RenewInviteUseCase *useCases.RenewInviteUseCase
|
||||||
ListUsersAndInvitesUseCase *useCases.ListUsersAndInvitesUseCase
|
ListUsersAndInvitesUseCase *useCases.ListUsersAndInvitesUseCase
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -44,13 +49,17 @@ type userListItem struct {
|
|||||||
Kind string `json:"kind"`
|
Kind string `json:"kind"`
|
||||||
Username string `json:"username"`
|
Username string `json:"username"`
|
||||||
DisplayName string `json:"display_name"`
|
DisplayName string `json:"display_name"`
|
||||||
|
Email string `json:"email"`
|
||||||
|
Role string `json:"role"`
|
||||||
Status string `json:"status"`
|
Status string `json:"status"`
|
||||||
CreatedAt time.Time `json:"created_at"`
|
CreatedAt time.Time `json:"created_at"`
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewInviteHandler(createInvite *useCases.CreateInviteUseCase, listUsersAndInvites *useCases.ListUsersAndInvitesUseCase) *InviteHandler {
|
func NewInviteHandler(createInvite *useCases.CreateInviteUseCase, cancelInvite *useCases.CancelInviteUseCase, renewInvite *useCases.RenewInviteUseCase, listUsersAndInvites *useCases.ListUsersAndInvitesUseCase) *InviteHandler {
|
||||||
return &InviteHandler{
|
return &InviteHandler{
|
||||||
CreateInviteUseCase: createInvite,
|
CreateInviteUseCase: createInvite,
|
||||||
|
CancelInviteUseCase: cancelInvite,
|
||||||
|
RenewInviteUseCase: renewInvite,
|
||||||
ListUsersAndInvitesUseCase: listUsersAndInvites,
|
ListUsersAndInvitesUseCase: listUsersAndInvites,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -82,23 +91,82 @@ func (h *InviteHandler) CreateInvite(w http.ResponseWriter, r *http.Request) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
writeInviteResponse(w, http.StatusCreated, created)
|
||||||
|
}
|
||||||
|
|
||||||
|
func writeInviteResponse(w http.ResponseWriter, status int, entry invite.Invite) {
|
||||||
body, err := json.Marshal(inviteResponse{
|
body, err := json.Marshal(inviteResponse{
|
||||||
ID: created.ID,
|
ID: entry.ID,
|
||||||
Kind: useCases.EntryKindInvite,
|
Kind: useCases.EntryKindInvite,
|
||||||
Email: created.Email,
|
Email: entry.Email,
|
||||||
Status: string(created.StatusAt(time.Now())),
|
Status: string(entry.StatusAt(time.Now())),
|
||||||
CreatedAt: created.CreatedAt,
|
CreatedAt: entry.CreatedAt,
|
||||||
ExpiresAt: created.ExpiresAt,
|
ExpiresAt: entry.ExpiresAt,
|
||||||
})
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
http.Error(w, "Internal server error", http.StatusInternalServerError)
|
http.Error(w, "Internal server error", http.StatusInternalServerError)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
w.Header().Set("Cache-Control", "no-store")
|
w.Header().Set("Cache-Control", "no-store")
|
||||||
w.WriteHeader(http.StatusCreated)
|
w.WriteHeader(status)
|
||||||
_, _ = w.Write(body)
|
_, _ = 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) {
|
func writeCreateInviteError(w http.ResponseWriter, err error) {
|
||||||
switch {
|
switch {
|
||||||
case errors.Is(err, invite.ErrEmailHasAccount):
|
case errors.Is(err, invite.ErrEmailHasAccount):
|
||||||
@@ -123,7 +191,7 @@ func (h *InviteHandler) ListUsers(w http.ResponseWriter, _ *http.Request) {
|
|||||||
items = append(items, inviteListItem{entry.ID, entry.Kind, entry.Email, entry.Status, entry.CreatedAt})
|
items = append(items, inviteListItem{entry.ID, entry.Kind, entry.Email, entry.Status, entry.CreatedAt})
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
items = append(items, userListItem{entry.ID, entry.Kind, entry.Username, entry.DisplayName, entry.Status, entry.CreatedAt})
|
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)
|
body, err := json.Marshal(items)
|
||||||
|
|||||||
@@ -0,0 +1,100 @@
|
|||||||
|
package middleware
|
||||||
|
|
||||||
|
import (
|
||||||
|
"RenewCMS/api/pkg/apperr"
|
||||||
|
"RenewCMS/internal/domain/apikey"
|
||||||
|
"RenewCMS/internal/infrastructure/useCases"
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"net/http"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/go-chi/jwtauth/v5"
|
||||||
|
"github.com/lestrrat-go/jwx/v2/jwt"
|
||||||
|
)
|
||||||
|
|
||||||
|
const bearerScheme = "bearer "
|
||||||
|
|
||||||
|
type apiKeyIdContextKey struct{}
|
||||||
|
|
||||||
|
func bearerAPIKey(r *http.Request) (string, bool) {
|
||||||
|
header := r.Header.Get("Authorization")
|
||||||
|
if len(header) < len(bearerScheme) || !strings.EqualFold(header[:len(bearerScheme)], bearerScheme) {
|
||||||
|
return "", false
|
||||||
|
}
|
||||||
|
|
||||||
|
credential := strings.TrimSpace(header[len(bearerScheme):])
|
||||||
|
return credential, strings.HasPrefix(credential, apikey.RawKeyPrefix)
|
||||||
|
}
|
||||||
|
|
||||||
|
func apiKeyIdFrom(r *http.Request) (uint32, bool) {
|
||||||
|
id, ok := r.Context().Value(apiKeyIdContextKey{}).(uint32)
|
||||||
|
return id, ok
|
||||||
|
}
|
||||||
|
|
||||||
|
func RequireSession(next http.Handler) http.Handler {
|
||||||
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
if _, isKey := bearerAPIKey(r); isKey {
|
||||||
|
http.Error(w, apperr.SessionRequiredErrorMessage, http.StatusForbidden)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
next.ServeHTTP(w, r)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func APIKeyAuth(authenticate *useCases.AuthenticateAPIKeyUseCase, maxRequests int, window time.Duration) func(http.Handler) http.Handler {
|
||||||
|
limiter := newKeyedRateLimiter(maxRequests, window, apiKeyRateLimitKey)
|
||||||
|
|
||||||
|
return func(next http.Handler) http.Handler {
|
||||||
|
limited := limiter(next)
|
||||||
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
rawKey, isKey := bearerAPIKey(r)
|
||||||
|
if !isKey {
|
||||||
|
next.ServeHTTP(w, r)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
authenticated, err := authenticate.AuthenticateAPIKey(rawKey)
|
||||||
|
if err != nil {
|
||||||
|
writeAPIKeyError(w, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
token, err := sessionTokenFor(authenticated)
|
||||||
|
if err != nil {
|
||||||
|
http.Error(w, "Internal server error", http.StatusInternalServerError)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
ctx := jwtauth.NewContext(r.Context(), token, nil)
|
||||||
|
ctx = context.WithValue(ctx, apiKeyIdContextKey{}, authenticated.Key.ID)
|
||||||
|
limited.ServeHTTP(w, r.WithContext(ctx))
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func writeAPIKeyError(w http.ResponseWriter, err error) {
|
||||||
|
if errors.Is(err, apikey.ErrAPIKeyInvalid) {
|
||||||
|
http.Error(w, apperr.UnauthorizedErrorMessage, http.StatusUnauthorized)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
http.Error(w, "Internal server error", http.StatusInternalServerError)
|
||||||
|
}
|
||||||
|
|
||||||
|
func sessionTokenFor(authenticated useCases.AuthenticatedAPIKey) (jwt.Token, error) {
|
||||||
|
token := jwt.New()
|
||||||
|
if err := token.Set("user_id", float64(authenticated.User.ID)); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if err := token.Set("token_version", float64(authenticated.User.TokenVersion)); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return token, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func apiKeyRateLimitKey(r *http.Request) string {
|
||||||
|
id, _ := apiKeyIdFrom(r)
|
||||||
|
return strconv.FormatUint(uint64(id), 10)
|
||||||
|
}
|
||||||
@@ -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)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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)
|
||||||
|
|||||||
@@ -19,6 +19,22 @@ const TooManyRequestsErrorMessage = "Too many requests. Please try again later."
|
|||||||
const EmailHasAccountErrorMessage = "This address already has an account."
|
const EmailHasAccountErrorMessage = "This address already has an account."
|
||||||
const PendingInviteErrorMessage = "There's already a pending invite for this address."
|
const PendingInviteErrorMessage = "There's already a pending invite for this address."
|
||||||
const InviteNotSentErrorMessage = "Couldn't send the invite. Try again in a moment."
|
const InviteNotSentErrorMessage = "Couldn't send the invite. Try again in a moment."
|
||||||
|
const InviteNotFoundErrorMessage = "Invite not found"
|
||||||
|
const InviteAlreadyAcceptedErrorMessage = "This invite has already been accepted."
|
||||||
const InviteInvalidErrorMessage = "This invite link doesn't work."
|
const InviteInvalidErrorMessage = "This invite link doesn't work."
|
||||||
const InviteExpiredErrorMessage = "This invite has expired."
|
const InviteExpiredErrorMessage = "This invite has expired."
|
||||||
|
const OwnerRequiredErrorMessage = "Only the owner can do this."
|
||||||
const UsernameTakenErrorMessage = "That username is taken. Try another."
|
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."
|
||||||
|
const ArticleBodyFormatErrorMessage = "The format must be one of: markdown, html, json."
|
||||||
|
const APIKeyNotFoundErrorMessage = "API key not found"
|
||||||
|
const APIKeyExpiryErrorMessage = "The expiry must be a date in the future."
|
||||||
|
const SessionRequiredErrorMessage = "This action needs a real session."
|
||||||
@@ -13,6 +13,7 @@ type PublicUser struct {
|
|||||||
CreatedAt time.Time `json:"created_at"`
|
CreatedAt time.Time `json:"created_at"`
|
||||||
UpdatedAt time.Time `json:"updated_at"`
|
UpdatedAt time.Time `json:"updated_at"`
|
||||||
DisplayName string `json:"display_name"`
|
DisplayName string `json:"display_name"`
|
||||||
|
Role user.Role `json:"role"`
|
||||||
}
|
}
|
||||||
|
|
||||||
func New(u user.User) PublicUser {
|
func New(u user.User) PublicUser {
|
||||||
@@ -24,5 +25,6 @@ func New(u user.User) PublicUser {
|
|||||||
CreatedAt: u.CreatedAt,
|
CreatedAt: u.CreatedAt,
|
||||||
UpdatedAt: u.UpdatedAt,
|
UpdatedAt: u.UpdatedAt,
|
||||||
DisplayName: u.DisplayName,
|
DisplayName: u.DisplayName,
|
||||||
|
Role: u.Role,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -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)
|
||||||
|
}
|
||||||
|
}
|
||||||
+119
-6
@@ -1,16 +1,20 @@
|
|||||||
package api
|
package api
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"RenewCMS/api/handlers/apikey"
|
||||||
"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/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"
|
||||||
@@ -30,11 +34,23 @@ func GetHelloWorld(w http.ResponseWriter, _ *http.Request) {
|
|||||||
_, _ = w.Write(msg)
|
_, _ = w.Write(msg)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const (
|
||||||
|
apiKeyMaxRequests = 120
|
||||||
|
apiKeyWindow = time.Minute
|
||||||
|
)
|
||||||
|
|
||||||
|
func (c *UseCases) apiKeyAuth() func(http.Handler) http.Handler {
|
||||||
|
c.apiKeyAuthOnce.Do(func() {
|
||||||
|
c.apiKeyAuthMiddleware = middleware.APIKeyAuth(c.AuthenticateAPIKeyUseCase, apiKeyMaxRequests, apiKeyWindow)
|
||||||
|
})
|
||||||
|
return c.apiKeyAuthMiddleware
|
||||||
|
}
|
||||||
|
|
||||||
func NewArticleRouter(container *UseCases) http.Handler {
|
func NewArticleRouter(container *UseCases) http.Handler {
|
||||||
r := chi.NewRouter()
|
r := chi.NewRouter()
|
||||||
|
r.Use(container.apiKeyAuth())
|
||||||
|
|
||||||
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, container.DeleteImageUseCase)
|
|
||||||
|
|
||||||
r.Group(func(r chi.Router) {
|
r.Group(func(r chi.Router) {
|
||||||
r.Get("/", articleHandler.ListArticles)
|
r.Get("/", articleHandler.ListArticles)
|
||||||
@@ -49,8 +65,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)
|
|
||||||
r.Delete("/{id}/image/{imageId}", imageHandler.DeleteImage)
|
|
||||||
})
|
})
|
||||||
return r
|
return r
|
||||||
}
|
}
|
||||||
@@ -85,11 +99,18 @@ func NewAuthRouter(container *UseCases, isProduction bool, rateLimit config.Auth
|
|||||||
r.Post("/invite/accept", acceptInviteHandler.AcceptInvite)
|
r.Post("/invite/accept", acceptInviteHandler.AcceptInvite)
|
||||||
})
|
})
|
||||||
r.Group(func(r chi.Router) {
|
r.Group(func(r chi.Router) {
|
||||||
|
r.Use(middleware.RequireSession)
|
||||||
r.Use(jwtauth.Verifier(container.Token))
|
r.Use(jwtauth.Verifier(container.Token))
|
||||||
r.Use(jwtauth.Authenticator(container.Token))
|
r.Use(jwtauth.Authenticator(container.Token))
|
||||||
r.Use(middleware.RequireCurrentToken(container.GetUserUseCase))
|
r.Use(middleware.RequireCurrentToken(container.GetUserUseCase))
|
||||||
r.Post("/verify", verificationHandler.Verify)
|
r.Post("/verify", verificationHandler.Verify)
|
||||||
r.Delete("/register", verificationHandler.CancelRegistration)
|
r.Delete("/register", verificationHandler.CancelRegistration)
|
||||||
|
})
|
||||||
|
r.Group(func(r chi.Router) {
|
||||||
|
r.Use(jwtauth.Verifier(container.Token))
|
||||||
|
r.Use(container.apiKeyAuth())
|
||||||
|
r.Use(jwtauth.Authenticator(container.Token))
|
||||||
|
r.Use(middleware.RequireCurrentToken(container.GetUserUseCase))
|
||||||
r.Get("/me", meHandler.Me)
|
r.Get("/me", meHandler.Me)
|
||||||
})
|
})
|
||||||
return r
|
return r
|
||||||
@@ -99,22 +120,110 @@ func NewUserRouter(container *UseCases, rateLimit config.AuthRateLimitSettings,
|
|||||||
r := chi.NewRouter()
|
r := chi.NewRouter()
|
||||||
|
|
||||||
userHandler := user.NewHandler(container.UpdateUserProfileUseCase)
|
userHandler := user.NewHandler(container.UpdateUserProfileUseCase)
|
||||||
inviteHandler := user.NewInviteHandler(container.CreateInviteUseCase, container.ListUsersAndInvitesUseCase)
|
inviteHandler := user.NewInviteHandler(container.CreateInviteUseCase, container.CancelInviteUseCase, container.RenewInviteUseCase, container.ListUsersAndInvitesUseCase)
|
||||||
|
|
||||||
r.Use(jwtauth.Verifier(container.Token))
|
r.Use(jwtauth.Verifier(container.Token))
|
||||||
|
r.Use(container.apiKeyAuth())
|
||||||
r.Use(jwtauth.Authenticator(container.Token))
|
r.Use(jwtauth.Authenticator(container.Token))
|
||||||
r.Use(middleware.RequireCurrentToken(container.GetUserUseCase))
|
r.Use(middleware.RequireCurrentToken(container.GetUserUseCase))
|
||||||
r.Use(middleware.RequireVerifiedUser(container.GetUserUseCase))
|
r.Use(middleware.RequireVerifiedUser(container.GetUserUseCase))
|
||||||
r.Patch("/me", userHandler.UpdateMe)
|
r.Patch("/me", userHandler.UpdateMe)
|
||||||
r.Get("/", inviteHandler.ListUsers)
|
r.Get("/", inviteHandler.ListUsers)
|
||||||
r.Group(func(r chi.Router) {
|
r.Group(func(r chi.Router) {
|
||||||
|
r.Use(middleware.RequireOwner(container.GetUserUseCase))
|
||||||
r.Use(middleware.TrustedProxyRealIP(trustedProxies))
|
r.Use(middleware.TrustedProxyRealIP(trustedProxies))
|
||||||
r.Use(middleware.NewRateLimiter(rateLimit.MaxAttempts, rateLimit.Window))
|
r.Use(middleware.NewRateLimiter(rateLimit.MaxAttempts, rateLimit.Window))
|
||||||
r.Post("/invite", inviteHandler.CreateInvite)
|
r.Post("/invite", inviteHandler.CreateInvite)
|
||||||
|
r.Delete("/invite/{id}", inviteHandler.CancelInvite)
|
||||||
|
r.Post("/invite/{id}/renew", inviteHandler.RenewInvite)
|
||||||
})
|
})
|
||||||
return r
|
return r
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func NewSettingsRouter(container *UseCases) http.Handler {
|
||||||
|
r := chi.NewRouter()
|
||||||
|
|
||||||
|
settingsHandler := settings.NewHandler(container.GetSettingsUseCase)
|
||||||
|
|
||||||
|
r.Use(jwtauth.Verifier(container.Token))
|
||||||
|
r.Use(container.apiKeyAuth())
|
||||||
|
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(middleware.RequireSession)
|
||||||
|
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 NewAPIKeyRouter(container *UseCases) http.Handler {
|
||||||
|
r := chi.NewRouter()
|
||||||
|
|
||||||
|
apiKeyHandler := apikey.NewHandler(container.CreateAPIKeyUseCase, container.ListAPIKeysUseCase, container.RevokeAPIKeyUseCase)
|
||||||
|
|
||||||
|
r.Use(middleware.RequireSession)
|
||||||
|
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.Post("/", apiKeyHandler.Create)
|
||||||
|
r.Get("/", apiKeyHandler.List)
|
||||||
|
r.Delete("/{id}", apiKeyHandler.Revoke)
|
||||||
|
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(container.apiKeyAuth())
|
||||||
|
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()
|
||||||
|
|
||||||
@@ -128,6 +237,10 @@ func InitBackendRoutes(container *UseCases, settings config.Settings) *chi.Mux {
|
|||||||
r.Mount("/article", NewArticleRouter(container))
|
r.Mount("/article", NewArticleRouter(container))
|
||||||
})
|
})
|
||||||
r.Mount("/user", NewUserRouter(container, settings.AuthRateLimit, settings.TrustedProxies))
|
r.Mount("/user", NewUserRouter(container, settings.AuthRateLimit, settings.TrustedProxies))
|
||||||
|
r.Mount("/settings", NewSettingsRouter(container))
|
||||||
|
r.Mount("/media", NewMediaRouter(container))
|
||||||
|
r.Mount("/api-key", NewAPIKeyRouter(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
|
||||||
@@ -154,7 +267,7 @@ func enableCorsIfConfigured(r *chi.Mux, origins []string) {
|
|||||||
}
|
}
|
||||||
r.Use(cors.Handler(cors.Options{
|
r.Use(cors.Handler(cors.Options{
|
||||||
AllowedOrigins: origins,
|
AllowedOrigins: origins,
|
||||||
AllowedMethods: []string{"GET", "POST", "PUT", "DELETE", "OPTIONS"},
|
AllowedMethods: []string{"GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"},
|
||||||
AllowedHeaders: []string{"Accept", "Authorization", "Content-Type", "X-CSRF-Token"},
|
AllowedHeaders: []string{"Accept", "Authorization", "Content-Type", "X-CSRF-Token"},
|
||||||
ExposedHeaders: []string{"Link"},
|
ExposedHeaders: []string{"Link"},
|
||||||
AllowCredentials: false,
|
AllowCredentials: false,
|
||||||
|
|||||||
@@ -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))
|
||||||
|
}
|
||||||
@@ -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
|
||||||
|
}
|
||||||
+26
-5
@@ -8,6 +8,7 @@ import (
|
|||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"log"
|
"log"
|
||||||
|
"net"
|
||||||
"net/http"
|
"net/http"
|
||||||
"os"
|
"os"
|
||||||
"os/signal"
|
"os/signal"
|
||||||
@@ -47,9 +48,20 @@ 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",
|
||||||
|
"RENEWCMS_CONTAINER": "false",
|
||||||
}
|
}
|
||||||
|
|
||||||
|
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)
|
||||||
}
|
}
|
||||||
@@ -62,13 +74,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() {
|
||||||
@@ -119,12 +132,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:
|
||||||
@@ -134,9 +147,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
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,7 @@
|
|||||||
|
services:
|
||||||
|
renewcms:
|
||||||
|
build:
|
||||||
|
context: .
|
||||||
|
args:
|
||||||
|
VERSION: ${VERSION:-dev}
|
||||||
|
image: renewcms:${VERSION:-dev}
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
services:
|
||||||
|
renewcms:
|
||||||
|
image: ${RENEWCMS_IMAGE:-git.floriansylvain.fr/fsylvain/renewcms:beta}
|
||||||
|
restart: unless-stopped
|
||||||
|
env_file:
|
||||||
|
- docker.env
|
||||||
|
environment:
|
||||||
|
DB_FILE: /data/renewcms.db
|
||||||
|
UPLOAD_DIR: /data/uploads
|
||||||
|
RENEWCMS_CONTAINER: "true"
|
||||||
|
ports:
|
||||||
|
- "8080:8080"
|
||||||
|
volumes:
|
||||||
|
- renewcms-data:/data
|
||||||
|
stop_grace_period: 15s
|
||||||
|
healthcheck:
|
||||||
|
test: ["CMD", "wget", "-qO-", "http://127.0.0.1:8080/healthz"]
|
||||||
|
interval: 30s
|
||||||
|
timeout: 5s
|
||||||
|
retries: 3
|
||||||
|
start_period: 10s
|
||||||
|
|
||||||
|
volumes:
|
||||||
|
renewcms-data:
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
PUBLIC_URL=https://cms.example.com
|
||||||
|
JWT_SECRET=replace-with-output-of-openssl-rand-hex-32
|
||||||
|
SMTP_HOST=smtp.example.com
|
||||||
|
SMTP_PORT=465
|
||||||
|
SMTP_LOGIN=noreply@example.com
|
||||||
|
SMTP_PASSWORD=replace-me
|
||||||
|
SMTP_SENDER=noreply@example.com
|
||||||
|
|
||||||
|
ENVIRONMENT=production
|
||||||
|
CORS_ALLOWED_ORIGINS=
|
||||||
|
AUTH_RATE_LIMIT_MAX_ATTEMPTS=5
|
||||||
|
AUTH_RATE_LIMIT_WINDOW_SECONDS=60
|
||||||
|
TRUSTED_PROXIES=
|
||||||
+39
@@ -0,0 +1,39 @@
|
|||||||
|
# API reference
|
||||||
|
|
||||||
|
The full, searchable reference is the Integration page of the running app (`/integration`). It
|
||||||
|
renders `web/src/data/apiCatalogue.ts`, which is the single source for this page. This file is for
|
||||||
|
readers without the UI.
|
||||||
|
|
||||||
|
## Base URL
|
||||||
|
The origin that serves the app, for example `https://cms.example`. Every path starts with `/v1`,
|
||||||
|
for example `https://cms.example/v1/article/`.
|
||||||
|
|
||||||
|
## Authentication
|
||||||
|
- Public routes need nothing: `GET /v1/article/` and `GET /v1/article/{id}`. They return online
|
||||||
|
articles only.
|
||||||
|
- Everything else needs a signed-in browser session (the `jwt` cookie) or an API key:
|
||||||
|
`Authorization: Bearer rcms_...`. Create keys at `/integration/api-keys`. A key acts as its
|
||||||
|
creator, with that user's role, and shows in full once.
|
||||||
|
- A key cannot call `POST /v1/auth/verify`, `DELETE /v1/auth/register`, `/v1/api-key/*` or
|
||||||
|
`/v1/system/*`. Those answer 403 "This action needs a real session." An invalid, unknown, expired
|
||||||
|
or revoked key answers 401, even on public routes.
|
||||||
|
- Each key can make 120 requests per minute. Beyond that: 429 with a `Retry-After` header.
|
||||||
|
|
||||||
|
## Routes a key can call (20)
|
||||||
|
| Group | Routes |
|
||||||
|
| --- | --- |
|
||||||
|
| Articles | GET /v1/article/, GET /v1/article/{id}, POST /v1/article/, PATCH /v1/article/{id}, PATCH /v1/article/{id}/publish, PATCH /v1/article/{id}/unpublish, DELETE /v1/article/{id} |
|
||||||
|
| Media | GET /v1/media/, POST /v1/media/, PATCH /v1/media/{id}, DELETE /v1/media/{id}, POST /v1/media/merge, GET /v1/media/{id}/usage |
|
||||||
|
| Users and invites | GET /v1/user/, PATCH /v1/user/me, POST /v1/user/invite (owner only), DELETE /v1/user/invite/{id} (owner only), POST /v1/user/invite/{id}/renew (owner only), GET /v1/auth/me |
|
||||||
|
| Settings | GET /v1/settings |
|
||||||
|
|
||||||
|
Article routes accept `?format=markdown|html|json` (default `markdown`). `GET /v1/media/` accepts
|
||||||
|
`q`, `hash`, `cursor`, `filter`, `sort` and `limit`.
|
||||||
|
|
||||||
|
## Errors
|
||||||
|
Every error is a plain-text body with one sentence; the status is in the HTTP status line. The
|
||||||
|
statuses are 400, 401, 403, 404, 409, 429 and 500. Messages are listed on the Integration page.
|
||||||
|
|
||||||
|
## Notes
|
||||||
|
- Images in `body` use paths like `/static/uploadedImages/<uuid>.png`. Prefix them with the base URL.
|
||||||
|
- Browsers can call the API only from origins in the server's CORS setting.
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
# API keys
|
||||||
|
|
||||||
|
Developers can authenticate against `/v1` with a named API key sent as `Authorization: Bearer rcms_...` instead of the `jwt` cookie. A key acts with exactly the rights of the user who created it.
|
||||||
|
|
||||||
|
## Managing keys
|
||||||
|
|
||||||
|
Key management needs a real session (the `jwt` cookie from a verified user).
|
||||||
|
|
||||||
|
- `POST /v1/api-key` with `{"name": "ci", "expires_at": "<RFC3339, optional>"}` answers `201` with `id`, `name`, `prefix`, `key`, `created_at`, `expires_at`. The full `key` is shown once and never again.
|
||||||
|
- `GET /v1/api-key` lists the caller's keys (all keys for the owner), newest first, with a `status` of `active`, `expired` or `revoked`.
|
||||||
|
- `DELETE /v1/api-key/{id}` revokes a key and answers `204`. Revoking twice keeps the first `revoked_at`.
|
||||||
|
|
||||||
|
Only the SHA-256 hash and a 12 character prefix are stored.
|
||||||
|
|
||||||
|
## Where a key is accepted
|
||||||
|
|
||||||
|
`/v1/article` (public and protected routes), `/v1/user`, `/v1/media`, `/v1/settings` and `GET /v1/auth/me`. An invalid, expired or revoked `rcms_` key answers `401` and is never treated as anonymous. Each key is limited to 120 requests per minute (`429` with `Retry-After`). `last_used_at` is updated at most once per minute.
|
||||||
|
|
||||||
|
## Session-only routes
|
||||||
|
|
||||||
|
`/v1/api-key`, `POST /v1/auth/verify`, `DELETE /v1/auth/register` and every `/v1/system` route answer `403 This action needs a real session.` to any `rcms_` Bearer header. The public auth routes ignore the header.
|
||||||
|
|
||||||
|
A successful password reset revokes every key of that user.
|
||||||
@@ -0,0 +1,97 @@
|
|||||||
|
# Reading articles
|
||||||
|
|
||||||
|
Every route that returns an article accepts the optional `format` query parameter and returns the article body in that format. Articles are stored as HTML (Tiptap output). Storage and the request bodies of `POST /v1/article/` and `PATCH /v1/article/{id}` stay HTML.
|
||||||
|
|
||||||
|
## Routes that honour `format`
|
||||||
|
|
||||||
|
- `GET /v1/article/`
|
||||||
|
- `GET /v1/article/{id}`
|
||||||
|
- `POST /v1/article/`
|
||||||
|
- `PATCH /v1/article/{id}`
|
||||||
|
- `PATCH /v1/article/{id}/publish`
|
||||||
|
- `PATCH /v1/article/{id}/unpublish`
|
||||||
|
|
||||||
|
Visibility is unchanged: anonymous and unverified callers only see online articles, and an offline article answers `404 Article not found`.
|
||||||
|
|
||||||
|
## The `format` parameter
|
||||||
|
|
||||||
|
| Value | `body` | `body_format` |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| empty or absent | markdown string | `markdown` |
|
||||||
|
| `markdown` | markdown string | `markdown` |
|
||||||
|
| `html` | the stored HTML string | `html` |
|
||||||
|
| `json` | JSON array of blocks | `json` |
|
||||||
|
|
||||||
|
Values are case-insensitive. When `format` is repeated, the first value is used. Any other value answers `400` with the plain-text message `The format must be one of: markdown, html, json.` before any article is read or written. An invalid id is reported first, ahead of the format.
|
||||||
|
|
||||||
|
Breaking change: the default used to be HTML. Clients that need HTML must send `?format=html`. The web interface does so.
|
||||||
|
|
||||||
|
## Article object
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"id": 1,
|
||||||
|
"title": "Backyard Renovation Update",
|
||||||
|
"body": "## Plan\n\nReplace the **old** deck.",
|
||||||
|
"body_format": "markdown",
|
||||||
|
"is_online": true,
|
||||||
|
"created_at": "2026-03-12T09:14:00Z",
|
||||||
|
"updated_at": "2026-09-10T07:00:00Z"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Markdown output
|
||||||
|
|
||||||
|
Headings, bold, italic, links, bullet and ordered lists, blockquotes, fenced code blocks, rules, images and inline code are converted. Anything else is reduced to its text. `script` and `style` content is removed, and the source HTML is never passed through; the only HTML in the output is the alignment wrapper described below. List indentation attributes are dropped. Links with a scheme other than http, https, mailto or tel are reduced to their text. Characters that markdown would read as formatting (`*`, `_`, `` ` ``, `[`, `]`, `<`, `\`) and line starts that would read as a heading, list, quote or rule (`#`, `-`, `+`, `>`, `1.`) are backslash-escaped, so plain text stays plain text. A line break becomes a backslash followed by a newline.
|
||||||
|
|
||||||
|
### Text alignment
|
||||||
|
|
||||||
|
Markdown has no syntax for alignment, so centered, right-aligned and justified paragraphs and headings are wrapped in a `div` with an inline style. The blank lines around the content make CommonMark parse the inside as markdown:
|
||||||
|
|
||||||
|
```markdown
|
||||||
|
<div style="text-align: center">
|
||||||
|
|
||||||
|
A **centered** paragraph
|
||||||
|
|
||||||
|
</div>
|
||||||
|
```
|
||||||
|
|
||||||
|
Left alignment is the default and produces no wrapper. Your markdown renderer must allow raw HTML for the alignment to show (`html: true` in markdown-it); otherwise the wrapper tags appear as text, and a client that does not want them can request `?format=json` instead, where the alignment is a field.
|
||||||
|
|
||||||
|
## JSON block schema
|
||||||
|
|
||||||
|
`body` is a native JSON array. Every block has a `type`.
|
||||||
|
|
||||||
|
| Block | Fields |
|
||||||
|
| --- | --- |
|
||||||
|
| `heading` | `level` (1 to 6), `align` (only when `center`, `right` or `justify`), `children` (text nodes) |
|
||||||
|
| `paragraph` | `align` (only when `center`, `right` or `justify`), `children` (text nodes, empty array for an empty paragraph) |
|
||||||
|
| `list` | `ordered` (boolean), `items` (array of items, each an array of blocks) |
|
||||||
|
| `blockquote` | `children` (blocks) |
|
||||||
|
| `code` | `language` (empty string when unknown), `text` |
|
||||||
|
| `hr` | none |
|
||||||
|
| `image` | `src`, `alt` (empty string when missing) |
|
||||||
|
|
||||||
|
Text node: `{"type":"text","text":"...","marks":[...]}`. `marks` is always an array, listed outermost first. A mark is `{"type":"bold"}`, `{"type":"italic"}` or `{"type":"link","href":"..."}`. A line break becomes a `"\n"` inside the text. Adjacent text with identical marks is merged. Inline code, underline, strike-through and other formatting degrade to plain text. An image inside a paragraph becomes its own block and splits the paragraph. An empty body is `[]`.
|
||||||
|
|
||||||
|
Example for `<h2>Plan</h2><p>Replace the <strong>old</strong> deck.</p>`:
|
||||||
|
|
||||||
|
```json
|
||||||
|
[
|
||||||
|
{"type":"heading","level":2,"children":[{"type":"text","text":"Plan","marks":[]}]},
|
||||||
|
{"type":"paragraph","children":[
|
||||||
|
{"type":"text","text":"Replace the ","marks":[]},
|
||||||
|
{"type":"text","text":"old","marks":[{"type":"bold"}]},
|
||||||
|
{"type":"text","text":" deck.","marks":[]}
|
||||||
|
]}
|
||||||
|
]
|
||||||
|
```
|
||||||
|
|
||||||
|
## Errors
|
||||||
|
|
||||||
|
| Status | Body |
|
||||||
|
| --- | --- |
|
||||||
|
| `400` | `The server expects the ID to be in the format of an unsigned 32-bit integer (uint32).` for an invalid id |
|
||||||
|
| `400` | `The format must be one of: markdown, html, json.` for an unsupported format |
|
||||||
|
| `404` | `Article not found` |
|
||||||
|
| `500` | `Internal server error` when the body cannot be converted |
|
||||||
@@ -26,8 +26,14 @@ Nothing under `internal/` imports `api/`.
|
|||||||
| Package | Role |
|
| Package | Role |
|
||||||
|---|---|
|
|---|---|
|
||||||
| `api/handlers/user` | Authenticated user endpoints: profile update (`UpdateMe`) and the users list with invitations (`CreateInvite`, `ListUsers`). |
|
| `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. |
|
| `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
|
||||||
|
|
||||||
```
|
```
|
||||||
|
|||||||
@@ -30,9 +30,13 @@ Copy [`.env.example`](../.env.example) to `.env` to get started. When a required
|
|||||||
| `AUTH_RATE_LIMIT_MAX_ATTEMPTS` | `5` | Maximum number of requests a single client IP may send to `POST /v1/auth/login`, `POST /v1/auth/password-reset` or the invite-accept pair (`GET /v1/auth/invite` and `POST /v1/auth/invite/accept`, sharing one counter) within the window, tracked independently per route. |
|
| `AUTH_RATE_LIMIT_MAX_ATTEMPTS` | `5` | Maximum number of requests a single client IP may send to `POST /v1/auth/login`, `POST /v1/auth/password-reset` or the invite-accept pair (`GET /v1/auth/invite` and `POST /v1/auth/invite/accept`, sharing one counter) within the window, tracked independently per route. |
|
||||||
| `AUTH_RATE_LIMIT_WINDOW_SECONDS` | `60` | Length, in seconds, of the fixed rate-limit window for the routes above. |
|
| `AUTH_RATE_LIMIT_WINDOW_SECONDS` | `60` | Length, in seconds, of the fixed rate-limit window for the routes above. |
|
||||||
| `TRUSTED_PROXIES` | *(empty)* | Semicolon-separated list of exact IP addresses (no CIDR) of reverse proxies allowed to supply the client IP via `X-Real-IP` for the rate limiting of the routes above. When a request's connection address is not in this list, any `X-Real-IP` or `X-Forwarded-For` header it sends is ignored and the connection address is used instead. See [deployment.md](deployment.md). |
|
| `TRUSTED_PROXIES` | *(empty)* | Semicolon-separated list of exact IP addresses (no CIDR) of reverse proxies allowed to supply the client IP via `X-Real-IP` for the rate limiting of the routes above. When a request's connection address is not in this list, any `X-Real-IP` or `X-Forwarded-For` header it sends is ignored and the connection address is used instead. See [deployment.md](deployment.md). |
|
||||||
|
| `RENEWCMS_CONTAINER` | `false` | Set to `true` (case-insensitive; any other value means `false`) when the app runs in a container. Settings then tells the owner to update by pulling a new image instead of offering browser updates, and `can_apply` is always `false`. The Dockerfile and `docker-compose.yml` set it to `true`. Update checks still work. |
|
||||||
|
| `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
-1
@@ -8,7 +8,9 @@ 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.
|
||||||
|
|
||||||
|
To run it in a container instead, see [docker.md](docker.md). The published image `git.floriansylvain.fr/fsylvain/renewcms` is upgraded with `docker compose pull && docker compose up -d`. Tags are `vX.Y.Z`, `X.Y.Z`, `X.Y` and `latest` for a stable release, and `vX.Y.Z-<pre>`, `X.Y.Z-<pre>` and the moving `<pre-name>` (`beta`, `rc`) for a pre-release, which never moves `latest`. Maintainers publish with `task docker:publish` after `docker login git.floriansylvain.fr`; there is no CI. See [Maintainer: publishing](docker.md#maintainer-publishing).
|
||||||
|
|
||||||
## 1. Build
|
## 1. Build
|
||||||
|
|
||||||
@@ -19,8 +21,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. In Docker (`RENEWCMS_CONTAINER=true`) browser updates are not offered; Settings tells the owner to pull a new image instead, see [docker.md](docker.md).
|
||||||
|
|
||||||
|
### 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:
|
||||||
|
|||||||
+10
-4
@@ -25,19 +25,25 @@ 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` | 22 | `source/RenewCMS Screens Back-office.dc.html` |
|
| [Editor](screens/editor.md) | `/article/:id/edit` | 22 | `source/RenewCMS Screens Back-office.dc.html` |
|
||||||
| [Integration](screens/integration.md) | `/integration` | 2 | `source/RenewCMS Screens Back-office.dc.html` |
|
| [Media](screens/media.md) | `/media` | 41 | `source/RenewCMS Screens Back-office.dc.html` |
|
||||||
| [Users](screens/users.md) | `/users` | 10 | `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` | 8 | `source/RenewCMS Screens Back-office.dc.html` |
|
||||||
|
| [API keys](screens/integration-api-keys.md) | `/integration/api-keys` | 12 | `source/RenewCMS Screens API keys.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` |
|
| [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` |
|
| [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/IntegrationPage.dc.html` and `source/ApiKeysPage.dc.html`: the page components for the Integration and API keys screens (imported by `AppFrame.dc.html`). They hold 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 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 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".
|
- `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).
|
||||||
+95
-16
@@ -7,8 +7,10 @@
|
|||||||
| 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 (a bottom sheet below md) | displayName?, username, email | logout | none | DashboardShell |
|
| UserMenu | UDropdownMenu, UButton, UAvatar (a bottom sheet below md) | displayName?, username, email | logout | none | DashboardShell |
|
||||||
| UsersTable | UTable | rows: UserRow[], loading | none | none | Users (md and up) |
|
| UsersTable | UTable | rows: UserRow[], loading, canManage: boolean, busyIds: Set | cancel-invite, renew-invite | none | Users (md and up) |
|
||||||
| UserCardList | custom list | same as UsersTable | none | none | Users (below md) |
|
| 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 |
|
| InviteStatusBadge | UBadge | status: 'accepted'\|'pending'\|'expired' | none | none | Users |
|
||||||
| InviteUserModal | UModal, UForm, UFormField, UInput | none | invited(invite) | 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 |
|
| ProfileCard | custom card (border, padding, optional footer strip) | title, description | none | default, footer | Profile |
|
||||||
@@ -28,7 +30,12 @@
|
|||||||
| PasswordStrengthHint | custom (in UFormField #help) | rules: { label, met }[], showErrors: boolean | none | none | Register, Reset, Accept invite |
|
| 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, Accept invite, 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 | UCollapsible, UBadge, UTable, UTabs | method: 'GET'\|'POST'\|'PATCH'\|'DELETE', path, description, access, keyAccess, body?, examples: { fetch, curl, response }, errors, sessionOnly? | none | none | Integration |
|
||||||
|
| SectionIndex | custom nav (desktop), USelectMenu "Jump to" (mobile) | sections: { id, label }[], active: string | jump | none | Integration |
|
||||||
|
| SessionOnlyGroup | UAlert-style note + list rows | routes: { method, path }[] | none | none | Integration |
|
||||||
|
| ApiKeysTable | UTable, UBadge | keys: ApiKey[], showCreatedBy: boolean | revoke | none | API keys |
|
||||||
|
| CreateApiKeyModal | UModal, UForm, UFormField, UInput | open: boolean | create | none | API keys |
|
||||||
|
| ApiKeyReveal | UModal, UAlert, UButton | key: string | done | none | API keys |
|
||||||
| 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 |
|
||||||
@@ -45,7 +52,7 @@ These are the RenewCMS components, built from the primitives on the first page .
|
|||||||
|
|
||||||
### AuthShell
|
### AuthShell
|
||||||
|
|
||||||
One centered card for every public screen. The logo sits above the title, and the form or ResultPanel goes in the slot. Footer links and the theme select sit outside the card, so the card itself stays about one task.
|
One centered card for every public screen. The logo sits above the title, and the form or ResultPanel goes in the slot. Footer links, the language chip and the theme select sit outside the card, so the card itself stays about one task.
|
||||||
|
|
||||||
Log in Welcome back. Log in to manage your articles.
|
Log in Welcome back. Log in to manage your articles.
|
||||||
|
|
||||||
@@ -53,7 +60,7 @@ default slot
|
|||||||
|
|
||||||
Forgot password? System
|
Forgot password? System
|
||||||
|
|
||||||
Built from Custom layout component AuthShell.vue : a UPageCard variant="outline" inside a centered main , with AppLogo , and UColorModeSelect size="sm" in the footer. Forms inside it use UForm rather than UAuthForm , because every screen needs states (such as 403, 429 and an inline login during verification) that UAuthForm doesn't expose.
|
Built from Custom layout component AuthShell.vue : a UPageCard variant="outline" inside a centered main , with AppLogo , and UColorModeSelect size="sm" in the footer, next to the language chip (see LanguageSwitcher). Forms inside it use UForm rather than UAuthForm , because every screen needs states (such as 403, 429 and an inline login during verification) that UAuthForm doesn't expose.
|
||||||
|
|
||||||
Props, slots Props title: string , description?: string . Slots default , notice (an alert above the title, for session expired or password changed), footer (links). No emits.
|
Props, slots Props title: string , description?: string . Slots default , notice (an alert above the title, for session expired or password changed), footer (links). No emits.
|
||||||
|
|
||||||
@@ -63,7 +70,7 @@ Responsive 400 px card from sm up, with its top 12 vh from the top. Below sm , t
|
|||||||
|
|
||||||
### DashboardShell
|
### DashboardShell
|
||||||
|
|
||||||
The sidebar has four destinations (Home, Articles, Users, Integration), 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
|
||||||
|
|
||||||
@@ -97,7 +104,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. Superseded: see "UserMenu (changed)" under "Added with the Users and Profile screens".
|
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.
|
||||||
|
|
||||||
@@ -381,24 +388,23 @@ The Product components board was not regenerated for these. They are written fro
|
|||||||
|
|
||||||
### UserMenu (changed)
|
### UserMenu (changed)
|
||||||
|
|
||||||
The chip at the foot of the sidebar no longer logs out on click. It opens the account menu, which lists Profile and Log out.
|
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, the language 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.
|
- **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.
|
- **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, Log out (log-out). The current page's item is highlighted with `--ui-bg-elevated`.
|
- **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, a "Theme" section label, System, Light and Dark (14 px text, a check icon at the right edge on the current choice), a separator, a "Language" section label, English and Français (same row as the theme items, a check icon on the current one), a separator, Log out (log-out). Section labels are 11 px, weight 500, uppercase, letter-spacing .04em, `--ui-text-muted`, padded 6px 8px 2px. 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.
|
- **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 and language items keep the same order, section labels (padded 8px 16px 2px) and separators.
|
||||||
|
- **Language items:** a `menuitemradio` group named by the "Language" label. Each item is labelled with the language's own name (English, Français) and carries `lang="en"` / `lang="fr"`. Choosing one applies the language at once and keeps the menu open, like the theme items. See LanguageSwitcher.
|
||||||
- **Keyboard:** Escape or a click outside closes it. Arrow keys move between items.
|
- **Keyboard:** Escape or a click outside closes it. Arrow keys move between items.
|
||||||
- **Open question:** the shipped menu also offers System, Light and Dark. The board omits them. See [profile.md](screens/profile.md).
|
- 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)
|
### 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".
|
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
|
### UsersTable, UserCardList
|
||||||
|
|
||||||
Columns Username, Invite status, Created (sorted descending, with an arrow-down icon on the header). Grid `minmax(0,1fr) 160px 160px`, 36 px header on `--ui-bg-elevated`, 44 px rows with a top border. Below md the same rows become cards with a 68 px minimum height: the name line, then the badge and "Created {date}". There are no row actions.
|
Superseded by "UsersTable, UserCardList (changed)" below.
|
||||||
|
|
||||||
A row's name cell shows the display name first (medium weight, highlighted), the username beside it in muted text, and a mono "you" tag on the current user's row. Invite rows show the email, regular weight, toned. The row of a just-sent invite has `--ui-bg-elevated`.
|
|
||||||
|
|
||||||
Skeleton rows appear after 150 ms of loading.
|
Skeleton rows appear after 150 ms of loading.
|
||||||
|
|
||||||
@@ -734,4 +740,77 @@ 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 menuitemradio , with aria-checked on the current choice. The segmented variant is a radiogroup named "Theme".
|
||||||
|
|
||||||
|
### LanguageSwitcher
|
||||||
|
|
||||||
|
Two choices: English and Français. Each is always written in its own language, whatever the interface language. It appears in two places and never as a form select.
|
||||||
|
|
||||||
|
- **Account menu (signed in):** a "Language" section between the theme items and Log out. See UserMenu (changed).
|
||||||
|
- **Auth footer (signed out):** a chip beside the System theme chip, in the footer outside the card. The chip is 28 px high on desktop and 44 px on mobile, 8 px side padding, 1 px `--ui-border-accented` border, `--ui-text-toned` text, a 14 px lucide `languages` icon, then the current language's own name. `aria-haspopup="menu"`, `aria-expanded`, `aria-label` "Language: English". While open it takes `--ui-bg-elevated`. The footer sits at the right with an 8 px gap between the two chips.
|
||||||
|
- **Auth popover:** opens above the chip (bottom 36 px, right-aligned, 168 px wide), `--ui-bg`, 1 px `--ui-border`, `--rc-shadow-pop`, 4 px padding, `role="menu"` named "Language". Rows are 32 px (44 px on mobile), 14 px text, `menuitemradio` with `lang`, a 16 px check icon at the right edge on the current one. Choosing a row applies the language and closes the popover; Escape or an outside click closes it without changing anything.
|
||||||
|
- The choice persists across reloads and applies to every screen at once.
|
||||||
|
|
||||||
|
## 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, pendingTag?, action? (in-block Restart, Ready only) | 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) |
|
||||||
@@ -11,12 +11,15 @@ 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 |
|
| `/integration/api-keys` | DashboardShell | verified | ApiKeysPage + CreateApiKeyModal | GET /v1/api-key · POST /v1/api-key · DELETE /v1/api-key/{id} |
|
||||||
|
| `/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 |
|
| `/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* |
|
| `/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 |
|
||||||
|
|||||||
@@ -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
|
||||||
@@ -183,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"
|
||||||
|
|||||||
@@ -40,3 +40,17 @@ The greeting reads "Good morning, {name}", where the name is the display name wh
|
|||||||
- 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"
|
||||||
@@ -0,0 +1,58 @@
|
|||||||
|
# Integration: API keys
|
||||||
|
|
||||||
|
Route: `/integration/api-keys`. Component: `ApiKeysPage.dc.html`, mounted by `AppFrame`.
|
||||||
|
|
||||||
|
- **Visual reference:** `source/RenewCMS Screens API keys.dc.html`, group "API keys", drawn by `source/ApiKeysPage.dc.html` (open it in a browser; each state is drawn at desktop and mobile, with a light/dark toggle).
|
||||||
|
|
||||||
|
## API
|
||||||
|
`POST /v1/api-key` · `GET /v1/api-key` · `DELETE /v1/api-key/{id}`. Access: Session only. An API key cannot manage keys; with a key these routes answer 403 "This action needs a real session."
|
||||||
|
- `POST /v1/api-key` body: `name` (string, required, max 60), `expires_at` (RFC3339 string, optional, in the future). A past date answers 400 "The expiry must be a date in the future."
|
||||||
|
- `DELETE /v1/api-key/{id}`: unknown id answers 404 "API key not found".
|
||||||
|
|
||||||
|
## Placement
|
||||||
|
Under Integration, as a sub-page linked from the Authentication section ("Manage API keys") and the sidebar item. Keys exist to call the API and admins can create them; Settings is owner-only today. The mobile top bar has a back arrow that returns to Integration.
|
||||||
|
|
||||||
|
## Content
|
||||||
|
- Columns: Name, Key (prefix, mono), Status (active, expired, revoked), Created by (owners only), Created, Last used, Expires, Revoke. Owners see all keys; admins see their own.
|
||||||
|
- Create key modal: Name (required, up to 60, counter), Expiry date (optional, must be in the future). Errors: "Enter a name." / "Use 60 characters or fewer." / "Choose a date in the future."
|
||||||
|
- The Expiry field is a native date input. The displayed format follows the browser's locale, so there is no custom format. The board draws one example date only.
|
||||||
|
- One-time reveal: warning "You won't be able to see this key again.", monospace key, Copy / Copied, "Closing this window discards the key from the screen. Copy it first." Button "Done".
|
||||||
|
- Revoke: "Revoke this key?" / ""Nightly media import" (rcms_Mq7b…) will stop working right away. Requests that use it answer 401. This can't be undone." Buttons "Keep key", "Revoke key". Toast "Key revoked".
|
||||||
|
- Empty: "No API keys yet" / "Create a key to call the API from a script or service." Error: "Couldn't load your API keys" / "Check your connection and try again."
|
||||||
|
- Note: "Resetting a user's password revokes all of their keys."
|
||||||
|
|
||||||
|
## Mobile: pinned Create key
|
||||||
|
On mobile the "Create key" button is pinned to the bottom of the viewport (44 px high, full width, on a bar with a top border). It shows in Owner list, Admin own keys only, Loading, Empty, Error and Revoked, and is hidden behind every modal state. In Empty it replaces the inline button. The content has bottom padding so nothing sits under the bar, and the toast sits above it. Desktop keeps "Create key" in the page header (and in the Empty card).
|
||||||
|
|
||||||
|
## States
|
||||||
|
|
||||||
|
Names are matched exactly by the visual-check script.
|
||||||
|
|
||||||
|
### Owner: list
|
||||||
|
|
||||||
|
### Admin: own keys only
|
||||||
|
|
||||||
|
### Loading
|
||||||
|
the list request is in flight. Skeleton rows appear only after 150 ms.
|
||||||
|
|
||||||
|
### Empty
|
||||||
|
|
||||||
|
### Error
|
||||||
|
a 500 or network failure on the list request. If a key is created while this state is showing, the list reloads, the new key appears and the error alert is cleared.
|
||||||
|
|
||||||
|
### Create key
|
||||||
|
|
||||||
|
### Create key: validation
|
||||||
|
|
||||||
|
### Create key: name too long
|
||||||
|
|
||||||
|
### One-time reveal
|
||||||
|
|
||||||
|
### One-time reveal: copied
|
||||||
|
|
||||||
|
### Revoke: confirm
|
||||||
|
|
||||||
|
### Revoked
|
||||||
|
|
||||||
|
## Component inventory (Nuxt UI v4)
|
||||||
|
`UTable`, `UBadge`, `UModal` with `UForm`/`UFormField`/`UInput` (type date), `UAlert` color warning, `UButton`, `useClipboard`.
|
||||||
@@ -1,22 +1,82 @@
|
|||||||
# Connect your website
|
# Integration (API reference)
|
||||||
|
|
||||||
- **Route:** `/integration`
|
Route: `/integration`. Component: `IntegrationPage.dc.html`, mounted by `AppFrame`. The API keys sub-page is in `screens/integration-api-keys.md`.
|
||||||
- **API:** none (static)
|
|
||||||
- **Visual reference:** `source/RenewCMS Screens Back-office.dc.html`, group "Integration" (open it in a browser; each state is drawn at desktop and mobile, with a light/dark toggle).
|
|
||||||
|
|
||||||
Written for a developer. The base URL is window.location.origin.
|
- **Visual reference:** `source/RenewCMS Screens Back-office.dc.html`, group "Integration", drawn by `source/IntegrationPage.dc.html` (open it in a browser; each state is drawn at desktop and mobile, with a light/dark toggle).
|
||||||
|
|
||||||
|
## Navigation decision
|
||||||
|
Sticky section index on the right (desktop), "Jump to" select (mobile). A reference is read in one scroll and searched with the browser, so tabs would hide content and break find-in-page and deep links; the index keeps one page with anchors and shows position.
|
||||||
|
|
||||||
|
## Page copy
|
||||||
|
- Header: breadcrumb "Integration", title "API reference", description "Everything a developer needs to build on RenewCMS."
|
||||||
|
- Intro: "RenewCMS is headless: it stores your content and your own code displays it. There are two ways in. Public read-only access lets a website read online articles. API keys let a script or service manage articles, media and users without the back-office."
|
||||||
|
- Base URL: label "Base URL", button "Copy" / "Copied" (2 s, announced).
|
||||||
|
- Authentication, card "Public": "No key needed. Two read-only routes, and only online articles are returned." `GET /v1/article/`, `GET /v1/article/{id}`.
|
||||||
|
- Card "API key": "Send `Authorization: Bearer rcms_…`. Requests act as the user who created the key, with that user's role (owner or admin). A key never has more rights than its creator." CodeBlock tabs curl, fetch (GET /v1/auth/me). "Keys start with `rcms_` and are shown in full once, when you create them." Link "Manage API keys".
|
||||||
|
- Note 1: "A key can't create, list or revoke API keys, log in, register, verify or reset a password, or call anything under `/v1/system`. Those routes answer 403 "This action needs a real session." An invalid, unknown, expired or revoked key answers 401, even on public routes, and so does a key whose user was deleted or unverified."
|
||||||
|
- Note 2: "Each key can make 120 requests per minute. Beyond that the API answers 429 with a `Retry-After` header."
|
||||||
|
- Groups: Articles (7), Media (6), Users and invites (6), Settings (1), Session only (12 routes, 3 sub-groups; every `/v1/system` route is in this group). Session-only banner: "These routes need a signed-in browser session. With an API key they answer 403 "This action needs a real session.""
|
||||||
|
- Errors: "Every error is a plain-text body with a single sentence. The status code is in the HTTP status line, and the Content-Type is text/plain." Table 400, 401, 403, 404, 429, 500 with the real messages below. Sample: a status line plus the text body (`HTTP/1.1 403 Forbidden`, `Content-Type: text/plain`, blank line, `This action needs a real session.`).
|
||||||
|
- Notes: image URL prefix, CORS (existing copy), and "Article routes accept `?format=markdown`, `?format=html` or `?format=json` to choose how `body` is returned. With `json`, `body` is the stored JSON structure. Articles have `body_format: markdown` by default."
|
||||||
|
|
||||||
|
## EndpointCard states
|
||||||
|
- Collapsed (44 px row): method badge, mono path, one-line description, chips, chevron. Desktop is one line; mobile is three (method and path, description, chips).
|
||||||
|
- Expanded: "Request body" table (Name, Type, Required, Rule; "No request body." when empty), tabs fetch / curl / Response with one CodeBlock and Copy, then "Errors": status chip plus one-line caption (also its `title` tooltip).
|
||||||
|
- Session only: dashed border, muted fill, lock icon, "Session only" chip, no method colour, no expand.
|
||||||
|
- Chips: access "Public", "Verified user", "Owner only"; key "API key OK" (success soft) or "Session only" (dashed, muted).
|
||||||
|
- Method badges: GET `--ui-bg-inverted`, POST success soft, PATCH warning soft, DELETE error soft. Existing tokens only.
|
||||||
|
|
||||||
## States
|
## States
|
||||||
|
Desktop 1440×900, mobile 390×844, light and dark. Names are matched exactly by the visual-check script.
|
||||||
|
|
||||||
### Default
|
### 1. Default
|
||||||
|
|
||||||
**Trigger:** Opened from the sidebar or the Home card.
|
### 2. Group scrolled, one card expanded
|
||||||
|
|
||||||
- Breadcrumbs: Integration (mobile title "Integration")
|
### 3a. Copied: base URL
|
||||||
|
|
||||||
### Copied
|
### 3b. Copied: CodeBlock
|
||||||
|
|
||||||
**Trigger:** The base URL was copied. The button reads "Copied" for 2 s and this is announced.
|
### 4. Authentication
|
||||||
|
|
||||||
- Breadcrumbs: Integration (mobile title "Integration")
|
### 5. Session only
|
||||||
- copied: true
|
|
||||||
|
### 6. Errors
|
||||||
|
|
||||||
|
### 7. Navigation
|
||||||
|
|
||||||
|
## Error messages
|
||||||
|
Plain text, one sentence. Used in the table and in the per-endpoint error captions.
|
||||||
|
- 400: "The request cannot be processed due to a mismatch in the format of the body." / "The expiry must be a date in the future."
|
||||||
|
- 401: "You must be logged in to access this resource."
|
||||||
|
- 403: "This action needs a real session." (session-only routes called with a key) / "Only the owner can do this." / "You must verify your account to access this resource."
|
||||||
|
- 404: "Article not found" / "Image not found" / "Invite not found" / "API key not found"
|
||||||
|
- 429: "Too many requests. Please try again later." A per-key limit also sends `Retry-After`.
|
||||||
|
- 500: "Internal server error"
|
||||||
|
- 409, only as examples under their endpoints: `POST /v1/user/invite` "This address already has an account."; `POST /v1/media/merge` "Some of the images to merge changed. Refresh and try again." There is no 409 or 422 row in the table.
|
||||||
|
- 413 and 415 on `POST /v1/media/` keep their earlier plain captions; no real message is known.
|
||||||
|
|
||||||
|
## Request bodies
|
||||||
|
- `POST /v1/article/`: `title` (string, required, 3 to 200 characters), `body` (string, required, max 10000).
|
||||||
|
- `PATCH /v1/article/{id}`: `body` (string, required, max 10000).
|
||||||
|
- `PATCH /v1/media/{id}` (rename): `filename` (string, required).
|
||||||
|
- `POST /v1/media/merge`: `keep_id` (number, required, > 0), `merge_ids` (number[], required, at least 1, each > 0).
|
||||||
|
- `POST /v1/media/`: multipart/form-data, 1 file field (shown as "multipart/form-data, 1 file field").
|
||||||
|
- `PATCH /v1/user/me`: `display_name` (string, required, max 60 characters).
|
||||||
|
- `POST /v1/user/invite`: `email` (string, required, valid email).
|
||||||
|
- `POST /v1/system/update/restart`: optional body `{ "kind": "update" | "restart" }`.
|
||||||
|
|
||||||
|
## Component inventory and Nuxt UI v4
|
||||||
|
- EndpointCard (extended): `UCollapsible` (trigger is a button with aria-expanded), `UBadge` (method, chips, status), `UTable` (body fields), `UTabs` (fetch, curl, Response), CodeBlock.
|
||||||
|
- SectionIndex (new): custom `<nav>` of anchor buttons with `aria-current`; sticky, scroll-spy. Mobile: `USelectMenu` labelled "Jump to".
|
||||||
|
- SessionOnlyGroup (new): `UAlert`-style info note plus list rows; no new colour.
|
||||||
|
- ErrorTable: `UTable`. Info notes: existing note style (or `UAlert` variant `naked`).
|
||||||
|
|
||||||
|
## Assumptions to confirm
|
||||||
|
- Paths not in the brief: `/v1/settings`, `/v1/system/update/*`, `POST /v1/auth/register|verify|logout`.
|
||||||
|
- [to confirm] The multipart field name on `POST /v1/media/` is written as `file` as a placeholder.
|
||||||
|
- Response field names in the samples (for example `articlesUpdated`, `display_name` in the profile response) are illustrative.
|
||||||
|
- Code samples use a simple keyword and string colouring.
|
||||||
|
|
||||||
|
## Tokens
|
||||||
|
No new tokens. Foundations check: colours, radius (0) and spacing come from existing `--ui-*` and `--rc-*` values; every control has a 2 px primary focus ring; index, select and cards are keyboard operable. Open question: the board hard-codes a few pixel sizes, as the other screens do.
|
||||||
@@ -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. |
|
||||||
@@ -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. |
|
||||||
@@ -10,7 +10,7 @@ Once saved it replaces the username everywhere a person is named:
|
|||||||
|
|
||||||
- the sidebar chip and the account menu (name, and the avatar initials)
|
- the sidebar chip and the account menu (name, and the avatar initials)
|
||||||
- the Home greeting ("Good morning, Marta Alves")
|
- the Home greeting ("Good morning, Marta Alves")
|
||||||
- the Users list, with the username beside it
|
- the Display name column of the Users list
|
||||||
- the emails RenewCMS sends, such as "Marta Alves invited you to RenewCMS"
|
- 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.
|
Saving it empty goes back to the username. Logging in still uses the username.
|
||||||
@@ -48,11 +48,17 @@ Desktop: a 224 px popover above the chip, aligned to its left. Mobile: the accou
|
|||||||
| 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) |
|
| 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` |
|
| Item | Profile (circle-user icon), highlighted while on `/profile` |
|
||||||
| Separator | |
|
| Separator | |
|
||||||
|
| Label | "Theme": 11 px, weight 500, uppercase, letter-spacing .04em, muted |
|
||||||
|
| 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 | |
|
||||||
|
| Label | "Language", styled like "Theme" |
|
||||||
|
| Items | English, Français (each in its own language, with `lang`): a radio-style group with a check on the current one; choosing one applies the language at once and keeps the menu open |
|
||||||
|
| Separator | |
|
||||||
| Item | Log out (log-out icon) |
|
| 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.
|
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 has no System, Light or Dark items, while the shipped UserMenu has them. This is an open question, see the notes below.
|
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
|
## States
|
||||||
|
|
||||||
@@ -62,7 +68,7 @@ The board's menu has no System, Light or Dark items, while the shipped UserMenu
|
|||||||
|
|
||||||
- Breadcrumbs: Home (mobile title "Home")
|
- Breadcrumbs: Home (mobile title "Home")
|
||||||
- Page behind the menu: Home, default
|
- Page behind the menu: Home, default
|
||||||
- Menu open, as described above
|
- Menu open, as described above, with the Theme group (System, Light, Dark) and the Language group (English, Français) between Profile and Log out. The board shows Light and English checked
|
||||||
|
|
||||||
### Loading
|
### Loading
|
||||||
|
|
||||||
@@ -161,17 +167,17 @@ The board's menu has no System, Light or Dark items, while the shipped UserMenu
|
|||||||
|
|
||||||
### Display names in the Users list
|
### Display names in the Users list
|
||||||
|
|
||||||
**Trigger:** Accounts with a display name show it first, with the username beside it in grey. Accounts without one show the username. This state needs the Users page ([users.md](users.md)).
|
**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")
|
- Breadcrumbs: Users (mobile title "Users")
|
||||||
- Signed-in user's display name: "Marta Alves" (sidebar chip shows it too)
|
- Signed-in user's display name: "Marta Alves" (sidebar chip shows it too)
|
||||||
- Row `marta` (you): "Marta Alves", `marta` beside it in muted text, "you" tag, Accepted
|
- Row `marta@renew.example` (you): display name "Marta Alves", role owner, Accepted
|
||||||
- Row `ines`: "Inès Duarte", `ines` beside it in muted text, Accepted
|
- Row `ines.duarte@renew.example`: display name "Inès Duarte", role admin, Accepted
|
||||||
- Row `jonas`: `jonas` alone, Accepted
|
- Row `jonas@renew.example`: display name "—" (muted), role admin, Accepted
|
||||||
|
|
||||||
## Notes for implementation
|
## 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.
|
- `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.
|
- 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.
|
- "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.
|
||||||
- Open question: the shipped UserMenu offers System, Light and Dark, and the redesigned menu does not. Decide whether the theme choice stays in the menu, moves to the Profile page, or is dropped, before building the menu.
|
- 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`.
|
||||||
@@ -0,0 +1,127 @@
|
|||||||
|
# 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). The title row is a flex row with an 8 px gap that wraps. In "Ready to install" it carries a **Pending tag** after the title and the block holds the **Restart** button (see below). |
|
||||||
|
| Pending tag | Only in "Ready to install", right after the title: 20 px high, 0 6 px padding, IBM Plex Mono 11 px medium, `--ui-bg` fill, `--ui-warning` text and 1 px `--ui-warning` border, square corners, text "Pending". |
|
||||||
|
| In-block button | Only in "Ready to install", "Restart: confirm" and "Restart: request failed": the primary Restart button sits inside the status block, under the `meta` line, after 8 px of extra top padding, left-aligned (content width, 14 px side padding, 32 px high, 44 px on mobile, not stretched). The buttons row under the block is not drawn in these states. The hint stays under the card. |
|
||||||
|
| 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 and inside the status block when an update is ready, otherwise secondary in the buttons row), **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 | `clock`, warning, with the "Pending" tag after the title: "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" (primary, inside the block); 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. The card turns warning (orange) with a "Pending" tag and a `clock` icon, and Restart, the primary action, sits inside it. "Restart later" is closing the dialog or leaving the page. |
|
||||||
|
| Restart: confirm | Restart pressed. The card behind the dialog keeps the Ready look. 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. The card behind the dialog keeps the Ready look. |
|
||||||
|
| 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. |
|
||||||
+120
-12
@@ -1,24 +1,60 @@
|
|||||||
# Users
|
# Users
|
||||||
|
|
||||||
- **Route:** `/users`
|
- **Route:** `/users`
|
||||||
- **API:** GET /v1/user/ · POST /v1/user/invite
|
- **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).
|
- **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. Rows have no actions yet, so nobody can be removed, promoted or have an invite revoked from here. Pending and expired invites show the email address, because a username only exists once the invite is accepted.
|
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.
|
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
|
## The list
|
||||||
|
|
||||||
| Column | Content |
|
| Column | Content |
|
||||||
|---|---|
|
|---|---|
|
||||||
| Username | An accepted user: the display name if there is one (medium weight, highlighted) with the username beside it in muted text; otherwise the username alone. A pending or expired invite: the email address, regular weight, toned. The current user's row carries a muted mono "you" tag. |
|
| 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. |
|
| 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, for a user the day the account was created. |
|
| 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. |
|
||||||
|
|
||||||
Desktop is a table: 36 px header, 44 px rows, columns `minmax(0,1fr) 160px 160px`. Below md it becomes a card list (68 px minimum row height): the name line, then the badge and "Created {date}". 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 username is no longer shown in this list.
|
||||||
|
|
||||||
The admin who registered first is always listed, so the list is never empty.
|
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
|
## States
|
||||||
|
|
||||||
@@ -27,21 +63,28 @@ The admin who registered first is always listed, so the list is never empty.
|
|||||||
**Trigger:** The list loaded, newest first.
|
**Trigger:** The list loaded, newest first.
|
||||||
|
|
||||||
- Breadcrumbs: Users (mobile title "Users")
|
- Breadcrumbs: Users (mobile title "Users")
|
||||||
- Rows: `sam.oliveira@renew.example` Pending, 27 Sep 2026 · `p.huber@gmail.com` Expired, 3 Aug 2026 · `ines` (display name "Inès Duarte") Accepted, 18 Jun 2026 · `jonas` Accepted, 2 Apr 2026 · `marta` (you) Accepted, 12 Mar 2026
|
- 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
|
### Loading
|
||||||
|
|
||||||
**Trigger:** The first load, or a retry. Skeletons appear after 150 ms.
|
**Trigger:** The first load, or a retry. Skeletons appear after 150 ms.
|
||||||
|
|
||||||
- Breadcrumbs: Users (mobile title "Users")
|
- Breadcrumbs: Users (mobile title "Users")
|
||||||
- Five skeleton rows
|
- Five skeleton rows, one bar per column, plus a role-badge and a status-badge placeholder
|
||||||
|
|
||||||
### Only you
|
### Only you
|
||||||
|
|
||||||
**Trigger:** Nobody has been invited yet. The admin who registered is always listed.
|
**Trigger:** Nobody has been invited yet. The owner is always listed.
|
||||||
|
|
||||||
- Breadcrumbs: Users (mobile title "Users")
|
- Breadcrumbs: Users (mobile title "Users")
|
||||||
- One row: `marta` (you) Accepted
|
- 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."
|
- Hint under the list: "Invite someone so they can sign in with their own account instead of sharing yours."
|
||||||
|
|
||||||
### Error
|
### Error
|
||||||
@@ -111,14 +154,79 @@ The admin who registered first is always listed, so the list is never empty.
|
|||||||
**Trigger:** 201: the dialog closes, the new invite appears at the top as Pending (highlighted row), and a toast confirms.
|
**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")
|
- Breadcrumbs: Users (mobile title "Users")
|
||||||
- New first row: `lea.martin@renew.example` Pending, created "Today", row background `--ui-bg-elevated`
|
- 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."
|
- 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.
|
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
|
## Notes for implementation
|
||||||
|
|
||||||
- An accepted user is shown by username and display name only, never by email.
|
- 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.
|
- 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.
|
- 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 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.
|
||||||
@@ -0,0 +1,94 @@
|
|||||||
|
<!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="flex:1;min-height:0;overflow:hidden;background:var(--ui-bg-muted);color:var(--ui-text);font-family:'IBM Plex Sans',sans-serif;font-size:13px;line-height:20px;padding:{{ pad }};position:relative;display:flex;flex-direction:column;gap:16px">
|
||||||
|
<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="color:var(--ui-text-muted)">Integration › API keys</span><span style="font:600 {{ h1 }} 'IBM Plex Sans',sans-serif;color:var(--ui-text-highlighted)">API keys</span><span style="color:var(--ui-text-muted);text-wrap:pretty">{{ sub }}</span></div>
|
||||||
|
<sc-if value="{{ desk }}"><span style="height:36px;padding:0 14px;display:flex;align-items:center;gap:6px;background:var(--ui-primary);color:var(--ui-bg);font-weight:500">Create key</span></sc-if>
|
||||||
|
</div>
|
||||||
|
<sc-if value="{{ err }}"><div role="alert" style="display:flex;gap:10px;padding:12px 14px;background:var(--rc-error-soft);color:var(--ui-error)"><span style="flex:1"><strong>Couldn't load your API keys</strong><br>Check your connection and try again.</span><span style="font-weight:500;color:var(--ui-text-highlighted)">Try again</span></div></sc-if>
|
||||||
|
<sc-if value="{{ empty }}"><div style="background:var(--ui-bg);border:1px solid var(--ui-border);padding:48px 24px;display:flex;flex-direction:column;align-items:center;gap:10px;text-align:center"><span style="font:600 16px/24px 'IBM Plex Sans',sans-serif;color:var(--ui-text-highlighted)">No API keys yet</span><span style="color:var(--ui-text-toned);max-width:360px;text-wrap:pretty">Create a key to call the API from a script or service.</span><sc-if value="{{ desk }}"><span style="height:36px;padding:0 14px;display:flex;align-items:center;background:var(--ui-primary);color:var(--ui-bg);font-weight:500">Create key</span></sc-if></div></sc-if>
|
||||||
|
<sc-if value="{{ showList }}">
|
||||||
|
<sc-if value="{{ desk }}"><div style="background:var(--ui-bg);border:1px solid var(--ui-border)">
|
||||||
|
<div style="display:grid;grid-template-columns:{{ cols }};gap:12px;height:36px;align-items:center;padding:0 12px;background:var(--ui-bg-elevated);color:var(--ui-text-muted);font-weight:500"><span>Name</span><span>Key</span><span>Status</span><sc-if value="{{ owner }}"><span>Created by</span></sc-if><span>Created</span><span>Last used</span><span>Expires</span><span></span></div>
|
||||||
|
<sc-for list="{{ rows }}" as="r" hint-placeholder-count="4"><div style="display:grid;grid-template-columns:{{ cols }};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:70%;background:var(--ui-bg-accented)"></span><span style="height:20px;width:56px;background:var(--ui-bg-accented)"></span><span style="height:12px;width:60%;background:var(--ui-bg-accented)"></span><span></span><span></span><span></span></sc-if>
|
||||||
|
<sc-if value="{{ r.name }}"><span style="overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-weight:500;color:{{ r.fg }}">{{ r.name }}</span><span style="font:400 12px 'IBM Plex Mono',monospace;color:{{ r.fg2 }}">{{ r.prefix }}</span><span><span style="height:20px;padding:0 6px;display:inline-flex;align-items:center;background:{{ r.sbg }};color:{{ r.sfg }};font-size:12px;font-weight:500">{{ r.status }}</span></span>
|
||||||
|
<sc-if value="{{ owner }}"><span style="color:{{ r.fg2 }};overflow:hidden;text-overflow:ellipsis;white-space:nowrap">{{ r.by }}</span></sc-if><span style="color:{{ r.fg2 }}">{{ r.created }}</span><span style="color:{{ r.fg2 }}">{{ r.used }}</span><span style="color:{{ r.fg2 }}">{{ r.exp }}</span>
|
||||||
|
<span style="display:flex;justify-content:flex-end"><sc-if value="{{ r.canRevoke }}"><span style="height:28px;padding:0 10px;display:flex;align-items:center;border:1px solid var(--ui-border-accented);color:var(--ui-text-highlighted);font-weight:500">Revoke</span></sc-if></span></sc-if>
|
||||||
|
</div></sc-for></div></sc-if>
|
||||||
|
<sc-if value="{{ mob }}"><div style="background:var(--ui-bg);border:1px solid var(--ui-border);margin:0 -16px;border-left:0;border-right:0">
|
||||||
|
<sc-for list="{{ rows }}" as="r" hint-placeholder-count="4"><div style="display:flex;flex-direction:column;gap:6px;padding:12px 16px;border-bottom:1px solid var(--ui-border);background:{{ r.bg }}">
|
||||||
|
<sc-if value="{{ r.skel }}"><span style="height:14px;width:55%;background:var(--ui-bg-accented)"></span><span style="height:12px;width:40%;background:var(--ui-bg-accented)"></span></sc-if>
|
||||||
|
<sc-if value="{{ r.name }}"><div style="display:flex;align-items:center;gap:8px"><span style="flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-weight:500;font-size:15px;color:{{ r.fg }}">{{ r.name }}</span><span style="height:20px;padding:0 6px;display:inline-flex;align-items:center;background:{{ r.sbg }};color:{{ r.sfg }};font-size:12px;font-weight:500">{{ r.status }}</span></div>
|
||||||
|
<span style="font:400 12px 'IBM Plex Mono',monospace;color:{{ r.fg2 }}">{{ r.prefix }}</span>
|
||||||
|
<span style="color:{{ r.fg2 }}">Created {{ r.created }}<sc-if value="{{ owner }}"> by {{ r.by }}</sc-if> · Last used {{ r.used }} · Expires {{ r.exp }}</span>
|
||||||
|
<sc-if value="{{ r.canRevoke }}"><span style="align-self:flex-start;height:44px;padding:0 14px;display:flex;align-items:center;border:1px solid var(--ui-border-accented);color:var(--ui-text-highlighted);font-weight:500">Revoke</span></sc-if></sc-if>
|
||||||
|
</div></sc-for></div></sc-if>
|
||||||
|
</sc-if>
|
||||||
|
<div style="display:flex;flex-direction:column;gap:8px;font-size:14px;line-height:22px;color:var(--ui-text-toned)">
|
||||||
|
<div style="display:flex;gap:10px"><span style="display:flex;padding-top:3px;color:var(--ui-info)"><span aria-hidden="true" style="display:inline-block;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="text-wrap:pretty">Resetting a user's password revokes all of their keys.</span></div>
|
||||||
|
</div>
|
||||||
|
<sc-if value="{{ pinned }}"><div style="position:absolute;left:0;right:0;bottom:0;z-index:40;padding:12px 16px;background:var(--ui-bg);border-top:1px solid var(--ui-border)"><span style="height:44px;display:flex;align-items:center;justify-content:center;gap:6px;background:var(--ui-primary);color:var(--ui-bg);font-weight:500">Create key</span></div></sc-if>
|
||||||
|
<sc-if value="{{ toast }}"><div role="status" style="position:absolute;{{ toastPos }};z-index:60;display:flex;gap:10px;padding:12px 14px;background:var(--ui-bg);border:1px solid var(--ui-border);box-shadow:var(--rc-shadow-pop);color:var(--ui-success)"><span style="display:flex;flex-direction:column"><strong>Key revoked</strong><span style="color:var(--ui-text-toned)">"Nightly media import" can no longer be used.</span></span></div></sc-if>
|
||||||
|
</div>
|
||||||
|
<sc-if value="{{ modal }}"><div style="position:absolute;inset:0;z-index:50;background:var(--rc-overlay);display:flex;align-items:{{ mAlign }};justify-content:center;padding:{{ mPad }}">
|
||||||
|
<div role="dialog" aria-modal="true" style="width:{{ mW }};max-width:100%;background:var(--ui-bg);border:1px solid var(--ui-border);box-shadow:var(--rc-shadow-modal);padding:20px;display:flex;flex-direction:column;gap:14px;color:var(--ui-text)">
|
||||||
|
<div style="display:flex;flex-direction:column;gap:4px"><span style="font:600 18px/26px 'IBM Plex Sans',sans-serif;color:var(--ui-text-highlighted)">{{ m.title }}</span><span style="color:var(--ui-text-toned);font-size:14px;line-height:22px;text-wrap:pretty">{{ m.desc }}</span></div>
|
||||||
|
<sc-if value="{{ m.form }}">
|
||||||
|
<div style="display:flex;flex-direction:column;gap:6px"><div style="display:flex;justify-content:space-between"><span style="font-weight:500;color:var(--ui-text-highlighted)">Name</span><span style="font:400 12px 'IBM Plex Mono',monospace;color:{{ m.cntFg }}">{{ m.count }}</span></div><span style="height:40px;padding:0 12px;display:flex;align-items:center;border:1px solid {{ m.nameBd }};background:var(--ui-bg);color:var(--ui-text-highlighted)">{{ m.name }}</span><span style="color:{{ m.nameFg }}">{{ m.nameHelp }}</span></div>
|
||||||
|
<div style="display:flex;flex-direction:column;gap:6px"><span style="font-weight:500;color:var(--ui-text-highlighted)">Expiry date <span style="font-weight:400;color:var(--ui-text-muted)">(optional)</span></span><span style="height:40px;padding:0 12px;display:flex;align-items:center;border:1px solid {{ m.expBd }};background:var(--ui-bg);color:{{ m.expTx }}">{{ m.exp }}</span><span style="color:{{ m.expFg }}">{{ m.expHelp }}</span></div>
|
||||||
|
</sc-if>
|
||||||
|
<sc-if value="{{ m.reveal }}">
|
||||||
|
<div style="display:flex;gap:10px;padding:10px 12px;background:var(--rc-warning-soft);color:var(--ui-warning)"><span style="display:flex;padding-top:2px"><span aria-hidden="true" style="display:inline-block;width:16px;height:16px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/triangle-alert.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/triangle-alert.svg') center / contain no-repeat"></span></span><span style="font-weight:500">You won't be able to see this key again.</span></div>
|
||||||
|
<div style="display:flex;flex-direction:{{ keyDir }};border:1px solid var(--ui-border-accented);background:var(--ui-bg-elevated)"><span style="flex:1;min-width:0;padding:10px 12px;font:400 12px/20px 'IBM Plex Mono',monospace;word-break:break-all;color:var(--ui-text-highlighted)">rcms_Kf3x9QwL0aBcT7nV2uYdE5sHjR8mPz4WqXg6C1oIyNe</span><span style="height:44px;padding:0 14px;display:flex;align-items:center;justify-content:center;gap:6px;border-left:1px solid var(--ui-border-accented);font-weight:500;color:{{ m.cpFg }}"><span aria-hidden="true" style="display:inline-block;width:14px;height:14px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/{{ m.cpIcon }}.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/{{ m.cpIcon }}.svg') center / contain no-repeat"></span>{{ m.cpT }}</span></div>
|
||||||
|
<span style="color:var(--ui-text-muted)">Closing this window discards the key from the screen. Copy it first.</span>
|
||||||
|
</sc-if>
|
||||||
|
<div style="display:flex;flex-direction:{{ btnDir }};justify-content:flex-end;gap:8px"><sc-if value="{{ m.cancel }}"><span style="height:44px;padding:0 14px;display:flex;align-items:center;justify-content:center;border:1px solid var(--ui-border-accented);color:var(--ui-text-highlighted);font-weight:500">{{ m.cancel }}</span></sc-if><span style="height:44px;padding:0 14px;display:flex;align-items:center;justify-content:center;font-weight:500;background:{{ m.cbg }};color:{{ m.cfg }};opacity:{{ m.cop }}">{{ m.confirm }}</span></div>
|
||||||
|
</div></div></sc-if>
|
||||||
|
</x-dc>
|
||||||
|
<script type="text/x-dc" data-dc-script>
|
||||||
|
class Component extends DCLogic {
|
||||||
|
renderVals() {
|
||||||
|
const mob = !!this.props.mobile, k = (this.props.s && this.props.s.ak) || {}
|
||||||
|
const owner = k.view !== 'admin'
|
||||||
|
const R = (name, prefix, status, by, created, used, exp) => {
|
||||||
|
const rv = status === 'revoked', tone = { active: ['var(--rc-success-soft)', 'var(--ui-success)'], expired: ['var(--rc-warning-soft)', 'var(--ui-warning)'], revoked: ['var(--ui-bg-elevated)', 'var(--ui-text-muted)'] }[status]
|
||||||
|
return { name, prefix, status, by, created, used, exp, sbg: tone[0], sfg: tone[1], bg: rv ? 'var(--ui-bg-muted)' : 'var(--ui-bg)', fg: rv ? 'var(--ui-text-muted)' : 'var(--ui-text-highlighted)', fg2: rv ? 'var(--ui-text-muted)' : 'var(--ui-text-toned)', canRevoke: !rv }
|
||||||
|
}
|
||||||
|
let all = owner
|
||||||
|
? [R('Website build', 'rcms_Kf3x…', 'active', 'Marta Alves', '12 Mar 2026', '3 Oct 2026', 'None'), R('Nightly media import', 'rcms_Mq7b…', k.revoked ? 'revoked' : 'active', 'Jonas', '2 Apr 2026', '3 Oct 2026', '31 Dec 2026'), R('Staging preview', 'rcms_Zt2d…', 'expired', 'Marta Alves', '14 Jun 2026', '20 Aug 2026', '30 Aug 2026'), R('Old migration script', 'rcms_Hn5w…', 'revoked', 'Inès Duarte', '3 Apr 2026', '9 May 2026', 'None')]
|
||||||
|
: [R('Nightly media import', 'rcms_Mq7b…', 'active', 'Jonas', '2 Apr 2026', '3 Oct 2026', '31 Dec 2026'), R('Old CI token', 'rcms_Lp9c…', 'revoked', 'Jonas', '18 Jan 2026', '2 Feb 2026', 'None')]
|
||||||
|
const st = k.state || 'list'
|
||||||
|
const rows = st === 'loading' ? Array.from({ length: 4 }, () => ({ skel: true, bg: 'var(--ui-bg)' })) : all
|
||||||
|
const cp = { reveal: true }
|
||||||
|
const b = (o) => ({ cancel: 'Cancel', cbg: 'var(--ui-primary)', cfg: 'var(--ui-bg)', cop: '1', ...o })
|
||||||
|
const form = (o) => b({ form: true, title: 'Create API key', desc: 'The key acts as you, with your role. It is shown in full once.', confirm: 'Create key', name: 'Nightly media import', count: '20 / 60', cntFg: 'var(--ui-text-muted)', nameBd: 'var(--ui-border-accented)', nameFg: 'var(--ui-text-muted)', nameHelp: 'Required. Up to 60 characters.', exp: '31 Dec 2026', expTx: 'var(--ui-text-highlighted)', expBd: 'var(--ui-border-accented)', expFg: 'var(--ui-text-muted)', expHelp: 'Optional. Must be in the future. Leave it empty for a key that does not expire.', ...o })
|
||||||
|
const M = {
|
||||||
|
create: form({}),
|
||||||
|
invalid: form({ name: '', count: '0 / 60', nameBd: 'var(--ui-error)', nameFg: 'var(--ui-error)', nameHelp: 'Enter a name.', exp: '12 Mar 2026', expBd: 'var(--ui-error)', expFg: 'var(--ui-error)', expHelp: 'Choose a date in the future.' }),
|
||||||
|
toolong: form({ name: 'Nightly import of the new media library from the Brussels office file server', count: '75 / 60', cntFg: 'var(--ui-error)', nameBd: 'var(--ui-error)', nameFg: 'var(--ui-error)', nameHelp: 'Use 60 characters or fewer.' }),
|
||||||
|
reveal: b({ reveal: true, title: 'Your new API key', desc: '"Nightly media import" is ready. Copy the key and store it somewhere safe.', cancel: '', confirm: 'Done', cpT: 'Copy', cpIcon: 'copy', cpFg: 'var(--ui-text-highlighted)' }),
|
||||||
|
copied: b({ reveal: true, title: 'Your new API key', desc: '"Nightly media import" is ready. Copy the key and store it somewhere safe.', cancel: '', confirm: 'Done', cpT: 'Copied', cpIcon: 'check', cpFg: 'var(--ui-success)' }),
|
||||||
|
revoke: b({ title: 'Revoke this key?', desc: '"Nightly media import" (rcms_Mq7b…) will stop working right away. Requests that use it answer 401. This can\'t be undone.', cancel: 'Keep key', confirm: 'Revoke key', cbg: 'var(--ui-error)', cfg: 'var(--ui-bg)' })
|
||||||
|
}
|
||||||
|
const m = k.modal ? M[k.modal] : null
|
||||||
|
return {
|
||||||
|
mob, desk: !mob, owner, rows, pad: mob ? '20px 16px 84px' : '32px', pinned: mob && !m, h1: mob ? '20px/28px' : '28px/36px',
|
||||||
|
sub: owner ? 'Keys act as the user who created them. As an owner you see everyone\'s keys.' : 'Keys act as you, with your role. You only see your own keys.',
|
||||||
|
err: st === 'error', empty: st === 'empty', showList: st === 'list' || st === 'loading',
|
||||||
|
cols: owner ? 'minmax(0,1.3fr) 110px 76px minmax(0,1fr) 100px 100px 100px 80px' : 'minmax(0,1.3fr) 110px 76px 100px 100px 100px 80px',
|
||||||
|
toast: !!k.toast, toastPos: mob ? 'left:16px;right:16px;bottom:84px' : 'right:24px;bottom:24px;width:320px',
|
||||||
|
modal: !!m, m: m || {}, mAlign: mob ? 'flex-end' : 'flex-start', mPad: mob ? '16px' : '120px 16px 16px', mW: mob ? '100%' : '480px', btnDir: mob ? 'column-reverse' : 'row', keyDir: mob ? 'column' : 'row'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
@@ -12,20 +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="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>
|
<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><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 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><div style="padding:6px 8px 2px;font-size:11px;font-weight:500;letter-spacing:.04em;text-transform:uppercase;color:var(--ui-text-muted)">Theme</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 style="padding:6px 8px 2px;font-size:11px;font-weight:500;letter-spacing:.04em;text-transform:uppercase;color:var(--ui-text-muted)">Language</div><sc-for list="{{ langSeg }}" as="m" hint-placeholder-count="2"><div data-act="{{ m.act }}" lang="{{ m.code }}" 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>
|
||||||
|
|
||||||
@@ -43,6 +43,7 @@
|
|||||||
<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, {{ 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>
|
<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">
|
||||||
@@ -176,25 +177,8 @@
|
|||||||
</sc-if>
|
</sc-if>
|
||||||
</sc-if>
|
</sc-if>
|
||||||
|
|
||||||
<sc-if value="{{ isInteg }}">
|
<sc-if value="{{ isInteg }}"><div style="position:relative;flex:1;min-height:0;overflow:hidden"><dc-import name="IntegrationPage" s="{{ s }}" mobile="{{ mob }}" style="display:flex;flex-direction:column;flex:1;min-height:0;overflow:hidden" hint-size="100%,100%"></dc-import></div></sc-if>
|
||||||
<div style="padding:{{ pad }};display:flex;flex-direction:column;gap:24px;max-width:860px;overflow:hidden">
|
<sc-if value="{{ isKeys }}"><div style="display:flex;flex-direction:column;flex:1;min-height:0;overflow:hidden"><dc-import name="ApiKeysPage" s="{{ s }}" mobile="{{ mob }}" style="display:flex;flex-direction:column;flex:1;min-height:0;overflow:hidden" hint-size="100%,100%"></dc-import></div></sc-if>
|
||||||
<div style="display:flex;flex-direction:column;gap:4px"><span style="font:600 20px/28px 'IBM Plex Sans',sans-serif;color:var(--ui-text-highlighted)">Connect your website</span><span style="color:var(--ui-text-muted)">A guide for the developer who builds your public site.</span></div>
|
|
||||||
<p style="margin:0;font-size:14px;line-height:22px;color:var(--ui-text-toned);text-wrap:pretty">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.</p>
|
|
||||||
<div style="display:flex;flex-direction:column;gap:6px"><span style="font-weight:500;color:var(--ui-text-highlighted)">Base URL</span><div style="display:flex;border:1px solid var(--ui-border-accented);background:var(--ui-bg)"><span style="flex:1;min-width:0;height:40px;padding:0 12px;display:flex;align-items:center;font:400 13px 'IBM Plex Mono',monospace;overflow:hidden;white-space:nowrap">https://cms.renew.example</span><span data-act="copy" style="height:40px;padding:0 12px;display:flex;align-items:center;gap:6px;border-left:1px solid var(--ui-border-accented);font-weight:500;color:{{ copyFg }}"><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/{{ copyIcon }}.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/{{ copyIcon }}.svg') center / contain no-repeat"></span>{{ copyText }}</span></div></div>
|
|
||||||
<sc-for list="{{ endpoints }}" as="e" hint-placeholder-count="2">
|
|
||||||
<div style="background:var(--ui-bg);border:1px solid var(--ui-border)">
|
|
||||||
<div style="padding:16px;display:flex;flex-direction:column;gap:8px;border-bottom:1px solid var(--ui-border)"><div style="display:flex;align-items:center;gap:10px;flex-wrap:wrap"><span style="height:22px;padding:0 7px;display:inline-flex;align-items:center;background:var(--ui-bg-inverted);color:var(--ui-text-inverted);font:500 12px 'IBM Plex Mono',monospace">GET</span><span style="font:500 14px 'IBM Plex Mono',monospace;color:var(--ui-text-highlighted)">{{ e.path }}</span></div><span style="color:var(--ui-text-toned)">{{ e.desc }}</span></div>
|
|
||||||
<div style="display:flex;gap:20px;padding:0 16px;border-bottom:1px solid var(--ui-border)"><span style="height:36px;display:flex;align-items:center;border-bottom:2px solid {{ e.l1 }};margin-bottom:-1px;font-weight:500;color:var(--ui-text-highlighted)">fetch</span><span style="height:36px;display:flex;align-items:center;color:var(--ui-text-toned)">curl</span><span style="height:36px;display:flex;align-items:center;color:var(--ui-text-toned)">Response</span></div>
|
|
||||||
<div style="background:var(--ui-bg-elevated)"><div style="height:32px;padding:0 8px 0 16px;display:flex;align-items:center;justify-content:space-between;border-bottom:1px solid var(--ui-border)"><span style="font:500 12px 'IBM Plex Mono',monospace;color:var(--ui-text-muted)">JavaScript</span><span style="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:14px;height:14px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/copy.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/copy.svg') center / contain no-repeat"></span>Copy</span></div><pre style="margin:0;padding:14px 16px;overflow:hidden;font:400 12px/19px 'IBM Plex Mono',monospace;color:var(--ui-text);white-space:pre">{{ e.code }}</pre></div>
|
|
||||||
</div>
|
|
||||||
</sc-for>
|
|
||||||
<div style="display:flex;flex-direction:column;gap:10px;font-size:14px;line-height:22px;color:var(--ui-text-toned)">
|
|
||||||
<div style="display:flex;gap:10px"><span style="display:flex;padding-top:3px;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="text-wrap:pretty">Anonymous callers only ever get online articles. Drafts stay private until you publish them.</span></div>
|
|
||||||
<div style="display:flex;gap:10px"><span style="display:flex;padding-top:3px;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="text-wrap:pretty">Images in <code>body</code> use paths like <code>/static/uploadedImages/<uuid>.png</code>. Prefix them with the base URL before rendering.</span></div>
|
|
||||||
<div style="display:flex;gap:10px"><span style="display:flex;padding-top:3px;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="text-wrap:pretty">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.</span></div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</sc-if>
|
|
||||||
|
|
||||||
<sc-if value="{{ isUsers }}">
|
<sc-if value="{{ isUsers }}">
|
||||||
<div style="padding:{{ pad }};display:flex;flex-direction:column;gap:16px;flex:1;min-height:0">
|
<div style="padding:{{ pad }};display:flex;flex-direction:column;gap:16px;flex:1;min-height:0">
|
||||||
@@ -202,11 +186,11 @@
|
|||||||
<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="{{ 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 }}">
|
<sc-if value="{{ usTable }}">
|
||||||
<div style="background:var(--ui-bg);border:1px solid var(--ui-border)">
|
<div style="background:var(--ui-bg);border:1px solid var(--ui-border)">
|
||||||
<div style="display:grid;grid-template-columns:minmax(0,1fr) 160px 160px;height:36px;align-items:center;padding:0 12px;background:var(--ui-bg-elevated);color:var(--ui-text-muted);font-weight:500"><span>Username</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></div>
|
<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">
|
<sc-for list="{{ usRows }}" as="r" hint-placeholder-count="5">
|
||||||
<div style="display:grid;grid-template-columns:minmax(0,1fr) 160px 160px;height:44px;align-items:center;padding:0 12px;border-top:1px solid var(--ui-border);background:{{ r.bg }}">
|
<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:30%;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.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.name }}"><span style="display:flex;align-items:center;gap:8px;min-width:0;padding-right:12px"><span style="overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-weight:{{ r.fw }};color:{{ r.fg }}">{{ r.name }}</span><sc-if value="{{ r.sub }}"><span style="flex-shrink:0;color:var(--ui-text-muted)">{{ r.sub }}</span></sc-if><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><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></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>
|
</div>
|
||||||
</sc-for>
|
</sc-for>
|
||||||
</div>
|
</div>
|
||||||
@@ -216,7 +200,7 @@
|
|||||||
<sc-for list="{{ usRows }}" as="r" hint-placeholder-count="5">
|
<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 }}">
|
<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.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.name }}"><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:{{ r.fw }};color:{{ r.fg }}">{{ r.name }}</span><sc-if value="{{ r.sub }}"><span style="flex-shrink:0;color:var(--ui-text-muted)">{{ r.sub }}</span></sc-if><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><div style="display:flex;align-items:center;gap:10px;font-size:12px;color:var(--ui-text-muted)"><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>
|
<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>
|
</div>
|
||||||
</sc-for>
|
</sc-for>
|
||||||
</div>
|
</div>
|
||||||
@@ -226,6 +210,22 @@
|
|||||||
<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 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>
|
||||||
|
|
||||||
|
<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"><div style="display:flex;align-items:center;flex-wrap:wrap;gap:8px"><span style="font:600 14px/22px 'IBM Plex Sans',sans-serif;color:var(--ui-text-highlighted)">{{ s.upd.title }}</span><sc-if value="{{ s.upd.pendingTag }}"><span style="height:20px;padding:0 6px;display:inline-flex;align-items:center;background:var(--ui-bg);color:var(--ui-warning);border:1px solid var(--ui-warning);font:500 11px 'IBM Plex Mono',monospace">Pending</span></sc-if></div><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><sc-if value="{{ s.upd.inBtn }}"><div style="display:flex;padding-top:8px"><span role="button" style="height:{{ btnH }};padding:0 14px;display:flex;align-items:center;justify-content:center;gap:6px;background:{{ s.upd.inBtn.bg }};color:{{ s.upd.inBtn.fg }};border:1px solid {{ s.upd.inBtn.bd }};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/{{ s.upd.inBtn.icon }}.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/{{ s.upd.inBtn.icon }}.svg') center / contain no-repeat"></span>{{ s.upd.inBtn.t }}</span></div></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 }}">
|
<sc-if value="{{ isProfile }}">
|
||||||
<div style="padding:{{ pad }};display:flex;flex-direction:column;gap:20px;max-width:720px;overflow:hidden">
|
<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>
|
<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>
|
||||||
@@ -263,7 +263,9 @@
|
|||||||
</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><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="{{ 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><div style="padding:8px 16px 2px;font-size:11px;font-weight:500;letter-spacing:.04em;text-transform:uppercase;color:var(--ui-text-muted)">Theme</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 style="padding:8px 16px 2px;font-size:11px;font-weight:500;letter-spacing:.04em;text-transform:uppercase;color:var(--ui-text-muted)">Language</div><sc-for list="{{ langSeg }}" as="m" hint-placeholder-count="2"><div data-act="{{ m.act }}" lang="{{ m.code }}" 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 }}">
|
||||||
@@ -336,8 +338,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'], ['users', 'users', 'Users'], ['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]
|
||||||
@@ -390,7 +392,9 @@ class Component extends DCLogic {
|
|||||||
}
|
}
|
||||||
const US = s.users || {}
|
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 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 usRows = (US.loading ? Array.from({ length: 5 }, () => ({ skel: true })) : (US.rows || [])).map(r => r.skel ? r : ({ ...r, name: (r.you && s.display) || r.display || r.u || r.email, sub: r.u && ((r.you && s.display) || r.display) ? r.u : '', fw: r.u ? 500 : 400, fg: r.u ? 'var(--ui-text-highlighted)' : 'var(--ui-text-toned)', b: badges[r.st] || badges.pending, bg: r.hl ? 'var(--ui-bg-elevated)' : 'transparent' }))
|
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 who = s.display || 'marta'
|
||||||
const ini = s.display ? s.display.trim().split(/\s+/).slice(0, 2).map(w => w[0]).join('').toUpperCase() : 'MA'
|
const ini = s.display ? s.display.trim().split(/\s+/).slice(0, 2).map(w => w[0]).join('').toUpperCase() : 'MA'
|
||||||
const pf = s.pf || {}
|
const pf = s.pf || {}
|
||||||
@@ -414,17 +418,17 @@ class Component extends DCLogic {
|
|||||||
const edTitle = e.title || 'How we price a bathroom renovation'
|
const edTitle = e.title || 'How we price a bathroom renovation'
|
||||||
return {
|
return {
|
||||||
cr, s, nav, crumbs, who, ini, pf, dn, dnSave, rsNote, rsBtn,
|
cr, s, nav, crumbs, who, ini, pf, dn, dnSave, rsNote, rsBtn,
|
||||||
menuOpen: !!s.userMenu, deskMenu: !m && !!s.userMenu, mobMenu: m && !!s.userMenu, pfItemBg: 'var(--ui-bg-elevated)',
|
langSeg: [['en','English'],['fr','Français']].map(([k,tt])=>{const on=(s.lang||'en')===k;return {act:'lang-'+k,code:k,t:tt,on,op:on?1:0}}), 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)',
|
chipBg: s.userMenu || s.nav === 'profile' ? 'var(--rc-sand)' : 'transparent', chipFg: s.userMenu || s.nav === 'profile' ? '#111111' : 'var(--ui-text-highlighted)',
|
||||||
isProfile: k === 'profile', pfLoading: k === 'profile' && !!pf.loading, pfReady: k === 'profile' && !pf.loading,
|
isSettings: k === 'settings', isProfile: k === 'profile', pfLoading: k === 'profile' && !!pf.loading, pfReady: k === 'profile' && !pf.loading,
|
||||||
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,
|
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', isUsers: k === 'users',
|
isBoot: !!s.boot, isHome: k === 'home' && !s.boot, isList: k === 'articles', isEditor: k === 'editor', isInteg: k === 'integration', isKeys: k === 'apikeys', isError: k === 'error', isUsers: k === 'users',
|
||||||
usRows, usError: !!US.error, usOnly: !!US.only && !US.error, usTable: !m && !US.error, usCards: m && !US.error,
|
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,
|
||||||
|
|||||||
@@ -54,16 +54,17 @@
|
|||||||
<sc-if value="{{ hasFooter }}">
|
<sc-if value="{{ hasFooter }}">
|
||||||
<div style="width:{{ w }};max-width:100%;padding:{{ footPad }};display:flex;align-items:center;justify-content:space-between;gap:12px;flex-wrap:wrap;font-size:13px;color:var(--ui-text-muted)">
|
<div style="width:{{ w }};max-width:100%;padding:{{ footPad }};display:flex;align-items:center;justify-content:space-between;gap:12px;flex-wrap:wrap;font-size:13px;color:var(--ui-text-muted)">
|
||||||
<span style="display:flex;gap:6px;flex-wrap:wrap;align-items:center"><sc-if value="{{ s.footer }}"><span>{{ s.footer.pre }}</span><span data-act="footer" style="color:var(--ui-text-highlighted);font-weight:500;text-decoration:underline;text-underline-offset:3px">{{ s.footer.link }}</span></sc-if><sc-if value="{{ s.pending }}"><span style="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">API pending</span></sc-if></span>
|
<span style="display:flex;gap:6px;flex-wrap:wrap;align-items:center"><sc-if value="{{ s.footer }}"><span>{{ s.footer.pre }}</span><span data-act="footer" style="color:var(--ui-text-highlighted);font-weight:500;text-decoration:underline;text-underline-offset:3px">{{ s.footer.link }}</span></sc-if><sc-if value="{{ s.pending }}"><span style="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">API pending</span></sc-if></span>
|
||||||
<span style="height:28px;padding:0 8px;display:flex;align-items:center;gap:6px;border:1px solid var(--ui-border-accented);color:var(--ui-text-toned)"><span aria-hidden="true" style="display:inline-block;width:14px;height:14px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/monitor.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/monitor.svg') center / contain no-repeat"></span>System</span>
|
<span style="position:relative;display:flex;align-items:center;gap:8px"><sc-if value="{{ langOpen }}"><div role="menu" aria-label="Language" style="position:absolute;right:0;bottom:36px;z-index:10;width:168px;background:var(--ui-bg);border:1px solid var(--ui-border);box-shadow:var(--rc-shadow-pop);padding:4px"><sc-for list="{{ langSeg }}" as="m" hint-placeholder-count="2"><div data-act="{{ m.act }}" lang="{{ m.code }}" role="menuitemradio" aria-checked="{{ m.on }}" style="height:{{ optH }};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></sc-if><span data-act="langmenu" role="button" aria-haspopup="menu" aria-expanded="{{ langOpen }}" aria-label="Language: {{ langName }}" style="height:{{ chipH }};padding:0 8px;display:flex;align-items:center;gap:6px;border:1px solid var(--ui-border-accented);color:var(--ui-text-toned);background:{{ langBg }}"><span aria-hidden="true" style="display:inline-block;width:14px;height:14px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/languages.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/languages.svg') center / contain no-repeat"></span>{{ langName }}</span><span style="height:{{ chipH }};padding:0 8px;display:flex;align-items:center;gap:6px;border:1px solid var(--ui-border-accented);color:var(--ui-text-toned)"><span aria-hidden="true" style="display:inline-block;width:14px;height:14px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/monitor.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/monitor.svg') center / contain no-repeat"></span>System</span></span>
|
||||||
</div>
|
</div>
|
||||||
</sc-if>
|
</sc-if>
|
||||||
</div>
|
</div>
|
||||||
</x-dc>
|
</x-dc>
|
||||||
<script type="text/x-dc" data-dc-script data-props="{"$preview":{"width":480,"height":620},"s":{"editor":null,"tsType":"object"},"mobile":{"editor":"boolean","default":false,"tsType":"boolean"}}">
|
<script type="text/x-dc" data-dc-script data-props="{"$preview":{"width":480,"height":620},"s":{"editor":null,"tsType":"object"},"lang":{"editor":"enum","options":["en","fr"],"default":"en","tsType":"string"},"langOpen":{"editor":"boolean","default":false,"tsType":"boolean"},"mobile":{"editor":"boolean","default":false,"tsType":"boolean"}}">
|
||||||
class Component extends DCLogic {
|
class Component extends DCLogic {
|
||||||
renderVals() {
|
renderVals() {
|
||||||
const s = this.props.s || {}
|
const s = this.props.s || {}
|
||||||
const m = !!this.props.mobile
|
const m = !!this.props.mobile
|
||||||
|
const lang = this.props.lang || s.lang || 'en'
|
||||||
const tone = t => ({ bg: 'var(--rc-' + t + '-soft)', fg: 'var(--ui-' + t + ')' })
|
const tone = t => ({ bg: 'var(--rc-' + t + '-soft)', fg: 'var(--ui-' + t + ')' })
|
||||||
const notice = s.notice ? { ...s.notice, ...tone(s.notice.tone) } : null
|
const notice = s.notice ? { ...s.notice, ...tone(s.notice.tone) } : null
|
||||||
const result = s.result ? { ...s.result, ...tone(s.result.tone), actions: (s.result.actions || []).map((a, i) => i === 0 && !a.secondary ? { act: 'result-' + i, t: a.t, bg: 'var(--ui-primary)', fg: 'var(--ui-bg)', bd: '1px solid var(--ui-primary)' } : { act: 'result-' + i, t: a.t, bg: 'var(--ui-bg)', fg: 'var(--ui-text-highlighted)', bd: '1px solid var(--ui-border-accented)' }) } : null
|
const result = s.result ? { ...s.result, ...tone(s.result.tone), actions: (s.result.actions || []).map((a, i) => i === 0 && !a.secondary ? { act: 'result-' + i, t: a.t, bg: 'var(--ui-primary)', fg: 'var(--ui-bg)', bd: '1px solid var(--ui-primary)' } : { act: 'result-' + i, t: a.t, bg: 'var(--ui-bg)', fg: 'var(--ui-text-highlighted)', bd: '1px solid var(--ui-border-accented)' }) } : null
|
||||||
@@ -87,7 +88,9 @@ class Component extends DCLogic {
|
|||||||
return {
|
return {
|
||||||
s, notice, result, fields,
|
s, notice, result, fields,
|
||||||
hasForm: fields.length > 0 && !!s.submit,
|
hasForm: fields.length > 0 && !!s.submit,
|
||||||
hasFooter: !!(s.footer || s.pending || !m),
|
hasFooter: true,
|
||||||
|
langOpen: !!(this.props.langOpen ?? s.langOpen), langName: lang === 'fr' ? 'Français' : 'English', langBg: this.props.langOpen ?? s.langOpen ? 'var(--ui-bg-elevated)' : 'transparent', chipH: m ? '44px' : '28px', optH: m ? '44px' : '32px',
|
||||||
|
langSeg: [['en','English'],['fr','Français']].map(([k,t]) => ({ act: 'lang-' + k, code: k, t, on: lang === k, op: lang === k ? 1 : 0 })),
|
||||||
submitOpacity: s.submit && s.submit.disabled && !s.submit.loading ? '0.4' : '1',
|
submitOpacity: s.submit && s.submit.disabled && !s.submit.loading ? '0.4' : '1',
|
||||||
w: m ? '100%' : '400px',
|
w: m ? '100%' : '400px',
|
||||||
border: m ? '0' : '1px solid var(--ui-border)',
|
border: m ? '0' : '1px solid var(--ui-border)',
|
||||||
|
|||||||
@@ -0,0 +1,290 @@
|
|||||||
|
<!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 ref="{{ rootRef }}" onScroll="{{ onScroll }}" style="position:absolute;inset:0;overflow-y:auto;overflow-x:hidden;scrollbar-width:thin;background:var(--ui-bg-muted);color:var(--ui-text);font-family:'IBM Plex Sans',sans-serif;font-size:13px;line-height:20px">
|
||||||
|
<sc-if value="{{ mob }}">
|
||||||
|
<div style="position:sticky;top:0;z-index:5;background:var(--ui-bg);border-bottom:1px solid var(--ui-border);padding:8px 16px;display:flex;flex-direction:column;gap:4px">
|
||||||
|
<button aria-haspopup="listbox" aria-expanded="{{ jumpOpen }}" aria-label="Jump to section" onClick="{{ toggleJump }}" style="all:unset;box-sizing:border-box;cursor:pointer;height:44px;padding:0 12px;display:flex;align-items:center;gap:8px;border:1px solid var(--ui-border-accented);background:var(--ui-bg);font-size:14px" style-focus-visible="outline:2px solid var(--ui-primary);outline-offset:2px"><span style="color:var(--ui-text-muted)">Jump to</span><span style="flex:1;font-weight:500;color:var(--ui-text-highlighted)">{{ activeLabel }}</span><span aria-hidden="true" style="display:inline-block;width:16px;height:16px;background-color:var(--ui-text-muted);-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></button>
|
||||||
|
<sc-if value="{{ jumpOpen }}"><div role="listbox" aria-label="Sections" style="position:absolute;left:16px;right:16px;top:56px;background:var(--ui-bg);border:1px solid var(--ui-border);box-shadow:var(--rc-shadow-pop);padding:4px">
|
||||||
|
<sc-for list="{{ index }}" as="i" hint-placeholder-count="8"><button role="option" aria-selected="{{ i.on }}" onClick="{{ i.go }}" style="all:unset;box-sizing:border-box;cursor:pointer;width:100%;height:44px;padding:0 10px;display:flex;align-items:center;justify-content:space-between;font-size:14px;background:{{ i.bg }};color:var(--ui-text-highlighted);font-weight:{{ i.fw }}" style-focus-visible="outline:2px solid var(--ui-primary);outline-offset:-2px">{{ i.t }}<span aria-hidden="true" style="display:inline-block;width:16px;height:16px;background-color:currentColor;opacity:{{ i.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></button></sc-for>
|
||||||
|
</div></sc-if>
|
||||||
|
</div>
|
||||||
|
</sc-if>
|
||||||
|
<div style="position:relative;padding:{{ pad }};display:flex;gap:40px;align-items:flex-start">
|
||||||
|
<div style="flex:1;min-width:0;display:flex;flex-direction:column;gap:{{ secGap }}">
|
||||||
|
|
||||||
|
<div style="display:flex;flex-direction:column;gap:6px">
|
||||||
|
<span style="color:var(--ui-text-muted)">Integration</span>
|
||||||
|
<span style="font:600 {{ h1 }} 'IBM Plex Sans',sans-serif;color:var(--ui-text-highlighted)">API reference</span>
|
||||||
|
<span style="color:var(--ui-text-muted);font-size:14px;line-height:22px">Everything a developer needs to build on RenewCMS.</span>
|
||||||
|
</div>
|
||||||
|
<p style="margin:0;font-size:14px;line-height:22px;color:var(--ui-text-toned);text-wrap:pretty;max-width:720px">RenewCMS is headless: it stores your content and your own code displays it. There are two ways in. Public read-only access lets a website read online articles. API keys let a script or service manage articles, media and users without the back-office.</p>
|
||||||
|
|
||||||
|
<div style="display:flex;flex-direction:column;gap:6px">
|
||||||
|
<span style="font-weight:500;color:var(--ui-text-highlighted)">Base URL</span>
|
||||||
|
<div style="display:flex;border:1px solid var(--ui-border-accented);background:var(--ui-bg)"><span style="flex:1;min-width:0;height:40px;padding:0 12px;display:flex;align-items:center;font:400 13px 'IBM Plex Mono',monospace;overflow:hidden;white-space:nowrap">https://cms.renew.example</span>
|
||||||
|
<button aria-label="Copy base URL" onClick="{{ copyBase }}" style="all:unset;box-sizing:border-box;cursor:pointer;height:40px;padding:0 12px;display:flex;align-items:center;gap:6px;border-left:1px solid var(--ui-border-accented);font-weight:500;color:{{ baseCopy.fg }}" style-focus-visible="outline:2px solid var(--ui-primary);outline-offset:-2px"><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/{{ baseCopy.icon }}.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/{{ baseCopy.icon }}.svg') center / contain no-repeat"></span><span aria-live="polite">{{ baseCopy.t }}</span></button></div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<section data-anchor="auth" aria-labelledby="h-auth" style="display:flex;flex-direction:column;gap:14px">
|
||||||
|
<h2 id="h-auth" style="margin:0;font:600 18px/26px 'IBM Plex Sans',sans-serif;color:var(--ui-text-highlighted)">Authentication</h2>
|
||||||
|
<div style="display:grid;grid-template-columns:{{ authCols }};gap:12px;align-items:start">
|
||||||
|
<div style="background:var(--ui-bg);border:1px solid var(--ui-border);padding:16px;display:flex;flex-direction:column;gap:10px">
|
||||||
|
<div style="display:flex;align-items:center;gap:8px"><span style="font:600 15px/22px 'IBM Plex Sans',sans-serif;color:var(--ui-text-highlighted)">Public</span><span style="height:20px;padding:0 6px;display:inline-flex;align-items:center;border:1px solid var(--ui-border-accented);color:var(--ui-text-toned);font-size:12px">No key</span></div>
|
||||||
|
<span style="color:var(--ui-text-toned);text-wrap:pretty">No key needed. Two read-only routes, and only online articles are returned.</span>
|
||||||
|
<div style="display:flex;flex-direction:column;gap:6px;font:500 12px 'IBM Plex Mono',monospace;color:var(--ui-text-highlighted)"><span>GET /v1/article/</span><span>GET /v1/article/{id}</span></div>
|
||||||
|
</div>
|
||||||
|
<div style="background:var(--ui-bg);border:1px solid var(--ui-border);padding:16px;display:flex;flex-direction:column;gap:10px;min-width:0">
|
||||||
|
<div style="display:flex;align-items:center;gap:8px"><span style="font:600 15px/22px 'IBM Plex Sans',sans-serif;color:var(--ui-text-highlighted)">API key</span><span style="height:20px;padding:0 6px;display:inline-flex;align-items:center;background:var(--rc-success-soft);color:var(--ui-success);font-size:12px;font-weight:500">Full access</span></div>
|
||||||
|
<span style="color:var(--ui-text-toned);text-wrap:pretty">Send <code>Authorization: Bearer rcms_…</code>. Requests act as the user who created the key, with that user's role (owner or admin). A key never has more rights than its creator.</span>
|
||||||
|
<div style="border:1px solid var(--ui-border);min-width:0">
|
||||||
|
<div role="tablist" aria-label="Example language" style="display:flex;gap:16px;padding:0 12px;border-bottom:1px solid var(--ui-border)"><sc-for list="{{ authTabs }}" as="t" hint-placeholder-count="2"><button role="tab" aria-selected="{{ t.on }}" onClick="{{ t.pick }}" style="all:unset;box-sizing:border-box;cursor:pointer;height:36px;display:flex;align-items:center;border-bottom:2px solid {{ t.bd }};margin-bottom:-1px;font-weight:500;color:{{ t.fg }}" style-focus-visible="outline:2px solid var(--ui-primary);outline-offset:-2px">{{ t.t }}</button></sc-for></div>
|
||||||
|
<div style="background:var(--ui-bg-elevated)"><div style="height:32px;padding:0 4px 0 12px;display:flex;align-items:center;justify-content:space-between;border-bottom:1px solid var(--ui-border)"><span style="font:500 12px 'IBM Plex Mono',monospace;color:var(--ui-text-muted)">{{ authLang }}</span><button aria-label="Copy example" onClick="{{ copyAuth }}" style="all:unset;box-sizing:border-box;cursor:pointer;height:28px;padding:0 8px;display:flex;align-items:center;gap:6px;font-weight:500;color:{{ authCopy.fg }}" style-focus-visible="outline:2px solid var(--ui-primary);outline-offset:-2px"><span aria-hidden="true" style="display:inline-block;width:14px;height:14px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/{{ authCopy.icon }}.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/{{ authCopy.icon }}.svg') center / contain no-repeat"></span><span aria-live="polite">{{ authCopy.t }}</span></button></div>
|
||||||
|
<pre tabindex="0" style="margin:0;padding:12px;overflow-x:auto;font:400 12px/19px 'IBM Plex Mono',monospace;color:var(--ui-text)">{{ authCode }}</pre></div>
|
||||||
|
</div>
|
||||||
|
<span style="color:var(--ui-text-muted);text-wrap:pretty">Keys start with <code>rcms_</code> and are shown in full once, when you create them.</span>
|
||||||
|
<a href="#" style="align-self:flex-start;display:inline-flex;align-items:center;gap:6px;min-height:{{ linkH }};font-weight:500;color:var(--ui-text-highlighted)" style-focus-visible="outline:2px solid var(--ui-primary);outline-offset:2px">Manage API keys<span aria-hidden="true" style="display:inline-block;width:14px;height:14px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/arrow-right.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/arrow-right.svg') center / contain no-repeat"></span></a>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div style="display:flex;flex-direction:column;gap:10px;font-size:14px;line-height:22px;color:var(--ui-text-toned)">
|
||||||
|
<div style="display:flex;gap:10px"><span style="display:flex;padding-top:3px;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="text-wrap:pretty">A key can't create, list or revoke API keys, log in, register, verify or reset a password, or call anything under <code>/v1/system</code>. Those routes answer 403 "This action needs a real session." An invalid, unknown, expired or revoked key answers 401, even on public routes, and so does a key whose user was deleted or unverified.</span></div>
|
||||||
|
<div style="display:flex;gap:10px"><span style="display:flex;padding-top:3px;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="text-wrap:pretty">Each key can make 120 requests per minute. Beyond that the API answers 429 with a <code>Retry-After</code> header.</span></div>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<sc-for list="{{ groups }}" as="g" hint-placeholder-count="4">
|
||||||
|
<section data-anchor="{{ g.key }}" style="display:flex;flex-direction:column;gap:10px">
|
||||||
|
<div style="display:flex;align-items:baseline;gap:10px;flex-wrap:wrap"><h2 style="margin:0;font:600 18px/26px 'IBM Plex Sans',sans-serif;color:var(--ui-text-highlighted)">{{ g.title }}</h2><span style="color:var(--ui-text-muted)">{{ g.count }}</span></div>
|
||||||
|
<span style="color:var(--ui-text-toned);text-wrap:pretty">{{ g.desc }}</span>
|
||||||
|
<div style="border:1px solid var(--ui-border);border-top:0;background:var(--ui-bg)">
|
||||||
|
<sc-for list="{{ g.eps }}" as="ep" hint-placeholder-count="6">
|
||||||
|
<div data-anchor="{{ ep.anchor }}" style="border-top:1px solid var(--ui-border)">
|
||||||
|
<button aria-expanded="{{ ep.open }}" aria-label="{{ ep.label }}" onClick="{{ ep.toggle }}" style="all:unset;box-sizing:border-box;cursor:pointer;width:100%;display:{{ rowDisplay }};grid-template-columns:{{ rowCols }};flex-direction:column;align-items:{{ rowAlign }};gap:{{ rowGap }};padding:{{ rowPad }};min-height:44px;background:{{ ep.rowBg }}" style-focus-visible="outline:2px solid var(--ui-primary);outline-offset:-2px">
|
||||||
|
<span style="display:flex;align-items:center;gap:10px;min-width:0"><span style="width:56px;height:22px;flex-shrink:0;display:inline-flex;align-items:center;justify-content:center;background:{{ ep.mBg }};color:{{ ep.mFg }};border:1px solid {{ ep.mBd }};font:500 11px 'IBM Plex Mono',monospace">{{ ep.m }}</span><span style="min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font:500 13px 'IBM Plex Mono',monospace;color:var(--ui-text-highlighted)">{{ ep.p }}</span><sc-if value="{{ mob }}"><span style="flex:1"></span><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:16px;height:16px;color:var(--ui-text-muted);background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/{{ ep.chev }}.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/{{ ep.chev }}.svg') center / contain no-repeat"></span></sc-if></span>
|
||||||
|
<span style="min-width:0;color:var(--ui-text-toned);overflow:hidden;text-overflow:ellipsis;white-space:{{ descWrap }}">{{ ep.d }}</span>
|
||||||
|
<span style="display:flex;gap:6px;flex-wrap:wrap;justify-content:flex-start"><sc-for list="{{ ep.chips }}" as="c" hint-placeholder-count="2"><span style="height:20px;padding:0 6px;display:inline-flex;align-items:center;gap:4px;white-space:nowrap;background:{{ c.bg }};color:{{ c.fg }};border:1px {{ c.bs }} {{ c.bd }};font-size:12px;font-weight:{{ c.fw }}"><sc-if value="{{ c.icon }}"><span aria-hidden="true" style="display:inline-block;width:12px;height:12px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/{{ c.icon }}.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/{{ c.icon }}.svg') center / contain no-repeat"></span></sc-if>{{ c.t }}</span></sc-for></span>
|
||||||
|
<sc-if value="{{ desk }}"><span aria-hidden="true" style="display:inline-block;width:16px;height:16px;color:var(--ui-text-muted);background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/{{ ep.chev }}.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/{{ ep.chev }}.svg') center / contain no-repeat"></span></sc-if>
|
||||||
|
</button>
|
||||||
|
<sc-if value="{{ ep.open }}">
|
||||||
|
<div style="padding:4px {{ detX }} 16px;display:flex;flex-direction:column;gap:14px;border-top:1px solid var(--ui-border-muted)">
|
||||||
|
<div style="padding-top:10px;display:flex;flex-direction:column;gap:6px"><span style="font-weight:600;color:var(--ui-text-highlighted)">{{ ep.bodyTitle }}</span>
|
||||||
|
<sc-if value="{{ ep.hasFields }}"><div style="border:1px solid var(--ui-border)">
|
||||||
|
<div style="display:grid;grid-template-columns:{{ fCols }};gap:4px 12px;padding:6px 10px;background:var(--ui-bg-elevated);color:var(--ui-text-muted);font-weight:500"><span>Name</span><span>Type</span><span>Required</span><sc-if value="{{ desk }}"><span>Rule</span></sc-if></div>
|
||||||
|
<sc-for list="{{ ep.fields }}" as="f" hint-placeholder-count="2"><div style="display:grid;grid-template-columns:{{ fCols }};gap:2px 12px;padding:8px 10px;border-top:1px solid var(--ui-border)"><span style="font:500 12px 'IBM Plex Mono',monospace;color:var(--ui-text-highlighted)">{{ f.n }}</span><span style="font:400 12px 'IBM Plex Mono',monospace;color:var(--ui-text-toned)">{{ f.t }}</span><span style="color:var(--ui-text-toned)">{{ f.req }}</span><span style="grid-column:{{ ruleCol }};color:var(--ui-text-toned);text-wrap:pretty">{{ f.rule }}</span></div></sc-for></div></sc-if>
|
||||||
|
<sc-if value="{{ ep.noFields }}"><span style="color:var(--ui-text-muted)">No request body.</span></sc-if></div>
|
||||||
|
<div style="border:1px solid var(--ui-border);min-width:0">
|
||||||
|
<div role="tablist" aria-label="Example" style="display:flex;gap:16px;padding:0 12px;border-bottom:1px solid var(--ui-border)"><sc-for list="{{ ep.tabs }}" as="t" hint-placeholder-count="3"><button role="tab" aria-selected="{{ t.on }}" onClick="{{ t.pick }}" style="all:unset;box-sizing:border-box;cursor:pointer;height:{{ tabH }};display:flex;align-items:center;border-bottom:2px solid {{ t.bd }};margin-bottom:-1px;font-weight:500;color:{{ t.fg }}" style-focus-visible="outline:2px solid var(--ui-primary);outline-offset:-2px">{{ t.t }}</button></sc-for></div>
|
||||||
|
<div style="background:var(--ui-bg-elevated)"><div style="height:32px;padding:0 4px 0 12px;display:flex;align-items:center;justify-content:space-between;border-bottom:1px solid var(--ui-border)"><span style="font:500 12px 'IBM Plex Mono',monospace;color:var(--ui-text-muted)">{{ ep.lang }}</span><button aria-label="{{ ep.copyLabel }}" onClick="{{ ep.copy }}" style="all:unset;box-sizing:border-box;cursor:pointer;height:28px;padding:0 8px;display:flex;align-items:center;gap:6px;font-weight:500;color:{{ ep.cFg }}" style-focus-visible="outline:2px solid var(--ui-primary);outline-offset:-2px"><span aria-hidden="true" style="display:inline-block;width:14px;height:14px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/{{ ep.cIcon }}.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/{{ ep.cIcon }}.svg') center / contain no-repeat"></span><span aria-live="polite">{{ ep.cT }}</span></button></div>
|
||||||
|
<pre tabindex="0" style="margin:0;padding:12px;overflow-x:auto;font:400 12px/19px 'IBM Plex Mono',monospace;color:var(--ui-text)">{{ ep.code }}</pre></div>
|
||||||
|
</div>
|
||||||
|
<div style="display:flex;flex-direction:column;gap:6px"><span style="font-weight:600;color:var(--ui-text-highlighted)">Errors</span>
|
||||||
|
<sc-for list="{{ ep.errs }}" as="e" hint-placeholder-count="2"><div title="{{ e.cap }}" style="display:flex;align-items:baseline;gap:10px"><span style="width:36px;height:20px;flex-shrink:0;display:inline-flex;align-items:center;justify-content:center;border:1px solid var(--ui-border-accented);color:var(--ui-text-toned);font:500 11px 'IBM Plex Mono',monospace">{{ e.c }}</span><span style="min-width:0;color:var(--ui-text-toned);text-wrap:pretty">{{ e.cap }}</span></div></sc-for></div>
|
||||||
|
</div>
|
||||||
|
</sc-if>
|
||||||
|
</div>
|
||||||
|
</sc-for>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
</sc-for>
|
||||||
|
|
||||||
|
<section data-anchor="session" aria-labelledby="h-sess" style="display:flex;flex-direction:column;gap:10px">
|
||||||
|
<div style="display:flex;align-items:baseline;gap:10px;flex-wrap:wrap"><h2 id="h-sess" style="margin:0;font:600 18px/26px 'IBM Plex Sans',sans-serif;color:var(--ui-text-highlighted)">Session only</h2><span style="color:var(--ui-text-muted)">12 routes, not available to API keys</span></div>
|
||||||
|
<div style="background:var(--ui-bg-muted);border:1px dashed var(--ui-border-accented)">
|
||||||
|
<div style="display:flex;gap:10px;padding:12px 14px;color:var(--ui-text-toned);text-wrap:pretty"><span style="display:flex;padding-top:2px;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/lock.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/lock.svg') center / contain no-repeat"></span></span><span>These routes need a signed-in browser session. With an API key they answer 403 "This action needs a real session."</span></div>
|
||||||
|
<sc-for list="{{ sessGroups }}" as="sg" hint-placeholder-count="3">
|
||||||
|
<div style="border-top:1px dashed var(--ui-border-accented)">
|
||||||
|
<div style="padding:8px 14px 4px;font-size:11px;font-weight:500;letter-spacing:.04em;text-transform:uppercase;color:var(--ui-text-muted)">{{ sg.t }}</div>
|
||||||
|
<sc-for list="{{ sg.rows }}" as="r" hint-placeholder-count="4"><div style="display:{{ rowDisplay }};grid-template-columns:{{ sessCols }};flex-direction:column;align-items:{{ rowAlign }};gap:{{ sessGap }};padding:{{ sessPad }};min-height:36px"><span style="display:flex;align-items:center;gap:10px;min-width:0"><span style="width:56px;flex-shrink:0;font:500 11px 'IBM Plex Mono',monospace;color:var(--ui-text-muted)">{{ r.m }}</span><span style="min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font:400 13px 'IBM Plex Mono',monospace;color:var(--ui-text-toned)">{{ r.p }}</span></span><span style="color:var(--ui-text-muted)">{{ r.d }}</span><span style="height:20px;padding:0 6px;display:inline-flex;align-items:center;gap:4px;align-self:{{ chipSelf }};border:1px dashed var(--ui-border-accented);color:var(--ui-text-muted);font-size:12px;white-space:nowrap"><span aria-hidden="true" style="display:inline-block;width:12px;height:12px;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>Session only</span></div></sc-for>
|
||||||
|
</div>
|
||||||
|
</sc-for>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section data-anchor="errors" aria-labelledby="h-err" style="display:flex;flex-direction:column;gap:10px">
|
||||||
|
<h2 id="h-err" style="margin:0;font:600 18px/26px 'IBM Plex Sans',sans-serif;color:var(--ui-text-highlighted)">Errors</h2>
|
||||||
|
<span style="color:var(--ui-text-toned);text-wrap:pretty">Every error is a plain-text body with a single sentence. The status code is in the HTTP status line, and the Content-Type is text/plain.</span>
|
||||||
|
<div style="border:1px solid var(--ui-border);background:var(--ui-bg);overflow:hidden">
|
||||||
|
<div style="display:grid;grid-template-columns:{{ errCols }};gap:12px;padding:8px 12px;background:var(--ui-bg-elevated);color:var(--ui-text-muted);font-weight:500"><span>Status</span><span>Meaning</span><sc-if value="{{ desk }}"><span>Typical cause</span></sc-if></div>
|
||||||
|
<sc-for list="{{ errRows }}" as="r" hint-placeholder-count="8"><div style="display:grid;grid-template-columns:{{ errCols }};gap:2px 12px;padding:10px 12px;border-top:1px solid var(--ui-border)"><span style="font:500 13px 'IBM Plex Mono',monospace;color:var(--ui-text-highlighted)">{{ r.c }}</span><span style="font-weight:500;color:var(--ui-text-highlighted)">{{ r.m }}</span><span style="grid-column:{{ errCause }};color:var(--ui-text-toned);text-wrap:pretty">{{ r.w }}</span></div></sc-for>
|
||||||
|
</div>
|
||||||
|
<div style="border:1px solid var(--ui-border);min-width:0"><div style="background:var(--ui-bg-elevated)"><div style="height:32px;padding:0 12px;display:flex;align-items:center;border-bottom:1px solid var(--ui-border);font:500 12px 'IBM Plex Mono',monospace;color:var(--ui-text-muted)">Error response · text/plain</div>
|
||||||
|
<pre tabindex="0" style="margin:0;padding:12px;overflow-x:auto;font:400 12px/19px 'IBM Plex Mono',monospace;color:var(--ui-text)">{{ errBody }}</pre></div></div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section data-anchor="notes" aria-labelledby="h-notes" style="display:flex;flex-direction:column;gap:10px">
|
||||||
|
<h2 id="h-notes" style="margin:0;font:600 18px/26px 'IBM Plex Sans',sans-serif;color:var(--ui-text-highlighted)">Notes</h2>
|
||||||
|
<div style="display:flex;flex-direction:column;gap:10px;font-size:14px;line-height:22px;color:var(--ui-text-toned)">
|
||||||
|
<div style="display:flex;gap:10px"><span style="display:flex;padding-top:3px;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="text-wrap:pretty">Images in <code>body</code> use paths like <code>/static/uploadedImages/<uuid>.png</code>. Prefix them with the base URL before rendering.</span></div>
|
||||||
|
<div style="display:flex;gap:10px"><span style="display:flex;padding-top:3px;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="text-wrap:pretty">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.</span></div>
|
||||||
|
<div style="display:flex;gap:10px"><span style="display:flex;padding-top:3px;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="text-wrap:pretty">Article routes accept <code>?format=markdown</code>, <code>?format=html</code> or <code>?format=json</code> to choose how <code>body</code> is returned. With <code>json</code>, <code>body</code> is the stored JSON structure. Articles have <code>body_format: markdown</code> by default.</span></div>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
</div>
|
||||||
|
<sc-if value="{{ desk }}">
|
||||||
|
<nav aria-label="On this page" style="position:sticky;top:32px;width:168px;flex-shrink:0;display:flex;flex-direction:column;gap:2px;border-left:1px solid var(--ui-border)">
|
||||||
|
<span style="padding:0 12px 6px;font-size:11px;font-weight:500;letter-spacing:.04em;text-transform:uppercase;color:var(--ui-text-muted)">On this page</span>
|
||||||
|
<sc-for list="{{ index }}" as="i" hint-placeholder-count="8"><button aria-current="{{ i.cur }}" onClick="{{ i.go }}" style="all:unset;box-sizing:border-box;cursor:pointer;height:28px;padding:0 12px;margin-left:-1px;display:flex;align-items:center;border-left:2px solid {{ i.bd }};color:{{ i.fg }};font-weight:{{ i.fw }}" style-hover="color:var(--ui-text-highlighted)" style-focus-visible="outline:2px solid var(--ui-primary);outline-offset:-2px">{{ i.t }}</button></sc-for>
|
||||||
|
</nav>
|
||||||
|
</sc-if>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</x-dc>
|
||||||
|
<script type="text/x-dc" data-dc-script>
|
||||||
|
class Component extends DCLogic {
|
||||||
|
state = (() => { const i = (this.props.s && this.props.s.int) || {}; return { open: i.open ? { [i.open]: true } : {}, tab: i.open ? { [i.open]: i.tab || 'fetch' } : {}, copied: i.copied || null, jump: !!i.jump, active: i.scroll === 'ep-' + i.open ? 'media' : (i.scroll || 'auth'), authTab: i.authTab || 'curl' } })()
|
||||||
|
rootRef = React.createRef()
|
||||||
|
BASE = 'https://cms.renew.example'
|
||||||
|
KEY = 'rcms_Kf3x9QwL0aBc…'
|
||||||
|
IDX = [['auth', 'Authentication'], ['articles', 'Articles'], ['media', 'Media'], ['users', 'Users and invites'], ['settings', 'Settings'], ['session', 'Session only'], ['errors', 'Errors'], ['notes', 'Notes']]
|
||||||
|
componentDidMount() {
|
||||||
|
const i = (this.props.s && this.props.s.int) || {}
|
||||||
|
const go = () => { if (i.scroll) this.scrollTo(i.scroll, !!this.props.mobile) }
|
||||||
|
go(); setTimeout(go, 250); setTimeout(go, 900)
|
||||||
|
if (document.fonts && document.fonts.ready) document.fonts.ready.then(go)
|
||||||
|
}
|
||||||
|
scrollTo(a, mob) {
|
||||||
|
const r = this.rootRef.current; if (!r) return
|
||||||
|
const el = r.querySelector('[data-anchor="' + a + '"]'); if (!el) return
|
||||||
|
const off = a.indexOf('ep-') === 0 ? 24 : 0
|
||||||
|
r.scrollTop = Math.max(0, this.yOf(el, r) - (mob ? 64 : 32) - off)
|
||||||
|
}
|
||||||
|
yOf(el, r) { const w = el.offsetParent; return el.offsetTop + (w && w !== r ? w.offsetTop : 0) }
|
||||||
|
onScroll = () => {
|
||||||
|
const r = this.rootRef.current; if (!r) return
|
||||||
|
let cur = this.IDX[0][0]
|
||||||
|
for (const [k] of this.IDX) { const el = r.querySelector('[data-anchor="' + k + '"]'); if (el && this.yOf(el, r) <= r.scrollTop + 120) cur = k }
|
||||||
|
if (cur !== this.state.active) this.setState({ active: cur })
|
||||||
|
}
|
||||||
|
flash(k) {
|
||||||
|
this.setState({ copied: k }); clearTimeout(this._t); this._t = setTimeout(() => this.setState({ copied: null }), 2000)
|
||||||
|
}
|
||||||
|
hl(code) {
|
||||||
|
const re = /("[^"\n]*"|'[^'\n]*')|\b(const|await|fetch|curl|new)\b|\b(\d+)\b/g
|
||||||
|
const out = []; let last = 0, m, k = 0
|
||||||
|
while ((m = re.exec(code))) {
|
||||||
|
if (m.index > last) out.push(code.slice(last, m.index))
|
||||||
|
const c = m[1] ? 'var(--ui-success)' : m[2] ? 'var(--ui-info)' : 'var(--ui-warning)'
|
||||||
|
out.push(React.createElement('span', { key: k++, style: { color: c } }, m[0])); last = m.index + m[0].length
|
||||||
|
}
|
||||||
|
out.push(code.slice(last)); return out
|
||||||
|
}
|
||||||
|
eps() {
|
||||||
|
const A = (id, m, p, d, acc, key, errs, fields, x = {}) => ({ id, m, p, d, acc, key, errs: acc === 'Verified user' ? errs.flatMap(e => e[0] === 401 ? [e, e403] : [e]) : errs, fields, ...x })
|
||||||
|
const S = (n, t, req, rule) => ({ n, t, req, rule })
|
||||||
|
const e401 = [401, 'You must be logged in to access this resource.']
|
||||||
|
const e403 = [403, 'You must verify your account to access this resource.']
|
||||||
|
const e404 = [404, 'Article not found']
|
||||||
|
const m404 = [404, 'Image not found']
|
||||||
|
const i404 = [404, 'Invite not found']
|
||||||
|
const mm = 'The request cannot be processed due to a mismatch in the format of the body.'
|
||||||
|
const j = o => JSON.stringify(o, null, 2)
|
||||||
|
const G = {
|
||||||
|
articles: { title: 'Articles', desc: 'Read, write and publish articles. Titles can\'t be changed after creation.', eps: [
|
||||||
|
A('art-list', 'GET', '/v1/article/', 'List articles. Anonymous callers get online articles only.', 'Public', 1, [e401], [], { pub: 1, r: j([{ id: 12, title: 'How we price a bathroom renovation', status: 'online' }]) }),
|
||||||
|
A('art-get', 'GET', '/v1/article/{id}', 'Get one article. Drafts answer 404 to anonymous callers.', 'Public', 1, [e401, e404], [], { pub: 1, r: j({ id: 12, title: 'How we price a bathroom renovation', status: 'online', body: 'A bathroom renovation is priced by room size, plumbing changes and finish level.', body_format: 'markdown' }) }),
|
||||||
|
A('art-create', 'POST', '/v1/article/', 'Create a draft article.', 'Verified user', 1, [[400, mm], e401], [S('title', 'string', 'Yes', '3 to 200 characters. Can\'t be changed later.'), S('body', 'string', 'Yes', 'Up to 10 000 characters.')], { body: { title: 'Choosing tiles for a small bathroom', body: 'Small rooms show every grout line.' }, r: j({ id: 13, status: 'draft' }) }),
|
||||||
|
A('art-update', 'PATCH', '/v1/article/{id}', 'Update the body of an article.', 'Verified user', 1, [[400, mm], e401, e404], [S('body', 'string', 'Yes', 'Up to 10 000 characters.')], { body: { body: 'Updated text.' }, r: j({ id: 12, status: 'draft' }) }),
|
||||||
|
A('art-pub', 'PATCH', '/v1/article/{id}/publish', 'Publish an article.', 'Verified user', 1, [e401, e404], [], { r: j({ id: 12, status: 'online' }) }),
|
||||||
|
A('art-unpub', 'PATCH', '/v1/article/{id}/unpublish', 'Unpublish an article.', 'Verified user', 1, [e401, e404], [], { r: j({ id: 12, status: 'draft' }) }),
|
||||||
|
A('art-del', 'DELETE', '/v1/article/{id}', 'Delete an article and its images.', 'Verified user', 1, [e401, e404], [], { r: '204 No Content' })
|
||||||
|
] },
|
||||||
|
media: { title: 'Media', desc: 'The image library. One image can be used in many articles.', eps: [
|
||||||
|
A('med-list', 'GET', '/v1/media/', 'List images.', 'Verified user', 1, [e401], [], { r: j([{ id: 4, filename: 'north-wall.jpg', size: 3900000 }]) }),
|
||||||
|
A('med-up', 'POST', '/v1/media/', 'Upload an image (multipart).', 'Verified user', 1, [[400, mm], e401, [413, 'The file is over 10 MB.'], [415, 'Not a PNG, JPEG, WEBP or SVG image.']], [S('file', 'file', 'Yes', 'PNG, JPEG, WEBP or SVG, up to 10 MB.')], { multi: true, form: [['file', '@north-wall.jpg']], r: j({ id: 4, filename: 'north-wall.jpg', url: '/static/uploadedImages/3f9c.jpg' }) }),
|
||||||
|
A('med-ren', 'PATCH', '/v1/media/{id}', 'Rename an image. The URL stays the same.', 'Verified user', 1, [[400, mm], e401, m404], [S('filename', 'string', 'Yes', 'The new filename.')], { body: { filename: 'north-wall-01.jpg' }, r: j({ id: 4, filename: 'north-wall-01.jpg' }) }),
|
||||||
|
A('med-del', 'DELETE', '/v1/media/{id}', 'Delete an image. Articles that use it show a broken image.', 'Verified user', 1, [e401, m404], [], { r: '204 No Content' }),
|
||||||
|
A('med-merge', 'POST', '/v1/media/merge', 'Merge identical copies into one image.', 'Verified user', 1, [[400, mm], e401, [409, 'Some of the images to merge changed. Refresh and try again.']], [S('keep_id', 'number', 'Yes', 'Greater than 0. The image to keep.'), S('merge_ids', 'number[]', 'Yes', 'At least 1, each greater than 0. Identical copies to delete. Articles switch to the kept image.')], { body: { keep_id: 4, merge_ids: [9, 11] }, r: j({ merged: 2, articlesUpdated: 5 }) }),
|
||||||
|
A('med-use', 'GET', '/v1/media/{id}/usage', 'List the articles that use an image.', 'Verified user', 1, [e401, m404], [], { r: j([{ id: 12, title: 'How we price a bathroom renovation', status: 'online' }]) })
|
||||||
|
] },
|
||||||
|
users: { title: 'Users and invites', desc: 'People who can sign in, and pending invitations.', eps: [
|
||||||
|
A('usr-list', 'GET', '/v1/user/', 'List users and invites.', 'Verified user', 1, [e401], [], { r: j([{ email: 'marta@renew.example', role: 'owner', status: 'accepted' }]) }),
|
||||||
|
A('usr-me', 'PATCH', '/v1/user/me', 'Update my profile.', 'Verified user', 1, [[400, mm], e401], [S('display_name', 'string', 'Yes', 'Up to 60 characters.')], { body: { display_name: 'Marta Alves' }, r: j({ display_name: 'Marta Alves' }) }),
|
||||||
|
A('usr-inv', 'POST', '/v1/user/invite', 'Invite a user by email.', 'Verified user', 1, [[400, mm], e401, [409, 'This address already has an account.']], [S('email', 'string', 'Yes', 'A valid email address. The link expires after 3 days.')], { body: { email: 'lea.martin@renew.example' }, r: j({ id: 7, status: 'pending' }) }),
|
||||||
|
A('usr-cancel', 'DELETE', '/v1/user/invite/{id}', 'Cancel a pending invite.', 'Verified user', 1, [e401, i404], [], { r: '204 No Content' }),
|
||||||
|
A('usr-renew', 'POST', '/v1/user/invite/{id}/renew', 'Renew an expired invite.', 'Verified user', 1, [e401, i404], [], { r: j({ id: 7, status: 'pending' }) }),
|
||||||
|
A('auth-me', 'GET', '/v1/auth/me', 'Get the current user. With a key, the key\'s owner.', 'Verified user', 1, [e401], [], { r: j({ username: 'marta', email: 'marta@renew.example', role: 'owner' }) })
|
||||||
|
] },
|
||||||
|
settings: { title: 'Settings', desc: 'Read the site settings.', eps: [
|
||||||
|
A('set-get', 'GET', '/v1/settings', 'Get settings.', 'Verified user', 1, [e401], [], { r: j({ version: 'v2.2.0-beta' }) })
|
||||||
|
] }
|
||||||
|
}
|
||||||
|
const MB = { GET: ['var(--ui-bg-inverted)', 'var(--ui-text-inverted)', 'var(--ui-bg-inverted)'], POST: ['var(--rc-success-soft)', 'var(--ui-success)', 'var(--ui-success)'], PATCH: ['var(--rc-warning-soft)', 'var(--ui-warning)', 'var(--ui-warning)'], DELETE: ['var(--rc-error-soft)', 'var(--ui-error)', 'var(--ui-error)'] }
|
||||||
|
const mob = !!this.props.mobile
|
||||||
|
return Object.keys(G).map(key => {
|
||||||
|
const g = G[key]
|
||||||
|
return { key, title: g.title, desc: g.desc, count: g.eps.length + (g.eps.length === 1 ? ' route' : ' routes'), eps: g.eps.map(e => {
|
||||||
|
const open = !!this.state.open[e.id], tab = this.state.tab[e.id] || 'fetch', url = this.BASE + e.p.replace('{id}', '12')
|
||||||
|
const hdr = e.pub ? [] : ['Authorization: Bearer ' + this.KEY]
|
||||||
|
let curl = 'curl ' + (e.m === 'GET' ? '' : '-X ' + e.m + ' ') + '"' + url + '"'
|
||||||
|
hdr.forEach(h => curl += ' \\\n -H "' + h + '"')
|
||||||
|
if (e.body) curl += ' \\\n -H "Content-Type: application/json" \\\n -d \'' + JSON.stringify(e.body) + '\''
|
||||||
|
if (e.form) e.form.forEach(f => curl += ' \\\n -F "' + f[0] + '=' + f[1] + '"')
|
||||||
|
let fe = (e.form ? 'const form = new FormData()\n' + e.form.map(f => f[1][0] === '@' ? "form.append('file', file)" : "form.append('" + f[0] + "', '" + f[1] + "')").join('\n') + '\n\n' : '') + "const res = await fetch('" + url + "'"
|
||||||
|
const opts = []
|
||||||
|
if (e.m !== 'GET') opts.push("method: '" + e.m + "'")
|
||||||
|
if (hdr.length || e.body) opts.push('headers: { ' + [hdr.length ? "Authorization: 'Bearer " + this.KEY + "'" : null, e.body ? "'Content-Type': 'application/json'" : null].filter(Boolean).join(', ') + ' }')
|
||||||
|
if (e.body) opts.push('body: JSON.stringify(' + JSON.stringify(e.body) + ')')
|
||||||
|
if (e.form) opts.push('body: form')
|
||||||
|
fe += opts.length ? ', {\n ' + opts.join(',\n ') + '\n})' : ')'
|
||||||
|
const code = tab === 'curl' ? curl : tab === 'fetch' ? fe : e.r
|
||||||
|
const lang = tab === 'curl' ? 'Shell' : tab === 'fetch' ? 'JavaScript' : 'JSON'
|
||||||
|
const cp = this.state.copied === e.id
|
||||||
|
const chip = (t, o) => ({ t, bg: 'transparent', fg: 'var(--ui-text-toned)', bd: 'var(--ui-border-accented)', bs: 'solid', fw: 400, ...o })
|
||||||
|
const chips = [chip(e.acc, e.acc === 'Owner only' ? { bg: 'var(--ui-bg-elevated)', fg: 'var(--ui-text-highlighted)', fw: 500 } : {}), chip('API key OK', { icon: 'check', bg: 'var(--rc-success-soft)', fg: 'var(--ui-success)', bd: 'transparent', fw: 500 })]
|
||||||
|
return { anchor: 'ep-' + e.id, open, m: e.m, p: e.p, d: e.d, mBg: MB[e.m][0], mFg: MB[e.m][1], mBd: MB[e.m][2], chev: open ? 'chevron-up' : 'chevron-down', rowBg: open ? 'var(--ui-bg-muted)' : 'transparent', label: e.m + ' ' + e.p + '. ' + e.d, chips,
|
||||||
|
toggle: () => this.setState(s => ({ open: { ...s.open, [e.id]: !s.open[e.id] } })),
|
||||||
|
bodyTitle: e.multi ? 'Request body · multipart/form-data, 1 file field' : e.body ? 'Request body · JSON' : 'Request body', hasFields: e.fields.length > 0, noFields: e.fields.length === 0, fields: e.fields,
|
||||||
|
tabs: ['fetch', 'curl', 'Response'].map(t => { const k = t === 'Response' ? 'response' : t, on = (k === tab) || (t === tab); return { t, on, bd: on ? 'var(--ui-primary)' : 'transparent', fg: on ? 'var(--ui-text-highlighted)' : 'var(--ui-text-toned)', pick: () => this.setState(s => ({ tab: { ...s.tab, [e.id]: k } })) } }),
|
||||||
|
lang, code: this.hl(code), copyLabel: 'Copy ' + lang + ' example', cT: cp ? 'Copied' : 'Copy', cIcon: cp ? 'check' : 'copy', cFg: cp ? 'var(--ui-success)' : 'var(--ui-text-toned)',
|
||||||
|
copy: () => { try { navigator.clipboard && navigator.clipboard.writeText(code) } catch (x) { } this.flash(e.id) },
|
||||||
|
errs: e.errs.map(([c, cap]) => ({ c, cap })) }
|
||||||
|
}) }
|
||||||
|
})
|
||||||
|
}
|
||||||
|
renderVals() {
|
||||||
|
const mob = !!this.props.mobile, st = this.state
|
||||||
|
const code = {
|
||||||
|
curl: 'curl "' + this.BASE + '/v1/auth/me" \\\n -H "Authorization: Bearer ' + this.KEY + '"',
|
||||||
|
fetch: "const res = await fetch('" + this.BASE + "/v1/auth/me', {\n headers: { Authorization: 'Bearer " + this.KEY + "' }\n})\nconst me = await res.json()"
|
||||||
|
}[st.authTab]
|
||||||
|
const cp = k => ({ t: st.copied === k ? 'Copied' : 'Copy', icon: st.copied === k ? 'check' : 'copy', fg: st.copied === k ? 'var(--ui-success)' : 'var(--ui-text-toned)' })
|
||||||
|
const bc = cp('base'); if (st.copied !== 'base') bc.fg = 'var(--ui-text-highlighted)'
|
||||||
|
const index = this.IDX.map(([k, t]) => { const on = st.active === k; return { t, on, cur: on ? 'true' : undefined, bd: on ? 'var(--ui-primary)' : 'transparent', fg: on ? 'var(--ui-text-highlighted)' : 'var(--ui-text-toned)', fw: on ? 500 : 400, bg: on ? 'var(--ui-bg-elevated)' : 'transparent', op: on ? 1 : 0, go: () => { this.setState({ jump: false, active: k }); this.scrollTo(k, mob) } } })
|
||||||
|
const sg = (t, rows) => ({ t, rows: rows.map(([m, p, d]) => ({ m, p, d })) })
|
||||||
|
const D = (a) => 'rowDisplay'
|
||||||
|
return {
|
||||||
|
rootRef: this.rootRef, onScroll: this.onScroll, mob, desk: !mob, jumpOpen: st.jump, toggleJump: () => this.setState(s => ({ jump: !s.jump })),
|
||||||
|
activeLabel: (this.IDX.find(x => x[0] === st.active) || this.IDX[0])[1], index,
|
||||||
|
pad: mob ? '20px 16px 96px' : '32px', secGap: mob ? '28px' : '32px', h1: mob ? '20px/28px' : '28px/36px', detX: mob ? '12px' : '16px', linkH: mob ? '44px' : '28px', tabH: mob ? '44px' : '36px',
|
||||||
|
authCols: mob ? 'minmax(0,1fr)' : 'minmax(0,5fr) minmax(0,7fr)',
|
||||||
|
baseCopy: bc, copyBase: () => { try { navigator.clipboard && navigator.clipboard.writeText(this.BASE) } catch (x) { } this.flash('base') },
|
||||||
|
authTabs: ['curl', 'fetch'].map(t => { const on = st.authTab === t; return { t, on, bd: on ? 'var(--ui-primary)' : 'transparent', fg: on ? 'var(--ui-text-highlighted)' : 'var(--ui-text-toned)', pick: () => this.setState({ authTab: t }) } }),
|
||||||
|
authLang: st.authTab === 'curl' ? 'Shell' : 'JavaScript', authCode: this.hl(code), authCopy: cp('auth'), copyAuth: () => { try { navigator.clipboard && navigator.clipboard.writeText(code) } catch (x) { } this.flash('auth') },
|
||||||
|
groups: this.eps(),
|
||||||
|
rowDisplay: mob ? 'flex' : 'grid', rowCols: mob ? 'none' : '300px minmax(0,1fr) auto 16px', rowAlign: mob ? 'stretch' : 'center', rowGap: mob ? '6px' : '16px', rowPad: mob ? '12px 12px' : '0 16px', descWrap: mob ? 'normal' : 'nowrap',
|
||||||
|
fCols: mob ? 'minmax(0,1fr) auto auto' : '120px 72px 72px minmax(0,1fr)', ruleCol: mob ? '1 / -1' : 'auto',
|
||||||
|
sessGroups: [sg('System · owner only', [['GET', '/v1/system/update', 'Update status'], ['POST', '/v1/system/update/check', 'Check for update'], ['POST', '/v1/system/update/download', 'Download update'], ['POST', '/v1/system/update/restart', 'Restart']]), sg('Sign in and account', [['POST', '/v1/auth/login', 'Log in'], ['POST', '/v1/auth/logout', 'Log out'], ['POST', '/v1/auth/register', 'Register'], ['POST', '/v1/auth/verify', 'Verify email'], ['POST', '/v1/auth/password-reset', 'Reset password']]), sg('API key management', [['GET', '/v1/api-key', 'List keys'], ['POST', '/v1/api-key', 'Create a key'], ['DELETE', '/v1/api-key/{id}', 'Revoke a key']])],
|
||||||
|
sessCols: mob ? 'none' : '280px minmax(0,1fr) auto', sessGap: mob ? '2px' : '16px', sessPad: mob ? '8px 14px' : '0 14px', chipSelf: mob ? 'flex-start' : 'center',
|
||||||
|
errCols: mob ? '56px minmax(0,1fr)' : '64px 200px minmax(0,1fr)', errCause: mob ? '2' : 'auto',
|
||||||
|
errRows: [
|
||||||
|
{ c: 400, m: 'Bad request', w: '"The request cannot be processed due to a mismatch in the format of the body." or "The expiry must be a date in the future."' },
|
||||||
|
{ c: 401, m: 'Unauthorized', w: '"You must be logged in to access this resource." Sent for an invalid, unknown, expired or revoked key, even on public routes, and for a key whose user was deleted or unverified.' },
|
||||||
|
{ c: 403, m: 'Forbidden', w: '"This action needs a real session." (a session-only route called with a key), "Only the owner can do this." or "You must verify your account to access this resource."' },
|
||||||
|
{ c: 404, m: 'Not found', w: '"Article not found", "Image not found", "Invite not found" or "API key not found". Drafts answer 404 to anonymous callers.' },
|
||||||
|
{ c: 429, m: 'Too many requests', w: '"Too many requests. Please try again later." A per-key limit of 120 requests per minute also sends a Retry-After header.' },
|
||||||
|
{ c: 500, m: 'Server error', w: '"Internal server error"' }
|
||||||
|
],
|
||||||
|
errBody: 'HTTP/1.1 403 Forbidden\nContent-Type: text/plain\n\nThis action needs a real session.'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
@@ -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="{"$preview":{"width":1440,"height":900},"s":{"editor":null,"tsType":"object"},"mobile":{"editor":null,"tsType":"boolean"}}">
|
||||||
|
class Component extends DCLogic {
|
||||||
|
renderVals() {
|
||||||
|
const s = this.props.s || {}, m = !!this.props.mobile, 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>
|
||||||
@@ -46,7 +46,7 @@
|
|||||||
<main ref="{{ stageRef }}" style="flex:1;min-width:0;height:100vh;overflow:auto;display:flex;align-items:center;justify-content:center;padding:24px">
|
<main ref="{{ stageRef }}" style="flex:1;min-width:0;height:100vh;overflow:auto;display:flex;align-items:center;justify-content:center;padding:24px">
|
||||||
<div style="flex-shrink:0;width:{{ boxW }};height:{{ boxH }};box-shadow:0 8px 40px rgb(0 0 0 / 0.15);overflow:hidden">
|
<div style="flex-shrink:0;width:{{ boxW }};height:{{ boxH }};box-shadow:0 8px 40px rgb(0 0 0 / 0.15);overflow:hidden">
|
||||||
<div onClick="{{ onStage }}" class="{{ hsClass }}" style="width:{{ devW }};height:{{ devH }};zoom:{{ zoom }};position:relative;overflow:hidden;background:var(--ui-bg-muted)">
|
<div onClick="{{ onStage }}" class="{{ hsClass }}" style="width:{{ devW }};height:{{ devH }};zoom:{{ zoom }};position:relative;overflow:hidden;background:var(--ui-bg-muted)">
|
||||||
<sc-if value="{{ isAuth }}"><div style="width:100%;height:100%;overflow:hidden;background:{{ authBg }};padding-top:{{ authTop }};display:flex;flex-direction:column;align-items:center"><dc-import name="AuthCard" s="{{ authS }}" mobile="{{ mobile }}" hint-size="400px,520px"></dc-import></div></sc-if>
|
<sc-if value="{{ isAuth }}"><div style="width:100%;height:100%;overflow:hidden;background:{{ authBg }};padding-top:{{ authTop }};display:flex;flex-direction:column;align-items:center"><dc-import name="AuthCard" lang="{{ lang }}" lang-open="{{ langOpen }}" s="{{ authS }}" mobile="{{ mobile }}" hint-size="400px,520px"></dc-import></div></sc-if>
|
||||||
<sc-if value="{{ isApp }}"><dc-import name="AppFrame" s="{{ appS }}" mobile="{{ mobile }}" hint-size="100%,100%"></dc-import></sc-if>
|
<sc-if value="{{ isApp }}"><dc-import name="AppFrame" s="{{ appS }}" mobile="{{ mobile }}" hint-size="100%,100%"></dc-import></sc-if>
|
||||||
<sc-if value="{{ isEmail }}"><div style="width:100%;height:100%;display:flex;flex-direction:column;background:var(--ui-bg)"><div style="flex-shrink:0;padding:14px 20px;border-bottom:1px solid var(--ui-border);display:flex;flex-direction:column;gap:2px"><span style="font-weight:600;font-size:15px;color:var(--ui-text-highlighted)">{{ emailSubject }}</span><span style="color:var(--ui-text-muted)">From RenewCMS · to marta@renew.example</span></div><iframe title="Email" srcDoc="{{ emailHtml }}" style="flex:1;width:100%;border:0"></iframe></div></sc-if>
|
<sc-if value="{{ isEmail }}"><div style="width:100%;height:100%;display:flex;flex-direction:column;background:var(--ui-bg)"><div style="flex-shrink:0;padding:14px 20px;border-bottom:1px solid var(--ui-border);display:flex;flex-direction:column;gap:2px"><span style="font-weight:600;font-size:15px;color:var(--ui-text-highlighted)">{{ emailSubject }}</span><span style="color:var(--ui-text-muted)">From RenewCMS · to marta@renew.example</span></div><iframe title="Email" srcDoc="{{ emailHtml }}" style="flex:1;width:100%;border:0"></iframe></div></sc-if>
|
||||||
<sc-if value="{{ mnav }}">
|
<sc-if value="{{ mnav }}">
|
||||||
@@ -187,6 +187,10 @@ 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 === 'usermenu') return this.setState({ userMenu: !s.userMenu })
|
||||||
|
if (a === 'langmenu') return this.setState({ langOpen: !s.langOpen })
|
||||||
|
if (a && a.startsWith('lang-')) return this.setState({ lang: a.slice(5), langOpen: false })
|
||||||
|
if (s.langOpen) this.setState({ langOpen: false })
|
||||||
|
if (a && a.startsWith('theme-')) return this.setState({ mode: a.slice(6) })
|
||||||
if (s.userMenu) this.setState({ userMenu: false })
|
if (s.userMenu) this.setState({ userMenu: false })
|
||||||
if (a === 'pf-reset') return this.setState({ pfReset: 'sent' })
|
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 })
|
||||||
@@ -427,8 +431,8 @@ class Component extends DCLogic {
|
|||||||
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, lang: s.lang || 'en', langOpen: !!s.langOpen,
|
||||||
authS: isAuth ? this.authS() : {}, appS: isApp ? { ...this.appS(), userMenu: s.userMenu } : {},
|
authS: isAuth ? this.authS() : {}, appS: isApp ? { ...this.appS(), userMenu: s.userMenu, mode: s.mode, lang: s.lang || 'en' } : {},
|
||||||
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',
|
||||||
|
|||||||
@@ -0,0 +1,106 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html>
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||||
|
<script src="./support.js"></script>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<x-dc>
|
||||||
|
<helmet>
|
||||||
|
<meta name="design_doc_mode" content="canvas">
|
||||||
|
<link rel="icon" href="brand/favicon.svg">
|
||||||
|
<link href="https://fonts.googleapis.com/css2?family=IBM+Plex+Sans:wght@400;500;600&family=IBM+Plex+Mono:wght@400;500&family=Source+Serif+4:ital,opsz,wght@0,8..60,400;0,8..60,600;1,8..60,400&display=swap" rel="stylesheet">
|
||||||
|
<style>body{margin:0;font-family:'IBM Plex Sans',sans-serif;font-size:13px;line-height:20px}*{box-sizing:border-box}a{color:inherit;text-underline-offset:3px}a:hover{opacity:.8}code{font-family:'IBM Plex Mono',monospace;font-size:12px}</style>
|
||||||
|
</helmet>
|
||||||
|
<div ref="{{ rootRef }}" data-screen-label="Back-office screens" style="--ui-bg:#ffffff;--ui-bg-muted:#fafafa;--ui-bg-elevated:#f3f2f0;--ui-bg-accented:#e6e4e0;--ui-bg-inverted:#111111;--ui-text-dimmed:#999999;--ui-text-muted:#666666;--ui-text-toned:#444444;--ui-text:#222222;--ui-text-highlighted:#111111;--ui-text-inverted:#ffffff;--ui-border:#e6e4e0;--ui-border-muted:#f3f2f0;--ui-border-accented:#8a8783;--ui-primary:#111111;--ui-secondary:#635643;--ui-success:#315b33;--ui-info:#34536d;--ui-warning:#6c4700;--ui-error:#882c21;--rc-sand:#e8dfd1;--rc-success-soft:#eaefea;--rc-info-soft:#ebeef0;--rc-warning-soft:#f0ede6;--rc-error-soft:#f3eae9;--rc-overlay:rgb(10 10 10 / 0.4);--rc-shadow-pop:0 4px 16px rgb(17 17 17 / 0.08), 0 1px 2px rgb(17 17 17 / 0.06);--rc-shadow-modal:0 16px 48px rgb(17 17 17 / 0.18);--rc-canvas:#ecebe8;background:var(--rc-canvas);color:var(--ui-text);padding:64px;display:flex;flex-direction:column;gap:72px;width:max-content;min-width:100%">
|
||||||
|
|
||||||
|
<div style="display:flex;align-items:flex-end;gap:32px;max-width:1400px">
|
||||||
|
<div style="flex:1;display:flex;flex-direction:column;gap:10px">
|
||||||
|
<h1 style="margin:0;font:600 36px/44px 'IBM Plex Sans',sans-serif;letter-spacing:-0.02em;color:var(--ui-text-highlighted)">Screen: API keys</h1>
|
||||||
|
<p style="margin:0;max-width:880px;font-size:16px;line-height:26px;color:var(--ui-text-toned);text-wrap:pretty">The screen the Authentication section of <a href="RenewCMS Screens Back-office.dc.html">the Integration screen</a> links to. 1440 px at 50%, 390 px at 75%. The theme switch shows every state in dark mode.</p>
|
||||||
|
</div>
|
||||||
|
<div role="radiogroup" aria-label="Theme" style="display:flex;border:1px solid var(--ui-border-accented);background:var(--ui-bg)">
|
||||||
|
<sc-for list="{{ modes }}" as="m" hint-placeholder-count="3">
|
||||||
|
<button role="radio" aria-checked="{{ m.on }}" onClick="{{ m.pick }}" style="all:unset;cursor:pointer;height:36px;padding:0 14px;display:flex;align-items:center;font-weight:500;font-size:14px;background:{{ m.bg }};color:{{ m.fg }}" style-focus-visible="outline:2px solid var(--ui-primary);outline-offset:2px">{{ m.label }}</button>
|
||||||
|
</sc-for>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<sc-for list="{{ groups }}" as="g" hint-placeholder-count="7">
|
||||||
|
<section data-screen-label="{{ g.label }}" style="display:flex;flex-direction:column;gap:28px">
|
||||||
|
<div style="display:flex;flex-direction:column;gap:6px;max-width:1100px">
|
||||||
|
<h2 style="margin:0;font:600 28px/36px 'IBM Plex Sans',sans-serif;color:var(--ui-text-highlighted)">{{ g.title }}</h2>
|
||||||
|
<div style="display:flex;gap:16px;flex-wrap:wrap;font:400 14px/22px 'IBM Plex Mono',monospace;color:var(--ui-text-toned)"><span>{{ g.route }}</span><span style="color:var(--ui-text-muted)">{{ g.api }}</span></div>
|
||||||
|
<sc-if value="{{ g.note }}"><p style="margin:4px 0 0;font-size:15px;line-height:24px;color:var(--ui-text-toned);text-wrap:pretty">{{ g.note }}</p></sc-if>
|
||||||
|
</div>
|
||||||
|
<div style="display:flex;flex-wrap:wrap;gap:40px;align-items:flex-start">
|
||||||
|
<sc-for list="{{ g.states }}" as="st" hint-placeholder-count="4">
|
||||||
|
<div style="display:flex;flex-direction:column;gap:12px">
|
||||||
|
<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="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"><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>
|
||||||
|
</sc-for>
|
||||||
|
</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>
|
||||||
|
</sc-for>
|
||||||
|
|
||||||
|
</div>
|
||||||
|
</x-dc>
|
||||||
|
<script type="text/x-dc" data-dc-script data-props="{"theme":{"editor":"enum","options":["system","light","dark"],"default":"light","tsType":"'system' | 'light' | 'dark'"}}">
|
||||||
|
class Component extends DCLogic {
|
||||||
|
state = { mode: this.props.theme ?? 'light' }
|
||||||
|
rootRef = React.createRef()
|
||||||
|
light = { '--ui-bg': '#ffffff', '--ui-bg-muted': '#fafafa', '--ui-bg-elevated': '#f3f2f0', '--ui-bg-accented': '#e6e4e0', '--ui-bg-inverted': '#111111', '--ui-text-dimmed': '#999999', '--ui-text-muted': '#666666', '--ui-text-toned': '#444444', '--ui-text': '#222222', '--ui-text-highlighted': '#111111', '--ui-text-inverted': '#ffffff', '--ui-border': '#e6e4e0', '--ui-border-muted': '#f3f2f0', '--ui-border-accented': '#8a8783', '--ui-primary': '#111111', '--ui-secondary': '#635643', '--ui-success': '#315b33', '--ui-info': '#34536d', '--ui-warning': '#6c4700', '--ui-error': '#882c21', '--rc-sand': '#e8dfd1', '--rc-success-soft': '#eaefea', '--rc-info-soft': '#ebeef0', '--rc-warning-soft': '#f0ede6', '--rc-error-soft': '#f3eae9', '--rc-overlay': 'rgb(10 10 10 / 0.4)', '--rc-shadow-pop': '0 4px 16px rgb(17 17 17 / 0.08), 0 1px 2px rgb(17 17 17 / 0.06)', '--rc-shadow-modal': '0 16px 48px rgb(17 17 17 / 0.18)', '--rc-canvas': '#ecebe8' }
|
||||||
|
dark = { '--ui-bg': '#111111', '--ui-bg-muted': '#0a0a0a', '--ui-bg-elevated': '#1a1a1a', '--ui-bg-accented': '#222222', '--ui-bg-inverted': '#fafafa', '--ui-text-dimmed': '#666666', '--ui-text-muted': '#999999', '--ui-text-toned': '#cfccc7', '--ui-text': '#e6e4e0', '--ui-text-highlighted': '#fafafa', '--ui-text-inverted': '#111111', '--ui-border': '#333333', '--ui-border-muted': '#222222', '--ui-border-accented': '#666666', '--ui-primary': '#fafafa', '--ui-secondary': '#d4c5b0', '--ui-success': '#a3caa3', '--ui-info': '#a5c2db', '--ui-warning': '#dfb67d', '--ui-error': '#fba394', '--rc-sand': '#d4c5b0', '--rc-success-soft': '#1f241f', '--rc-info-soft': '#202428', '--rc-warning-soft': '#2a251e', '--rc-error-soft': '#2c201f', '--rc-overlay': 'rgb(0 0 0 / 0.6)', '--rc-shadow-pop': '0 4px 16px rgb(0 0 0 / 0.5)', '--rc-shadow-modal': '0 16px 48px rgb(0 0 0 / 0.6)', '--rc-canvas': '#1c1c1c' }
|
||||||
|
resolved() {
|
||||||
|
if (this.state.mode === 'system') return window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light'
|
||||||
|
return this.state.mode
|
||||||
|
}
|
||||||
|
apply() {
|
||||||
|
const el = this.rootRef.current
|
||||||
|
if (!el) return
|
||||||
|
const vars = this.resolved() === 'dark' ? this.dark : this.light
|
||||||
|
for (const k in vars) el.style.setProperty(k, vars[k])
|
||||||
|
document.body.style.background = vars['--rc-canvas']
|
||||||
|
}
|
||||||
|
componentDidMount() { this.apply() }
|
||||||
|
componentDidUpdate(p) {
|
||||||
|
if (p.theme !== this.props.theme && this.props.theme) this.setState({ mode: this.props.theme })
|
||||||
|
this.apply()
|
||||||
|
}
|
||||||
|
groups() {
|
||||||
|
const withM = (st, mo = {}) => ({ ...st, m: { ...st, ...mo } })
|
||||||
|
return this.finish([
|
||||||
|
{ label: 'API keys', title: 'API keys', route: '/integration/api-keys', api: 'GET /v1/api-key · POST /v1/api-key · DELETE /v1/api-key/{id} (session only)', note: 'Recommendation: place it under Integration, as a sub-page linked from the Authentication section and from the sidebar item. Keys exist to call the API, so they belong next to the reference. Settings is owner-only today, but admins can also create keys. The screen is session only: an API key cannot manage keys. Key name: required, up to 60 characters. Expiry: optional, in the future. A key is shown in full once; afterwards only its prefix is visible.', states: [
|
||||||
|
withM({ kind: 'apikeys', nav: 'integration', crumbs: ['Integration','API keys'], mTitle: 'API keys', mLead: 'arrow-left', name: "Owner: list", trigger: "Owners see every user's keys and a \"Created by\" column. Expired keys keep their Revoke action.", ak: {"view":"owner"} }, { ak: {"view":"owner"} }),
|
||||||
|
withM({ kind: 'apikeys', nav: 'integration', crumbs: ['Integration','API keys'], mTitle: 'API keys', mLead: 'arrow-left', name: "Admin: own keys only", trigger: "Admins see only the keys they created, with no \"Created by\" column.", ak: {"view":"admin"} }, { ak: {"view":"admin"} }),
|
||||||
|
withM({ kind: 'apikeys', nav: 'integration', crumbs: ['Integration','API keys'], mTitle: 'API keys', mLead: 'arrow-left', name: "Loading", trigger: "The list request is in flight. Skeleton rows appear after 150 ms.", ak: {"state":"loading"} }, { ak: {"state":"loading"} }),
|
||||||
|
withM({ kind: 'apikeys', nav: 'integration', crumbs: ['Integration','API keys'], mTitle: 'API keys', mLead: 'arrow-left', name: "Empty", trigger: "No keys yet.", ak: {"state":"empty"} }, { ak: {"state":"empty"} }),
|
||||||
|
withM({ kind: 'apikeys', nav: 'integration', crumbs: ['Integration','API keys'], mTitle: 'API keys', mLead: 'arrow-left', name: "Error", trigger: "A 500 or network failure on the list request.", ak: {"state":"error"} }, { ak: {"state":"error"} }),
|
||||||
|
withM({ kind: 'apikeys', nav: 'integration', crumbs: ['Integration','API keys'], mTitle: 'API keys', mLead: 'arrow-left', name: "Create key", trigger: "\"Create key\" in the page header, or the bottom action on mobile. Name is required and limited to 60 characters; expiry is optional.", ak: {"modal":"create"} }, { ak: {"modal":"create"} }),
|
||||||
|
withM({ kind: 'apikeys', nav: 'integration', crumbs: ['Integration','API keys'], mTitle: 'API keys', mLead: 'arrow-left', name: "Create key: validation", trigger: "On submit or blur. Nothing is sent. The name is empty and the expiry is in the past.", ak: {"modal":"invalid"} }, { ak: {"modal":"invalid"} }),
|
||||||
|
withM({ kind: 'apikeys', nav: 'integration', crumbs: ['Integration','API keys'], mTitle: 'API keys', mLead: 'arrow-left', name: "Create key: name too long", trigger: "Over 60 characters. Checked as you type.", ak: {"modal":"toolong"} }, { ak: {"modal":"toolong"} }),
|
||||||
|
withM({ kind: 'apikeys', nav: 'integration', crumbs: ['Integration','API keys'], mTitle: 'API keys', mLead: 'arrow-left', name: "One-time reveal", trigger: "201: the full key is shown once. Closing the dialog discards it from the screen.", ak: {"modal":"reveal"} }, { ak: {"modal":"reveal"} }),
|
||||||
|
withM({ kind: 'apikeys', nav: 'integration', crumbs: ['Integration','API keys'], mTitle: 'API keys', mLead: 'arrow-left', name: "One-time reveal: copied", trigger: "Copy was pressed. The button reads \"Copied\" for 2 s and this is announced.", ak: {"modal":"copied"} }, { ak: {"modal":"copied"} }),
|
||||||
|
withM({ kind: 'apikeys', nav: 'integration', crumbs: ['Integration','API keys'], mTitle: 'API keys', mLead: 'arrow-left', name: "Revoke: confirm", trigger: "Revoke on an active or expired row.", ak: {"modal":"revoke"} }, { ak: {"modal":"revoke"} }),
|
||||||
|
withM({ kind: 'apikeys', nav: 'integration', crumbs: ['Integration','API keys'], mTitle: 'API keys', mLead: 'arrow-left', name: "Revoked", trigger: "204: the key stays in the list, greyed, with no Revoke action. A toast confirms.", ak: {"revoked":1,"toast":1} }, { ak: {"revoked":1,"toast":1} })
|
||||||
|
] }
|
||||||
|
])
|
||||||
|
}
|
||||||
|
finish(gs) { return gs.map(g => ({ ...g, states: g.states.map(st => ({ notMedia: !st.isMedia, ...st, m: { ...st.m } })) })) }
|
||||||
|
renderVals() {
|
||||||
|
const modes = [['system', 'System'], ['light', 'Light'], ['dark', 'Dark']].map(([k, label]) => {
|
||||||
|
const on = this.state.mode === k
|
||||||
|
return { label, on, bg: on ? 'var(--ui-primary)' : 'transparent', fg: on ? 'var(--ui-bg)' : 'var(--ui-text-toned)', pick: () => this.setState({ mode: k }) }
|
||||||
|
})
|
||||||
|
return { rootRef: this.rootRef, modes, groups: this.groups() }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
@@ -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>
|
||||||
|
|
||||||
@@ -96,18 +97,40 @@ class Component extends DCLogic {
|
|||||||
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 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 })
|
||||||
const people = [
|
const people = [
|
||||||
{ email: 'sam.oliveira@renew.example', st: 'pending', c: '27 Sep 2026' },
|
{ email: 'sam.oliveira@renew.example', role: 'admin', st: 'pending', c: '27 Sep 2026' },
|
||||||
{ email: 'p.huber@gmail.com', st: 'expired', c: '3 Aug 2026' },
|
{ email: 'p.huber@gmail.com', display: 'Paul Huber', role: 'admin', st: 'expired', c: '3 Aug 2026' },
|
||||||
{ u: 'ines', display: 'Inès Duarte', st: 'accepted', c: '18 Jun 2026' },
|
{ email: 'ines.duarte@renew.example', display: 'Inès Duarte', role: 'admin', st: 'accepted', c: '18 Jun 2026' },
|
||||||
{ u: 'jonas', st: 'accepted', c: '2 Apr 2026' },
|
{ email: 'jonas@renew.example', role: 'admin', st: 'accepted', c: '2 Apr 2026' },
|
||||||
{ u: 'marta', st: 'accepted', c: '12 Mar 2026', you: true }
|
{ 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 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 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 invF = (value, extra = {}) => [{ label: 'Email', value, ...extra }]
|
||||||
const P = (pf = {}, o = {}) => withM({ kind: 'profile', nav: 'profile', crumbs: ['Profile'], mTitle: 'Profile', ...o, pf })
|
const P = (pf = {}, o = {}) => withM({ kind: 'profile', nav: 'profile', crumbs: ['Profile'], mTitle: 'Profile', ...o, pf })
|
||||||
const dname = 'Marta Alves'
|
const dname = 'Marta Alves'
|
||||||
return [
|
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 rdy = o.title === 'Version 2.3.0 is ready to install' && o.btns && o.btns.length; if (rdy) o = { ...o, tone: 'warning', icon: 'clock', pendingTag: true, inBtn: o.btns[0], btns: undefined }; 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 })
|
||||||
] },
|
] },
|
||||||
@@ -115,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.' }),
|
||||||
@@ -164,11 +189,93 @@ 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: 'Integration', title: 'Connect your website', route: '/integration', api: 'none (static)', note: 'Written for a developer. The base URL is window.location.origin.', states: [
|
{ 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: [
|
||||||
withM({ kind: 'integration', nav: 'integration', crumbs: ['Integration'], mTitle: 'Integration', name: 'Default', trigger: 'Opened from the sidebar or the Home card.' }),
|
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.' }),
|
||||||
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.' })
|
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: 'Users', title: 'Users', route: '/users', api: 'GET /v1/user/ · POST /v1/user/invite', note: 'One shared workspace: every user sees the same articles and this same list. Rows have no actions yet. Pending and expired invites show the email address, because a username only exists once the invite is accepted. An invite is Pending until its link is used, Expired after 3 days, and Accepted once the account is created.', states: [
|
{ 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: 'Integration: API reference', route: '/integration', api: 'none (static). Replaces "Connect your website".', note: 'Navigation: a sticky section index on the right on desktop, and a "Jump to" select on mobile. A long reference is read in one scroll and searched with the browser, so tabs would hide content and break find-in-page; the index keeps every group on one page, links to anchors and shows where you are. Written for a developer. The base URL is window.location.origin. The API keys screen has its own board.', states: [
|
||||||
|
withM({ kind: 'integration', nav: 'integration', crumbs: ['Integration'], mTitle: 'Integration', name: "1. Default", trigger: "Opened from the sidebar or the Home card. Every endpoint card is collapsed. Desktop shows the sticky index on the right; mobile shows the \"Jump to\" select above the content.", int: {} }, { int: {} }),
|
||||||
|
withM({ kind: 'integration', nav: 'integration', crumbs: ['Integration'], mTitle: 'Integration', name: "2. Group scrolled, one card expanded", trigger: "POST /v1/media/ opened in the Media group: multipart body with 1 file field, curl tab shown. Only one example block is visible per card. Other cards stay collapsed.", int: {"scroll":"media","open":"med-up","tab":"curl"} }, { int: {"scroll":"ep-med-up","open":"med-up","tab":"curl"} }),
|
||||||
|
withM({ kind: 'integration', nav: 'integration', crumbs: ['Integration'], mTitle: 'Integration', name: "3a. Copied: base URL", trigger: "The base URL was copied. The button reads \"Copied\" for 2 s and this is announced.", int: {"copied":"base"} }, { int: {"copied":"base"} }),
|
||||||
|
withM({ kind: 'integration', nav: 'integration', crumbs: ['Integration'], mTitle: 'Integration', name: "3b. Copied: CodeBlock", trigger: "The Copy button in the API key example after a click. Back to \"Copy\" after 2 s.", int: {"scroll":"auth","copied":"auth"} }, { int: {"scroll":"auth","copied":"auth"} }),
|
||||||
|
withM({ kind: 'integration', nav: 'integration', crumbs: ['Integration'], mTitle: 'Integration', name: "4. Authentication", trigger: "The API key card with its example, the \"Manage API keys\" link (goes to the API keys board) and the two notes.", int: {"scroll":"auth"} }, { int: {"scroll":"auth"} }),
|
||||||
|
withM({ kind: 'integration', nav: 'integration', crumbs: ['Integration'], mTitle: 'Integration', name: "5. Session only", trigger: "Routes API keys cannot call. Dashed, muted and locked, so they read as unavailable and not as an error.", int: {"scroll":"session"} }, { int: {"scroll":"session"} }),
|
||||||
|
withM({ kind: 'integration', nav: 'integration', crumbs: ['Integration'], mTitle: 'Integration', name: "6. Errors", trigger: "Status table and the plain-text error response (status line plus a one-sentence body). Key-specific causes are in the 401, 403 and 429 rows.", int: {"scroll":"errors"} }, { int: {"scroll":"errors"} }),
|
||||||
|
withM({ kind: 'integration', nav: 'integration', crumbs: ['Integration'], mTitle: 'Integration', name: "7. Navigation", trigger: "Desktop: the sticky index with the active item (Media). Mobile: the \"Jump to\" select open. Keyboard: the index buttons and the select are in the tab order, Enter jumps, Escape closes the list.", int: {"scroll":"media"} }, { int: {"scroll":"media","jump":true} })
|
||||||
|
] },
|
||||||
|
{ 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(), 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: { 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: { rows: people.slice(-1), only: true } }), name: 'Only you', trigger: 'Nobody has been invited yet. The admin who registered is always listed.' }),
|
||||||
@@ -178,7 +285,59 @@ class Component extends DCLogic {
|
|||||||
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({ 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({ 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: 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({ users: { rows: [{ email: 'lea.martin@renew.example', 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.' })
|
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 …/update/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: [
|
{ 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.' }),
|
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.' }),
|
||||||
@@ -193,7 +352,7 @@ class Component extends DCLogic {
|
|||||||
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: '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: '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.' }),
|
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: 'Accounts with a display name show it first, with the username beside it in grey. Accounts without one show the username.' })
|
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' } }),
|
||||||
@@ -201,8 +360,9 @@ class Component extends DCLogic {
|
|||||||
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
|
||||||
|
|||||||
+132
-3
@@ -80,8 +80,80 @@ Every state is drawn at desktop and mobile on the screen boards, with final copy
|
|||||||
| 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) |
|
||||||
| Integration | `/integration` | Default | Page load | [integration](screens/integration.md) |
|
| Media | `/media` | Grid, many images | Default view | [media](screens/media.md) |
|
||||||
| Integration | `/integration` | Copied | Copy clicked (2 s) | [integration](screens/integration.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, every endpoint card collapsed | [integration](screens/integration.md) |
|
||||||
|
| Integration | `/integration` | Group scrolled, one card expanded | A card opened, one example visible | [integration](screens/integration.md) |
|
||||||
|
| Integration | `/integration` | Copied: base URL | Copy clicked (2 s) | [integration](screens/integration.md) |
|
||||||
|
| Integration | `/integration` | Copied: CodeBlock | Copy clicked in a code block (2 s) | [integration](screens/integration.md) |
|
||||||
|
| Integration | `/integration` | Authentication | API key card, link and notes | [integration](screens/integration.md) |
|
||||||
|
| Integration | `/integration` | Session only | Routes API keys cannot call | [integration](screens/integration.md) |
|
||||||
|
| Integration | `/integration` | Errors | Status table and plain-text error shape | [integration](screens/integration.md) |
|
||||||
|
| Integration | `/integration` | Navigation | Section index active item; mobile Jump to open | [integration](screens/integration.md) |
|
||||||
|
| API keys | `/integration/api-keys` | Owner: list | Owner sees every key, with Created by | [integration-api-keys](screens/integration-api-keys.md) |
|
||||||
|
| API keys | `/integration/api-keys` | Admin: own keys only | Admin sees only their own keys | [integration-api-keys](screens/integration-api-keys.md) |
|
||||||
|
| API keys | `/integration/api-keys` | Loading | First load or retry | [integration-api-keys](screens/integration-api-keys.md) |
|
||||||
|
| API keys | `/integration/api-keys` | Empty | No keys yet | [integration-api-keys](screens/integration-api-keys.md) |
|
||||||
|
| API keys | `/integration/api-keys` | Error | 500 or network | [integration-api-keys](screens/integration-api-keys.md) |
|
||||||
|
| API keys | `/integration/api-keys` | Create key | Modal opened | [integration-api-keys](screens/integration-api-keys.md) |
|
||||||
|
| API keys | `/integration/api-keys` | Create key: validation | Name empty or expiry not in the future | [integration-api-keys](screens/integration-api-keys.md) |
|
||||||
|
| API keys | `/integration/api-keys` | Create key: name too long | More than 60 characters | [integration-api-keys](screens/integration-api-keys.md) |
|
||||||
|
| API keys | `/integration/api-keys` | One-time reveal | Key created, shown once | [integration-api-keys](screens/integration-api-keys.md) |
|
||||||
|
| API keys | `/integration/api-keys` | One-time reveal: copied | Copy clicked (2 s) | [integration-api-keys](screens/integration-api-keys.md) |
|
||||||
|
| API keys | `/integration/api-keys` | Revoke: confirm | Revoke pressed on a key | [integration-api-keys](screens/integration-api-keys.md) |
|
||||||
|
| API keys | `/integration/api-keys` | Revoked | Confirmed, key stays listed as revoked | [integration-api-keys](screens/integration-api-keys.md) |
|
||||||
| Users | `/users` | Default | List loaded, newest first | [users](screens/users.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` | Loading | First load or retry | [users](screens/users.md) |
|
||||||
| Users | `/users` | Only you | Nobody invited yet | [users](screens/users.md) |
|
| Users | `/users` | Only you | Nobody invited yet | [users](screens/users.md) |
|
||||||
@@ -90,6 +162,38 @@ Every state is drawn at desktop and mobile on the screen boards, with final copy
|
|||||||
| Users | `/users` | Invite: already a user | 409 | [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: 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` | 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` | 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` | 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` | Default, no display name | First visit | [profile](screens/profile.md) |
|
||||||
@@ -131,6 +235,8 @@ Response bodies are plain text and are never shown. `useApi` throws an `ApiError
|
|||||||
| 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 | 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 | 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 | 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 | Send reset link (profile) | "Couldn't send the link. Check your connection and try again." | Note |
|
||||||
@@ -146,9 +252,32 @@ Added by the Users and Profile screens, none of which exist yet:
|
|||||||
|
|
||||||
- `GET /v1/user/`: the users and their invites, newest first.
|
- `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.
|
- `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.
|
- `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.
|
- `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:
|
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, listing or deleting individual images, removing users, revoking invites and any kind of role. Changing the password while logged in works only through the emailed reset link on the Profile page.
|
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.
|
||||||
+202
@@ -0,0 +1,202 @@
|
|||||||
|
# Docker
|
||||||
|
|
||||||
|
RenewCMS runs as a container. The image is published to the registry at `git.floriansylvain.fr/fsylvain/renewcms`, so site operators pull it and never build from source; it can also be built from this repository. The image holds only the single binary (SPA embedded) on Alpine, runs as a non-root user (uid 10001) and keeps all state on one volume mounted at `/data`. It reuses the configuration contract described in [configuration.md](configuration.md); there are no Docker-specific variables.
|
||||||
|
|
||||||
|
Requirements: Docker with Compose v2. [task](https://taskfile.dev) is optional for operators and needed to build from source or to publish. Building needs no local Go or Bun. The image build bundles the SPA with `vite build` only; the `vue-tsc` type-check is not run inside the image (it does not work under the Bun-only build image), so keep running `bun run type-check` locally.
|
||||||
|
|
||||||
|
## Quick start
|
||||||
|
|
||||||
|
1. Copy the example env file and edit it:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
cp docker.env.example docker.env
|
||||||
|
```
|
||||||
|
|
||||||
|
Set `PUBLIC_URL`, the `SMTP_*` values and a generated secret (`openssl rand -hex 32`) for `JWT_SECRET`. `docker.env` is git-ignored and excluded from the build context, so it never ends up in an image. Never commit it.
|
||||||
|
|
||||||
|
2. Pull and start the published image:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
docker compose pull
|
||||||
|
docker compose up -d
|
||||||
|
```
|
||||||
|
|
||||||
|
`docker-compose.yml` uses `image: ${RENEWCMS_IMAGE:-git.floriansylvain.fr/fsylvain/renewcms:beta}`. The default tag is `beta` because `latest` does not exist until the first stable release (the default changes to `latest` then). Set `RENEWCMS_IMAGE` in your shell or in a `.env` file next to the compose file to pin another tag, for example `RENEWCMS_IMAGE=git.floriansylvain.fr/fsylvain/renewcms:v2.9.0-beta`.
|
||||||
|
|
||||||
|
To build from the local sources instead, see [Building from source](#building-from-source).
|
||||||
|
|
||||||
|
3. Check it: `curl http://localhost:8080/healthz` returns `ok`, and `http://localhost:8080/` serves the SPA.
|
||||||
|
|
||||||
|
Other tasks: `task docker:pull`, `task docker:upgrade` (pull, then `docker compose up -d`), `task docker:up` (local build, see below), `task docker:build` (image only, tagged with the `git describe` version and `latest`), `task docker:run` (one-off foreground run on the volume `renewcms-data`, without Compose), `task docker:logs` and `task docker:down`.
|
||||||
|
|
||||||
|
If a required variable is missing the container exits non-zero and the log names it, for example `Environment variable JWT_SECRET is not set`.
|
||||||
|
|
||||||
|
### Local trial over plain HTTP
|
||||||
|
|
||||||
|
`ENVIRONMENT` defaults to `production`, which makes the auth cookie `Secure`: browsers do not store it over `http://`, so login appears to fail. For a local trial on `http://localhost:8080`, set `ENVIRONMENT=development` and `PUBLIC_URL=http://localhost:8080` in `docker.env`. Use `production` only behind HTTPS.
|
||||||
|
|
||||||
|
## Building from source
|
||||||
|
|
||||||
|
`docker-compose.build.yml` adds the `build:` section and tags the result `renewcms:${VERSION:-dev}`. Use it as an override:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
docker compose -f docker-compose.yml -f docker-compose.build.yml up -d --build
|
||||||
|
```
|
||||||
|
|
||||||
|
`task docker:up` does the same and passes the `git describe` version as `VERSION`. To check what Compose resolves, run `docker compose config`: without the override it shows the registry image and no `build` section, with it the `build` section is present.
|
||||||
|
|
||||||
|
## Image tags
|
||||||
|
|
||||||
|
| Release | Tags pushed |
|
||||||
|
|---|---|
|
||||||
|
| `vX.Y.Z` (stable) | `vX.Y.Z`, `X.Y.Z`, `X.Y`, `latest` |
|
||||||
|
| `vX.Y.Z-<pre>` (for example `v2.9.0-beta`, `v2.9.0-rc.1`) | `vX.Y.Z-<pre>`, `X.Y.Z-<pre>`, and the moving tag `<pre-name>` (`beta`, `rc`) |
|
||||||
|
|
||||||
|
A pre-release never moves `latest`. Images are published for `linux/amd64` and `linux/arm64`. `renewcms --version` in the image prints the exact release tag. Images are not signed; the Ed25519 key signs the release binaries only.
|
||||||
|
|
||||||
|
## Environment
|
||||||
|
|
||||||
|
Compose reads `docker.env` through `env_file` and sets `DB_FILE=/data/renewcms.db` and `UPLOAD_DIR=/data/uploads` itself. Everything in [configuration.md](configuration.md) can go in `docker.env`. To publish another host port, change the left side of `ports` in `docker-compose.yml`; keep `PORT` at 8080 unless you also change the healthcheck.
|
||||||
|
|
||||||
|
The container receives SIGTERM on stop, and RenewCMS shuts down gracefully within 10 seconds. Compose uses `stop_grace_period: 15s`. The healthcheck calls `/healthz` inside the container.
|
||||||
|
|
||||||
|
## Data volume
|
||||||
|
|
||||||
|
State lives on the named volume `renewcms-data` (Compose prefixes it with the project name, usually `renewcms_renewcms-data`; check with `docker volume ls`). It holds the SQLite database, uploads, and update records.
|
||||||
|
|
||||||
|
- `docker compose down` removes the container and keeps the volume. The data survives and `docker compose up -d` brings it back.
|
||||||
|
- **`docker compose down -v` deletes the volume and all data.** The next start is an empty instance.
|
||||||
|
|
||||||
|
### Backup
|
||||||
|
|
||||||
|
Replace `VOLUME` with the real volume name. The image has no `sqlite3`, so stop the service for a consistent copy:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
docker compose stop
|
||||||
|
docker run --rm -v VOLUME:/data -v "$PWD":/backup alpine tar czf /backup/renewcms-backup.tar.gz -C /data .
|
||||||
|
docker compose start
|
||||||
|
```
|
||||||
|
|
||||||
|
### Restore into a fresh volume
|
||||||
|
|
||||||
|
```sh
|
||||||
|
docker compose down -v
|
||||||
|
docker volume create VOLUME
|
||||||
|
docker run --rm -v VOLUME:/data -v "$PWD":/backup alpine sh -c "tar xzf /backup/renewcms-backup.tar.gz -C /data && chown -R 10001:10001 /data"
|
||||||
|
docker compose up -d
|
||||||
|
```
|
||||||
|
|
||||||
|
## Reverse proxy and TLS
|
||||||
|
|
||||||
|
With `ENVIRONMENT=production` the site must be served over HTTPS, so put a reverse proxy in front and set `PUBLIC_URL` to the public `https://` address. Bind the published port to the host only when the proxy runs on the same host, by changing `ports` to `"127.0.0.1:8080:8080"`.
|
||||||
|
|
||||||
|
Caddy on the host:
|
||||||
|
|
||||||
|
```caddyfile
|
||||||
|
cms.example.com {
|
||||||
|
reverse_proxy 127.0.0.1:8080 {
|
||||||
|
header_up X-Real-IP {remote_host}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
nginx on the host:
|
||||||
|
|
||||||
|
```nginx
|
||||||
|
server {
|
||||||
|
listen 443 ssl;
|
||||||
|
server_name cms.example.com;
|
||||||
|
client_max_body_size 20m;
|
||||||
|
|
||||||
|
location / {
|
||||||
|
proxy_pass http://127.0.0.1:8080;
|
||||||
|
proxy_set_header Host $host;
|
||||||
|
proxy_set_header X-Real-IP $remote_addr;
|
||||||
|
proxy_set_header X-Forwarded-Proto $scheme;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Set `TRUSTED_PROXIES` to the proxy address as the container sees it, otherwise the login rate limiter ignores `X-Real-IP` and counts every client as the proxy. With a proxy on the host and the default bridge network, that is the bridge gateway (check with `docker network inspect`, often `172.17.0.1` or the Compose network gateway). With a proxy container on the same Compose network, it is that container's IP. The value is a semicolon-separated list of exact IPs, no CIDR. See [deployment.md](deployment.md#4-put-https-in-front).
|
||||||
|
|
||||||
|
## SMTP
|
||||||
|
|
||||||
|
RenewCMS sends registration and password-reset mail through the `SMTP_*` variables. Use your provider's host and port in `docker.env`.
|
||||||
|
|
||||||
|
To use a mail server running on the Docker host, set `SMTP_HOST=host.docker.internal`. Docker Desktop resolves that name. On Linux add the mapping to the service in `docker-compose.yml`:
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
extra_hosts:
|
||||||
|
- "host.docker.internal:host-gateway"
|
||||||
|
```
|
||||||
|
|
||||||
|
The host MTA must listen on an address reachable from the container, not only on `127.0.0.1`.
|
||||||
|
|
||||||
|
If SMTP is unreachable, the server still starts. Only the actions that send mail (registration, password reset, invitations) fail, and the error appears in `docker compose logs renewcms`.
|
||||||
|
|
||||||
|
## Upgrading
|
||||||
|
|
||||||
|
1. Back up the volume (see above).
|
||||||
|
2. Pull the new image and recreate the container on the same volume:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
docker compose pull
|
||||||
|
docker compose up -d
|
||||||
|
```
|
||||||
|
|
||||||
|
`task docker:upgrade` runs both. The schema is migrated at startup, and there is no down-migration.
|
||||||
|
3. Check `docker compose logs renewcms` for the new version line, or `docker run --rm git.floriansylvain.fr/fsylvain/renewcms:beta --version`. The owner's Settings page also shows the running version.
|
||||||
|
|
||||||
|
To roll back, set `RENEWCMS_IMAGE` to the previous tag, run `docker compose up -d`, and restore the backup if the schema changed.
|
||||||
|
|
||||||
|
If you built from source, upgrade with `git pull` and `task docker:up` instead.
|
||||||
|
|
||||||
|
## Maintainer: publishing
|
||||||
|
|
||||||
|
Publishing is a manual, maintainer-run task, like `task release`. There is no CI pipeline.
|
||||||
|
|
||||||
|
1. Tag the release and keep the work tree clean:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
git tag v2.9.0-beta
|
||||||
|
```
|
||||||
|
|
||||||
|
2. Log in once to the registry. The task never reads or stores credentials:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
docker login git.floriansylvain.fr
|
||||||
|
```
|
||||||
|
|
||||||
|
3. Make sure a buildx builder can build both platforms. Check with `docker buildx ls`. With the containerd image store (the Docker Desktop default) the default builder already works. Otherwise create one, and on a Linux host install the QEMU emulators:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
docker buildx create --use
|
||||||
|
docker run --privileged --rm tonistiigi/binfmt --install arm64
|
||||||
|
```
|
||||||
|
|
||||||
|
4. Publish:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
task docker:publish
|
||||||
|
```
|
||||||
|
|
||||||
|
`REGISTRY_IMAGE` defaults to `git.floriansylvain.fr/fsylvain/renewcms` and `VERSION` to `git describe --tags`. The task refuses to run, before building anything, when `REGISTRY_IMAGE` is empty, when `VERSION` is not an exact tag `vX.Y.Z` or `vX.Y.Z-<pre>` on HEAD, when the work tree is dirty, or when the builder cannot build `linux/amd64` and `linux/arm64`. It prints the tags it pushes.
|
||||||
|
|
||||||
|
### Dry run
|
||||||
|
|
||||||
|
```sh
|
||||||
|
task docker:publish -- --dry-run
|
||||||
|
task docker:publish VERSION=v2.9.0-rc.1 -- --dry-run
|
||||||
|
```
|
||||||
|
|
||||||
|
The dry run builds for the host platform only, loads the image into the local Docker, pushes nothing and needs no login. It prints the tags a real run would push. A `VERSION` override is accepted only with `--dry-run`, and a dirty tree is allowed there. Remove the loaded images afterwards with `docker rmi`.
|
||||||
|
|
||||||
|
### After pushing
|
||||||
|
|
||||||
|
- `docker buildx imagetools inspect git.floriansylvain.fr/fsylvain/renewcms:<tag>` lists `linux/amd64` and `linux/arm64`.
|
||||||
|
- The moving tag (`beta`) points at the new digest, and `latest` did not move for a pre-release.
|
||||||
|
- On a clean machine, `docker compose pull && docker compose up -d` starts the new image and Settings shows the new version.
|
||||||
|
|
||||||
|
## Limitations
|
||||||
|
|
||||||
|
Browser updates are unsupported in Docker (they need Linux with systemd, and a binary replaced inside a container is lost when it is recreated). The image and `docker-compose.yml` set `RENEWCMS_CONTAINER=true`, so the owner's Settings page shows when a newer version exists and tells them to pull a new image: `docker compose pull && docker compose up -d`. There is no Update or Restart button. Upgrade by pulling the image as above, or by rebuilding it if you build from source.
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
# 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 |
|
||||||
|
| `v2.7.0-beta` | v2.7.0-beta - Markdown and block article bodies |
|
||||||
|
| `v2.8.0-beta` | v2.8.0-beta - API keys and API reference |
|
||||||
|
| `v2.8.1-beta` | v2.8.1-beta - Docker deployment |
|
||||||
@@ -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.
|
||||||
@@ -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.
|
||||||
@@ -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.
|
||||||
@@ -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.
|
||||||
@@ -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.
|
||||||
@@ -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.
|
||||||
@@ -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.
|
||||||
@@ -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.
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
This release lets your website read article bodies as markdown, HTML or structured blocks, and fixes text alignment in the editor.
|
||||||
|
|
||||||
|
## New
|
||||||
|
|
||||||
|
**Article body formats**
|
||||||
|
|
||||||
|
- Read an article body as markdown, HTML or a typed block array with the `format` query parameter, so a headless frontend can render it with markdown-it, comark or its own components.
|
||||||
|
- Keep text alignment in every format: markdown wraps centered, right-aligned and justified blocks in a `div` with an inline style, and the block array carries an `align` field.
|
||||||
|
- Keep plain text plain: text that merely looks like markdown, such as `# not a heading` or `- not a list`, is escaped in the markdown output.
|
||||||
|
- See the Integration page snippets and [the article API reference](../api/articles.md) for the full contract.
|
||||||
|
|
||||||
|
## Improvements and fixes
|
||||||
|
|
||||||
|
- Fix the text alignment buttons in the article editor, which were disabled and showed a blocked cursor. Paragraphs and headings can be aligned left, center, right or justified again, and unaligned text stays free of inline styles.
|
||||||
|
- The web interface requests HTML explicitly when it loads, saves, publishes, unpublishes or creates an article, so the editor and the image counts behave exactly as before.
|
||||||
|
|
||||||
|
## API
|
||||||
|
|
||||||
|
- Changed: `GET /v1/article/`, `GET /v1/article/{id}`, `POST /v1/article/`, `PATCH /v1/article/{id}`, `PATCH /v1/article/{id}/publish` and `PATCH /v1/article/{id}/unpublish` now return `body` as markdown by default. Pass `?format=html` to keep the previous HTML body.
|
||||||
|
- Every article object now includes `body_format` (`markdown`, `html` or `json`), which names the format of `body`.
|
||||||
|
- `?format=json` on the same routes returns `body` as a JSON array of typed blocks instead of a string.
|
||||||
|
- An unsupported `format` answers `400` before anything is read or written.
|
||||||
|
- Storage and the request bodies of `POST` and `PATCH` stay HTML.
|
||||||
|
|
||||||
|
## Under the hood
|
||||||
|
|
||||||
|
- Add the article body renderer port in the domain, with a markdown and JSON block adapter, and tests for every supported element.
|
||||||
|
- Update `golang.org/x/crypto` to v0.57.0 and add `golang.org/x/net` as a direct dependency for HTML parsing.
|
||||||
|
- Add `@tiptap/extension-text-align` to the web interface.
|
||||||
|
|
||||||
|
## Upgrading
|
||||||
|
|
||||||
|
- Replace the binary. No database migration or new environment variable is required.
|
||||||
|
- Clients that read an article `body` as HTML must add `?format=html` to their article requests, because the default is now markdown.
|
||||||
|
- A markdown renderer needs raw HTML enabled for text alignment to show, for example `html: true` in markdown-it.
|
||||||
@@ -0,0 +1,41 @@
|
|||||||
|
This release adds API keys, so a script or service can use the whole API without the web interface, and turns the Integration page into a complete API reference.
|
||||||
|
|
||||||
|
## New
|
||||||
|
|
||||||
|
**API keys**
|
||||||
|
|
||||||
|
- Create named API keys from the new API keys screen under Integration, with an optional expiry date. The full key is shown once, when you create it, and only its prefix is visible afterwards.
|
||||||
|
- Send a key as `Authorization: Bearer rcms_...` to manage articles, media, users and invites, and to read settings. A key acts with exactly the rights of the user who created it, so an admin's key cannot do owner-only things.
|
||||||
|
- Revoke a key at any time. Active, expired and revoked keys all stay listed with their status, creation date and last use.
|
||||||
|
- The owner sees every key and who created it. Admins see only their own.
|
||||||
|
- Each key is limited to 120 requests per minute.
|
||||||
|
- Resetting a user's password revokes all of that user's keys.
|
||||||
|
|
||||||
|
**API reference**
|
||||||
|
|
||||||
|
- The Integration page now documents every route a developer can call, grouped by area: articles, media, users and invites, and settings. Each endpoint lists who can call it, its request body, ready-to-copy fetch and curl examples, a sample response and its error statuses.
|
||||||
|
- A new Authentication section explains public access and API keys, and a section index lets you jump between groups.
|
||||||
|
- Routes that need a signed-in browser session are listed separately, and the page shows the real error messages the API returns.
|
||||||
|
- The Integration page and the API keys screen are available in English and French.
|
||||||
|
|
||||||
|
## API
|
||||||
|
|
||||||
|
- `POST /v1/api-key` creates a key. It answers `201` with the key, shown once.
|
||||||
|
- `GET /v1/api-key` lists keys, newest first, each with a `status` of `active`, `expired` or `revoked`. For the owner, each entry also carries `created_by_name`.
|
||||||
|
- `DELETE /v1/api-key/{id}` revokes a key and answers `204`, also when the key is already revoked.
|
||||||
|
- An invalid, unknown, expired or revoked key answers `401` on every route, including public ones, and is never treated as anonymous.
|
||||||
|
- A key calling a session-only route answers `403` with "This action needs a real session." These routes are `/v1/api-key`, `POST /v1/auth/verify`, `DELETE /v1/auth/register` and everything under `/v1/system`.
|
||||||
|
- `GET /v1/auth/me` accepts an API key, so a client can check who a key belongs to.
|
||||||
|
- A key beyond 120 requests per minute gets `429` with a `Retry-After` header.
|
||||||
|
- Cross-origin requests now allow the `PATCH` method.
|
||||||
|
|
||||||
|
## Under the hood
|
||||||
|
|
||||||
|
- Add the API key domain, use cases, SQLite repository and an authentication middleware that runs after each token verifier. Keys are generated by a new domain interface and stored as SHA-256 hashes, never in clear.
|
||||||
|
- Add a typed API catalogue that drives the Integration page, with a test that every route has a description.
|
||||||
|
- Add the API keys and Integration specifications and QA procedures to `features/`, and the API key reference to `docs/api/`.
|
||||||
|
|
||||||
|
## Upgrading
|
||||||
|
|
||||||
|
- Replace the binary. The new API keys table is created automatically at startup. No new environment variable is required.
|
||||||
|
- Browsers calling the API from another origin can now use `PATCH`. Check your CORS configuration only if you restricted methods in a reverse proxy.
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
This release adds an official Docker deployment, so RenewCMS can run in a container instead of as a binary under systemd, and teaches Settings to guide container installs through updates.
|
||||||
|
|
||||||
|
## New
|
||||||
|
|
||||||
|
**Docker deployment**
|
||||||
|
|
||||||
|
- A container image holds the single RenewCMS binary on Alpine, runs as a non-root user and keeps the database and uploads on one volume. A Compose file starts it with an env file and a health check.
|
||||||
|
- Images are published for amd64 and arm64 to the project registry at `git.floriansylvain.fr/fsylvain/renewcms`. Prereleases carry the version tag and a moving `beta` tag, and `latest` is only used for stable releases.
|
||||||
|
- Upgrading is `docker compose pull && docker compose up -d`. Your data stays on the volume.
|
||||||
|
- A new Docker guide covers the quick start, backups of the data volume, the reverse proxy and TLS, reaching an SMTP server from the container, and building the image from source.
|
||||||
|
|
||||||
|
**Update guidance in containers**
|
||||||
|
|
||||||
|
- In a container, Settings no longer shows the browser update flow, which cannot work there. It shows the new version, the command to run on the server with a Copy button, and a link to the Docker guide.
|
||||||
|
- Download and restart are not offered in a container, and the API refuses them.
|
||||||
|
|
||||||
|
## API
|
||||||
|
|
||||||
|
- `GET /v1/system/update` has a new `container` boolean. It is `true` when the server runs in a container, and `can_apply` is then always `false`.
|
||||||
|
- `POST /v1/system/update/download` and `POST /v1/system/update/restart` answer `409` in a container, as they already do when browser updates are not set up.
|
||||||
|
|
||||||
|
## Under the hood
|
||||||
|
|
||||||
|
- Add a multi-stage Dockerfile, a Compose file with a separate build override, and tasks to build, run, pull, upgrade and publish the image. Publishing is a maintainer task that refuses to run unless the version is an exact tag on a clean tree.
|
||||||
|
- Add the container update guidance and the image publishing specifications and QA procedures to `features/`.
|
||||||
|
|
||||||
|
## Upgrading
|
||||||
|
|
||||||
|
- Replace the binary. No schema change and no required environment variable.
|
||||||
|
- There is one new optional variable, `RENEWCMS_CONTAINER`, which defaults to `false`. The Docker image and the Compose file set it to `true`. Leave it unset on a binary install.
|
||||||
|
- Docker users start from the Docker guide. To move an existing binary install to Docker, copy the database and uploads into the volume and keep the same environment variables.
|
||||||
|
|
||||||
|
## Known limitations
|
||||||
|
|
||||||
|
- Browser updates are not available in a container. Update by pulling a new image.
|
||||||
|
- The new container wording in Settings has no design frame yet.
|
||||||
@@ -26,7 +26,8 @@ Feature: An invited person accepts their invitation and gets a verified account
|
|||||||
And error responses are plain text from http.Error, success responses are JSON
|
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,
|
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
|
the hashed password, is_verified true, an empty verification code, and an empty display name
|
||||||
And the created user has the same access as any other verified user: no roles, no ownership
|
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
|
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
|
claims user_id and token_version, and Secure in production
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,457 @@
|
|||||||
|
Feature: Developers authenticate against /v1 with named API keys instead of the jwt cookie
|
||||||
|
|
||||||
|
As a developer integrating with RenewCMS
|
||||||
|
I want to create named API keys and send them as a Bearer token
|
||||||
|
So that I can manage articles, media and users without the UI, with exactly the rights of the
|
||||||
|
user who created the key and never more
|
||||||
|
|
||||||
|
Background:
|
||||||
|
Given internal/domain/apikey defines the entity APIKey with ID uint32, UserID uint32, Name,
|
||||||
|
Prefix, HashedKey, ExpiresAt *time.Time, RevokedAt *time.Time, LastUsedAt *time.Time and
|
||||||
|
CreatedAt, with snake_case json tags
|
||||||
|
And internal/domain/apikey defines the sentinels apikey.ErrAPIKeyNotFound,
|
||||||
|
apikey.ErrAPIKeyInvalid and apikey.ErrExpiryNotInFuture
|
||||||
|
And apikey.ErrAPIKeyInvalid covers an unknown, malformed, expired or revoked key and a key
|
||||||
|
whose user is deleted or unverified
|
||||||
|
And internal/domain/apikey defines the interface Repository with Create, Get(id),
|
||||||
|
GetByHashedKey(hashedKey), ListByUser(userId), ListAll(), Revoke(id, at),
|
||||||
|
RevokeAllByUser(userId, at) and TouchLastUsed(id, at)
|
||||||
|
And RevokeAllByUser sets RevokedAt to at on every key of that user that is not yet revoked and
|
||||||
|
leaves the RevokedAt of already revoked keys and every other user's keys untouched
|
||||||
|
And internal/domain/apikey defines the interface KeyGenerator with Generate() returning the
|
||||||
|
raw key, its display prefix and its SHA-256 hash, and Hash(rawKey) returning the SHA-256 hash
|
||||||
|
And internal/infrastructure/hashing implements KeyGenerator, asserted with
|
||||||
|
var _ apikey.KeyGenerator = &SHA256KeyGenerator{}
|
||||||
|
And a generated raw key is "rcms_" followed by the base64url encoding, without padding, of 32
|
||||||
|
random bytes, so it matches ^rcms_[A-Za-z0-9_-]{43}$
|
||||||
|
And the display prefix is the first 12 characters of the raw key
|
||||||
|
And only the SHA-256 hash and the prefix are persisted, never the raw key
|
||||||
|
And the use cases CreateAPIKey, ListAPIKeys, RevokeAPIKey and AuthenticateAPIKey depend only
|
||||||
|
on apikey.Repository, apikey.KeyGenerator, user.Repository and an injected clock
|
||||||
|
And ResetPasswordUseCase additionally receives apikey.Repository and an injected clock, and
|
||||||
|
after a successful password reset calls RevokeAllByUser(userId, now); it never reaches
|
||||||
|
persistence directly
|
||||||
|
And persistence has a GORM model, a mapper and a repository for the entity, the model is
|
||||||
|
added to the AutoMigrate list in api/dependecyInjection.go, and wiring happens only in
|
||||||
|
api/dependecyInjection.go
|
||||||
|
And a new middleware resolves "Authorization: Bearer rcms_<...>" to a user and places a jwt in
|
||||||
|
the same jwtauth request context the cookie path fills, with the claims user_id and
|
||||||
|
token_version taken from the user's current record
|
||||||
|
And that middleware runs after jwtauth.Verifier and ahead of jwtauth.Authenticator on the
|
||||||
|
/article routes (public and protected), /user, /media, /settings and GET /auth/me
|
||||||
|
And jwtauth.Authenticator, RequireCurrentToken, RequireVerifiedUser, RequireOwner and every
|
||||||
|
handler stay unchanged
|
||||||
|
And a new middleware RequireSession, mounted ahead of jwtauth.Verifier, answers 403 with
|
||||||
|
apperr.SessionRequiredErrorMessage whenever the Authorization header is a Bearer token that
|
||||||
|
starts with "rcms_", whether that key is valid, expired, revoked, unknown or garbage
|
||||||
|
And RequireSession is mounted on the key management routes POST /v1/api-key, GET /v1/api-key
|
||||||
|
and DELETE /v1/api-key/{id}, on the session-only auth routes POST /v1/auth/verify and
|
||||||
|
DELETE /v1/auth/register, and on every /v1/system route (all under /v1/system/update)
|
||||||
|
And a request on those routes without a "Bearer rcms_" header passes through RequireSession
|
||||||
|
unchanged, so cookie-only and jwt-Bearer behaviour there does not change
|
||||||
|
And the public auth routes login, register, registration, logout, password-reset,
|
||||||
|
password-reset/confirm, invite and invite/accept do not use the key middleware or
|
||||||
|
RequireSession and behave exactly as they do without a key header
|
||||||
|
And the routes are mounted under /v1 inside the jwtauth.Verifier, jwtauth.Authenticator,
|
||||||
|
RequireCurrentToken and RequireVerifiedUser group:
|
||||||
|
POST /v1/api-key, GET /v1/api-key and DELETE /v1/api-key/{id}
|
||||||
|
And a Bearer key on a key-accepting route that cannot authenticate gets 401 with
|
||||||
|
apperr.UnauthorizedErrorMessage, and a request without an rcms_ key keeps the existing
|
||||||
|
jwtauth.Authenticator response, status 401, unchanged by this feature
|
||||||
|
And new apperr strings: APIKeyNotFoundErrorMessage = "API key not found",
|
||||||
|
APIKeyExpiryErrorMessage = "The expiry must be a date in the future." and
|
||||||
|
SessionRequiredErrorMessage = "This action needs a real session."
|
||||||
|
And the per-key rate limit is 120 requests per minute, as constants in api/router.go
|
||||||
|
And enableCorsIfConfigured allows the methods GET, POST, PUT, PATCH, DELETE and OPTIONS
|
||||||
|
And users: owner id 1 "marta" (verified), admin id 2 "dev" (verified), admin id 3 "pat"
|
||||||
|
(verified), unverified id 4 "quinn"
|
||||||
|
|
||||||
|
Scenario: Creating a key returns the full key exactly once
|
||||||
|
Given a valid jwt cookie for admin 2
|
||||||
|
When the client sends POST /v1/api-key with body {"name": "ci-deploy"}
|
||||||
|
Then the response status is 201
|
||||||
|
And the header Cache-Control is "no-store"
|
||||||
|
And the body has exactly the keys id, name, prefix, key, created_at, expires_at
|
||||||
|
And name is "ci-deploy", expires_at is null, and key matches ^rcms_[A-Za-z0-9_-]{43}$
|
||||||
|
And prefix equals the first 12 characters of key
|
||||||
|
And the stored record has user_id 2 and HashedKey equal to the SHA-256 of key
|
||||||
|
And neither the raw key nor the stored hash appears in any later response
|
||||||
|
|
||||||
|
Scenario: The key can't be retrieved afterwards
|
||||||
|
Given admin 2 created the key "ci-deploy" and holds its raw key
|
||||||
|
When the same jwt cookie sends GET /v1/api-key
|
||||||
|
Then the response status is 200
|
||||||
|
And the body is a JSON array with one entry whose keys are exactly id, user_id, name, prefix,
|
||||||
|
status, created_at, last_used_at, expires_at, revoked_at
|
||||||
|
And the entry has no "key" and no "hashed_key" field
|
||||||
|
And the raw key and its hash appear nowhere in the body
|
||||||
|
And the entry's prefix is the first 12 characters of the raw key
|
||||||
|
|
||||||
|
Scenario: Creating a key with an expiry
|
||||||
|
Given a valid jwt cookie for admin 2
|
||||||
|
When the client sends POST /v1/api-key with body
|
||||||
|
{"name": "temp", "expires_at": "<now + 30 days, RFC3339>"}
|
||||||
|
Then the response status is 201
|
||||||
|
And expires_at in the body equals the requested instant
|
||||||
|
|
||||||
|
Scenario Outline: Creating a key with an invalid body is refused and creates nothing
|
||||||
|
Given a valid jwt cookie for admin 2
|
||||||
|
When the client sends POST /v1/api-key with <body>
|
||||||
|
Then the response status is 400
|
||||||
|
And the response body is <message>
|
||||||
|
And no key exists in the repository
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| body | message |
|
||||||
|
| body not-json | apperr.BodyErrorMessage |
|
||||||
|
| body {} | text containing 'Name' and 'required' |
|
||||||
|
| body {"name": ""} | text containing 'Name' and 'required' |
|
||||||
|
| body {"name": "<61 characters>"} | text containing 'Name' and 'max' |
|
||||||
|
| body {"name": "x", "expires_at": "yesterday"} | apperr.BodyErrorMessage |
|
||||||
|
| body {"name": "x", "expires_at": "<now - 1h>"} | apperr.APIKeyExpiryErrorMessage |
|
||||||
|
|
||||||
|
Scenario: A request body can't choose the owner or the role of a new key
|
||||||
|
Given a valid jwt cookie for admin 2
|
||||||
|
When the client sends POST /v1/api-key with body {"name": "sneaky", "user_id": 1, "role": "owner"}
|
||||||
|
Then the response status is 201
|
||||||
|
And the stored key belongs to user 2
|
||||||
|
And using that key on POST /v1/user/invite returns 403 with apperr.OwnerRequiredErrorMessage
|
||||||
|
|
||||||
|
Scenario Outline: Key management needs a verified real session
|
||||||
|
Given <caller>
|
||||||
|
When the client sends POST /v1/api-key with body {"name": "x"}
|
||||||
|
Then the response status is <status>
|
||||||
|
And the response body is <message>
|
||||||
|
And no key exists in the repository
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| caller | status | message |
|
||||||
|
| no credentials | 401 | the existing Authenticator response |
|
||||||
|
| a jwt cookie for user 4 | 403 | apperr.VerificationRequiredErrorMessage |
|
||||||
|
| a stale token_version cookie | 401 | the existing Authenticator response |
|
||||||
|
|
||||||
|
Scenario Outline: A valid key acts as its creator on every key-accepting route
|
||||||
|
Given an active key created by admin 2
|
||||||
|
When the client sends <method> <path> with "Authorization: Bearer <that key>" and no cookie <body>
|
||||||
|
Then the response status is <status>
|
||||||
|
And the effect is attributed to user 2
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| method | path | body | status |
|
||||||
|
| GET | /v1/settings | | 200 |
|
||||||
|
| GET | /v1/user | | 200 |
|
||||||
|
| PATCH | /v1/user/me | and body {"display_name": "Dev"} | 200 |
|
||||||
|
| POST | /v1/article | and body {"title": "A valid title", "body": "x"} | 201 |
|
||||||
|
| PATCH | /v1/article/1/publish | | 200 |
|
||||||
|
| DELETE | /v1/article/1 | | 204 |
|
||||||
|
| GET | /v1/media | | 200 |
|
||||||
|
| DELETE | /v1/media/1 | | 204 |
|
||||||
|
|
||||||
|
Scenario: A key can read its creator through GET /v1/auth/me
|
||||||
|
Given an active key created by admin 2
|
||||||
|
When the client sends GET /v1/auth/me with that key and no cookie
|
||||||
|
Then the response status is 200
|
||||||
|
And the body is the same JSON the jwt cookie of admin 2 gets on GET /v1/auth/me
|
||||||
|
And the body describes user 2 "dev"
|
||||||
|
|
||||||
|
Scenario: A key that can't authenticate gets 401 on GET /v1/auth/me
|
||||||
|
When the client sends GET /v1/auth/me with "Authorization: Bearer rcms_unknown"
|
||||||
|
Then the response status is 401
|
||||||
|
And the response body is apperr.UnauthorizedErrorMessage
|
||||||
|
|
||||||
|
Scenario: A key sees offline articles on the public article routes, an anonymous caller does not
|
||||||
|
Given an offline article 5 and an online article 6
|
||||||
|
And an active key created by admin 2
|
||||||
|
When the client sends GET /v1/article with that key
|
||||||
|
Then the body lists articles 5 and 6
|
||||||
|
When the client sends GET /v1/article with no credentials
|
||||||
|
Then the body lists only article 6
|
||||||
|
When the client sends GET /v1/article/5 with that key
|
||||||
|
Then the response status is 200
|
||||||
|
When the client sends GET /v1/article/5 with no credentials
|
||||||
|
Then the response status is 404
|
||||||
|
|
||||||
|
Scenario: An invalid key on a public article route is refused, not treated as anonymous
|
||||||
|
When the client sends GET /v1/article with "Authorization: Bearer rcms_unknown"
|
||||||
|
Then the response status is 401
|
||||||
|
And the response body is apperr.UnauthorizedErrorMessage
|
||||||
|
|
||||||
|
Scenario: An owner's key can do owner-only things
|
||||||
|
Given an active key created by owner 1
|
||||||
|
When the client sends POST /v1/user/invite with that key and body {"email": "new@example.com"}
|
||||||
|
Then the response status is 201
|
||||||
|
And the invite's invited_by is 1
|
||||||
|
|
||||||
|
Scenario: An admin's key can not do owner-only things
|
||||||
|
Given an active key created by admin 2
|
||||||
|
When the client sends POST /v1/user/invite with that key and body {"email": "new@example.com"}
|
||||||
|
Then the response status is 403
|
||||||
|
And the response body is apperr.OwnerRequiredErrorMessage
|
||||||
|
And no invite exists
|
||||||
|
|
||||||
|
Scenario Outline: A key that can't authenticate gets the same 401 as a bad jwt
|
||||||
|
Given <state>
|
||||||
|
When the client sends GET /v1/settings with "Authorization: Bearer <credential>"
|
||||||
|
Then the response status is 401
|
||||||
|
And the response body is apperr.UnauthorizedErrorMessage
|
||||||
|
And no handler or use case behind the route runs
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| state | credential |
|
||||||
|
| no key stored for it | rcms_unknownunknownunknownunknownunknownunknown1 |
|
||||||
|
| a key whose expires_at is one second ago | that key |
|
||||||
|
| a key that was revoked | that key |
|
||||||
|
| a key of user 1 whose user record was deleted | that key |
|
||||||
|
| a key of an unverified user | that key |
|
||||||
|
| nothing after the prefix | rcms_ |
|
||||||
|
| a key with one character changed | that key, last character changed |
|
||||||
|
| a key's hash passed instead of the key | the stored HashedKey, status 401 only |
|
||||||
|
|
||||||
|
Scenario: Key behaviour does not change the jwt cookie path
|
||||||
|
Given a valid jwt cookie for admin 2
|
||||||
|
When the client sends GET /v1/settings with only that cookie
|
||||||
|
Then the response status is 200
|
||||||
|
When the client sends GET /v1/settings with an Authorization header "Bearer <a valid jwt>" and no cookie
|
||||||
|
Then the response status is 200
|
||||||
|
When the client sends GET /v1/settings with a stale token_version cookie
|
||||||
|
Then the response status is 401
|
||||||
|
|
||||||
|
Scenario: A Bearer key wins over the cookie, and a bad key is not rescued by a good cookie
|
||||||
|
Given an active key created by admin 3 and a valid jwt cookie for owner 1
|
||||||
|
When the client sends POST /v1/user/invite with both the key and the cookie
|
||||||
|
Then the response status is 403
|
||||||
|
When the client sends GET /v1/settings with "Authorization: Bearer rcms_unknown" and the owner cookie
|
||||||
|
Then the response status is 401
|
||||||
|
|
||||||
|
Scenario Outline: Session-only routes refuse any rcms_ credential with 403
|
||||||
|
Given <state>
|
||||||
|
When the client sends <method> <path> with "Authorization: Bearer <credential>" <body>
|
||||||
|
Then the response status is 403
|
||||||
|
And the response body is apperr.SessionRequiredErrorMessage
|
||||||
|
And no use case behind the route runs
|
||||||
|
And no key was created, listed or revoked
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| state | credential | method | path | body |
|
||||||
|
| an active key of owner 1 | that key | POST | /v1/api-key | and body {"name": "child"} |
|
||||||
|
| an active key of owner 1 | that key | GET | /v1/api-key | |
|
||||||
|
| an active key of owner 1 | that key | DELETE | /v1/api-key/1 | |
|
||||||
|
| an active key of owner 1 | that key | POST | /v1/auth/verify | and body {"code": "x"} |
|
||||||
|
| an active key of owner 1 | that key | DELETE | /v1/auth/register | |
|
||||||
|
| an active key of owner 1 | that key | GET | /v1/system/update | |
|
||||||
|
| an active key of owner 1 | that key | POST | /v1/system/update/check | |
|
||||||
|
| an active key of owner 1 | that key | POST | /v1/system/update/download | |
|
||||||
|
| an active key of owner 1 | that key | POST | /v1/system/update/restart | |
|
||||||
|
| a revoked key | that key | GET | /v1/api-key | |
|
||||||
|
| no key stored for it | rcms_unknownunknownunknownunknownunknownunknown1 | POST | /v1/system/update/check | |
|
||||||
|
| nothing | rcms_ | DELETE | /v1/auth/register | |
|
||||||
|
|
||||||
|
Scenario Outline: The session-only routes still work as before with a session
|
||||||
|
Given a valid jwt cookie for owner 1
|
||||||
|
When the client sends <method> <path> with only that cookie <body>
|
||||||
|
Then the response is the same as before this feature
|
||||||
|
And a request with no credentials still gets status 401 from the existing Authenticator
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| method | path | body |
|
||||||
|
| POST | /v1/api-key | and body {"name": "x"} |
|
||||||
|
| GET | /v1/api-key | |
|
||||||
|
| GET | /v1/system/update | |
|
||||||
|
| POST | /v1/system/update/check | |
|
||||||
|
|
||||||
|
Scenario Outline: A key never obtains a session through the public auth routes
|
||||||
|
Given an active key created by owner 1
|
||||||
|
When the client sends <method> <path> with that key and body <body>
|
||||||
|
Then the response is the same as without the key
|
||||||
|
And no jwt cookie is set unless the credentials in the body are valid
|
||||||
|
And the stored user and password are unchanged
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| method | path | body |
|
||||||
|
| POST | /v1/auth/login | {"username": "marta", "password": "wrong-pass-1"} |
|
||||||
|
| POST | /v1/auth/password-reset/confirm | {"email": "marta@example.com", "code": "nope", "password": "newpassword1"} |
|
||||||
|
|
||||||
|
Scenario: A successful password reset revokes every key of that user
|
||||||
|
Given user 2 has active keys "a" and "b", and each works on GET /v1/settings
|
||||||
|
And user 2's stored PasswordResetCode is the hash of "reset-code-1" with an unexpired expiration
|
||||||
|
When the client sends POST /v1/auth/password-reset/confirm with body
|
||||||
|
{"email": "dev@example.com", "code": "reset-code-1", "password": "newpassword1"}
|
||||||
|
Then the response status is 200
|
||||||
|
And GET /v1/settings with key "a" returns 401 with apperr.UnauthorizedErrorMessage
|
||||||
|
And GET /v1/settings with key "b" returns 401 with apperr.UnauthorizedErrorMessage
|
||||||
|
|
||||||
|
Scenario: A password reset leaves other users' keys untouched
|
||||||
|
Given user 2 has an active key "a" and user 3 has an active key "c"
|
||||||
|
And user 2 has a valid password reset code "reset-code-1"
|
||||||
|
When user 2's password reset is confirmed with "reset-code-1"
|
||||||
|
Then GET /v1/settings with key "c" returns 200
|
||||||
|
And key "c" has no revoked_at
|
||||||
|
|
||||||
|
Scenario: Keys revoked by a password reset show as revoked
|
||||||
|
Given user 2 has active keys "a" and "b", and a clock at T
|
||||||
|
And user 2 has a valid password reset code "reset-code-1"
|
||||||
|
When user 2's password reset is confirmed with "reset-code-1"
|
||||||
|
And admin 2 logs in again with the new password and sends GET /v1/api-key with the new cookie
|
||||||
|
Then the entries "a" and "b" have status "revoked" and revoked_at T
|
||||||
|
|
||||||
|
Scenario: A password reset does not move the revoked_at of a key that was already revoked
|
||||||
|
Given user 2 has a key "old" revoked at T0 and an active key "a"
|
||||||
|
And user 2 has a valid password reset code "reset-code-1"
|
||||||
|
When user 2's password reset is confirmed with "reset-code-1" at a later time T
|
||||||
|
Then key "old" still has revoked_at T0
|
||||||
|
And key "a" has revoked_at T
|
||||||
|
|
||||||
|
Scenario Outline: A failed password reset confirmation revokes nothing
|
||||||
|
Given user 2 has an active key "a"
|
||||||
|
And user 2's stored PasswordResetCode is the hash of "reset-code-1" with <expiration>
|
||||||
|
When the client sends POST /v1/auth/password-reset/confirm with <body>
|
||||||
|
Then the response status is not 200
|
||||||
|
And key "a" has no revoked_at
|
||||||
|
And GET /v1/settings with key "a" returns 200
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| expiration | body |
|
||||||
|
| an unexpired expiration | {"email": "dev@example.com", "code": "wrong", "password": "newpassword1"} |
|
||||||
|
| an expiration in the past | {"email": "dev@example.com", "code": "reset-code-1", "password": "newpassword1"} |
|
||||||
|
| an unexpired expiration | {"email": "nobody@example.com", "code": "reset-code-1", "password": "newpassword1"} |
|
||||||
|
|
||||||
|
Scenario: Listing as an admin shows only that admin's keys
|
||||||
|
Given keys "a" and "b" created by admin 2 and key "c" created by admin 3
|
||||||
|
When admin 2 sends GET /v1/api-key with a jwt cookie
|
||||||
|
Then the body lists exactly "a" and "b"
|
||||||
|
|
||||||
|
Scenario: Listing as the owner shows every user's keys, with the creator's id
|
||||||
|
Given the same three keys and key "d" created by owner 1
|
||||||
|
When owner 1 sends GET /v1/api-key with a jwt cookie
|
||||||
|
Then the body lists "a", "b", "c" and "d" newest first
|
||||||
|
And each entry has the user_id of its creator
|
||||||
|
|
||||||
|
Scenario Outline: The list reports each key's state
|
||||||
|
Given a key that is <state>
|
||||||
|
When its creator sends GET /v1/api-key with a jwt cookie
|
||||||
|
Then the entry's status is "<status>", revoked_at is <revoked_at>, and last_used_at is <last_used>
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| state | status | revoked_at | last_used |
|
||||||
|
| active, never used | active | null | null |
|
||||||
|
| active, used 5 minutes ago | active | null | that time |
|
||||||
|
| expired one hour ago | expired | null | unchanged |
|
||||||
|
| revoked | revoked | a time | unchanged |
|
||||||
|
| both expired and revoked | revoked | a time | unchanged |
|
||||||
|
|
||||||
|
Scenario: Revoking a key ends it immediately
|
||||||
|
Given an active key "ci-deploy" created by admin 2
|
||||||
|
And the key works on GET /v1/settings
|
||||||
|
When admin 2 sends DELETE /v1/api-key/<its id> with a jwt cookie
|
||||||
|
Then the response status is 204 and the body is empty
|
||||||
|
And GET /v1/settings with that key returns 401 with apperr.UnauthorizedErrorMessage
|
||||||
|
And GET /v1/api-key lists it with status "revoked"
|
||||||
|
|
||||||
|
Scenario: Revoking twice is idempotent
|
||||||
|
Given a key revoked at time T
|
||||||
|
When its creator sends DELETE /v1/api-key/<its id> again
|
||||||
|
Then the response status is 204
|
||||||
|
And revoked_at is still T
|
||||||
|
|
||||||
|
Scenario: An admin can't revoke someone else's key, and learns nothing about it
|
||||||
|
Given a key created by admin 3
|
||||||
|
When admin 2 sends DELETE /v1/api-key/<its id> with a jwt cookie
|
||||||
|
Then the response status is 404
|
||||||
|
And the response body is apperr.APIKeyNotFoundErrorMessage
|
||||||
|
And the key still works
|
||||||
|
|
||||||
|
Scenario: The owner can revoke any key
|
||||||
|
Given a key created by admin 3
|
||||||
|
When owner 1 sends DELETE /v1/api-key/<its id> with a jwt cookie
|
||||||
|
Then the response status is 204
|
||||||
|
And the key gets 401 on GET /v1/settings
|
||||||
|
|
||||||
|
Scenario Outline: Revoking with a bad id
|
||||||
|
Given a valid jwt cookie for admin 2
|
||||||
|
When the client sends DELETE /v1/api-key/<id>
|
||||||
|
Then the response status is <status>
|
||||||
|
And the response body is <message>
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| id | status | message |
|
||||||
|
| abc | 400 | apperr.IdUint32ErrorMessage |
|
||||||
|
| -1 | 400 | apperr.IdUint32ErrorMessage |
|
||||||
|
| 4294967296 | 400 | apperr.IdUint32ErrorMessage |
|
||||||
|
| 999 | 404 | apperr.APIKeyNotFoundErrorMessage |
|
||||||
|
|
||||||
|
Scenario: Using a key records last_used_at, at most once per minute
|
||||||
|
Given an active key never used, and a fake clock at T
|
||||||
|
When the key authenticates a request at T
|
||||||
|
Then last_used_at is T
|
||||||
|
When it authenticates again at T + 30s
|
||||||
|
Then no write happened and last_used_at is still T
|
||||||
|
When it authenticates again at T + 61s
|
||||||
|
Then last_used_at is T + 61s
|
||||||
|
|
||||||
|
Scenario: A failure to record last_used_at doesn't fail the request
|
||||||
|
Given an active key and a repository whose TouchLastUsed returns an error
|
||||||
|
When the client sends GET /v1/settings with that key
|
||||||
|
Then the response status is 200
|
||||||
|
|
||||||
|
Scenario: A rejected key never records last_used_at
|
||||||
|
Given an expired key and a revoked key
|
||||||
|
When each is used on GET /v1/settings
|
||||||
|
Then each gets 401 and no last_used_at is written
|
||||||
|
|
||||||
|
Scenario: Each key has its own rate limit
|
||||||
|
Given two active keys "a" and "b" and a limit of N requests per minute per key
|
||||||
|
When key "a" sends N+1 requests to GET /v1/settings
|
||||||
|
Then request N+1 gets 429 with apperr.TooManyRequestsErrorMessage and a Retry-After header
|
||||||
|
And key "b" still gets 200
|
||||||
|
And a jwt cookie request still gets 200
|
||||||
|
|
||||||
|
Scenario: The rate limit does not apply to unauthenticated requests
|
||||||
|
When the client sends N+1 requests with "Authorization: Bearer rcms_unknown"
|
||||||
|
Then every response is 401, never 429
|
||||||
|
|
||||||
|
Scenario: The CORS preflight allows PATCH
|
||||||
|
Given settings with CorsAllowedOrigins ["https://app.example.com"]
|
||||||
|
When the client sends OPTIONS /v1/article/1 with Origin "https://app.example.com" and
|
||||||
|
Access-Control-Request-Method "PATCH"
|
||||||
|
Then the response is a successful preflight
|
||||||
|
And Access-Control-Allow-Methods includes PATCH
|
||||||
|
And a preflight for method "TRACE" is not allowed
|
||||||
|
|
||||||
|
Scenario: Use case: creating a key hashes it and stores no plaintext
|
||||||
|
Given a fake KeyGenerator returning raw "rcms_fake", prefix "rcms_fake", hash "hash:rcms_fake"
|
||||||
|
When CreateAPIKey is called with user 2 and name "ci"
|
||||||
|
Then the repository's Create receives HashedKey "hash:rcms_fake", Prefix "rcms_fake", UserID 2
|
||||||
|
And the result carries the raw key, which is not stored
|
||||||
|
|
||||||
|
Scenario: Use case: authenticating returns the user and rejects every invalid case with one sentinel
|
||||||
|
Given a fake KeyGenerator and keys that are unknown, expired, revoked, and owned by a missing or
|
||||||
|
unverified user
|
||||||
|
When AuthenticateAPIKey is called with each raw key
|
||||||
|
Then every call returns apikey.ErrAPIKeyInvalid, asserted with errors.Is
|
||||||
|
And a key expiring exactly at the clock's now is expired
|
||||||
|
And a valid key returns the user from user.Repository
|
||||||
|
|
||||||
|
Scenario: Use case: a failing repository is not reported as an invalid key
|
||||||
|
Given a repository whose GetByHashedKey returns an unexpected error
|
||||||
|
When AuthenticateAPIKey is called
|
||||||
|
Then the error is returned and errors.Is(err, apikey.ErrAPIKeyInvalid) is false
|
||||||
|
And the middleware answers 500 "Internal server error"
|
||||||
|
|
||||||
|
Scenario: Use case: ResetPassword revokes the user's keys through the domain repository
|
||||||
|
Given a fake apikey.Repository holding active keys of users 2 and 3, a fake clock at T, and a
|
||||||
|
user.Repository fake with a valid reset code for user 2
|
||||||
|
When ResetPasswordUseCase.ResetPassword succeeds for user 2
|
||||||
|
Then the fake apikey.Repository received exactly one RevokeAllByUser(2, T)
|
||||||
|
And user 3's keys are untouched
|
||||||
|
|
||||||
|
Scenario: Use case: ResetPassword does not call RevokeAllByUser when the reset fails
|
||||||
|
Given a fake apikey.Repository and a user.Repository fake with a wrong or expired reset code
|
||||||
|
When ResetPasswordUseCase.ResetPassword is called
|
||||||
|
Then it returns the existing invalid or expired sentinel
|
||||||
|
And RevokeAllByUser is never called
|
||||||
|
|
||||||
|
Scenario: Use case: a failure to revoke keys after a reset is reported
|
||||||
|
Given a valid reset code and an apikey.Repository whose RevokeAllByUser returns an error
|
||||||
|
When ResetPasswordUseCase.ResetPassword is called
|
||||||
|
Then the use case returns that error
|
||||||
|
And the password was already changed
|
||||||
@@ -0,0 +1,171 @@
|
|||||||
|
# QA procedure: API keys
|
||||||
|
|
||||||
|
Package: `test` (black-box). No live server, no real SQLite file, no real SMTP.
|
||||||
|
|
||||||
|
## Setup shared by every case
|
||||||
|
1. Call `validator.InitValidator()` once per test.
|
||||||
|
2. Add in-memory fakes with unique type names across the package: `mockAPIKeyRepo`
|
||||||
|
(implements `apikey.Repository` including `RevokeAllByUser`, with a `fail` switch per method such as
|
||||||
|
`failNext("TouchLastUsed")`, a `touchCalls` counter and a `revokeAllCalls` log of `(userId, at)`) and
|
||||||
|
`stubKeyGenerator` (deterministic raw/prefix/hash). Reuse `mockUserRepo`, `stubHasher` and the
|
||||||
|
article, media and invite fakes.
|
||||||
|
3. HTTP tests use the real SHA-256 generator, so key format and hashing are real. Unit-level tests
|
||||||
|
use `stubKeyGenerator`.
|
||||||
|
4. Build the handler stack from a `*api.UseCases` container holding fakes and mount
|
||||||
|
`api.InitBackendRoutes(container, settings)` on a test server (unused use cases stay nil). It is the
|
||||||
|
most faithful way to test the middleware order and the exclusions. If a nil use case breaks a
|
||||||
|
handler constructor, fall back to a fresh `chi.NewRouter()` that mirrors `api/router.go`:
|
||||||
|
`jwtauth.Verifier`, the key middleware, `jwtauth.Authenticator`, `RequireCurrentToken`,
|
||||||
|
`RequireVerifiedUser` (and `RequireOwner` on the invite group) for the key-accepting routes
|
||||||
|
(including `GET /auth/me`); `RequireSession` ahead of `jwtauth.Verifier` on `/api-key`,
|
||||||
|
`POST /auth/verify`, `DELETE /auth/register` and `/system`; and the public auth routes with neither.
|
||||||
|
The test token is `jwtauth.New("HS256", []byte("test-secret"), nil)`.
|
||||||
|
5. Inject a fake clock (`now func() time.Time`) into the key use cases and `ResetPasswordUseCase`.
|
||||||
|
6. Seed users: owner 1 "marta", admin 2 "dev", admin 3 "pat" (all verified), unverified 4 "quinn".
|
||||||
|
7. Helpers: `cookieFor(userId, tokenVersion)` mints a jwt cookie with
|
||||||
|
`token.Encode(map[string]any{"user_id": id, "token_version": v})`; `bearer(raw)` sets the header.
|
||||||
|
Create real keys through `POST /v1/api-key` with the cookie so the shown-once value is genuine.
|
||||||
|
|
||||||
|
## POST /v1/api-key
|
||||||
|
8. Admin 2 cookie, `{"name":"ci-deploy"}` -> `201`, `Cache-Control: no-store`, key set is exactly `id`,
|
||||||
|
`name`, `prefix`, `key`, `created_at`, `expires_at`; `key` matches `^rcms_[A-Za-z0-9_-]{43}$`; prefix
|
||||||
|
is `key[:12]`; stored `HashedKey` equals the generator's `Hash(key)`; `UserID` 2; the raw key is
|
||||||
|
stored nowhere in the fake.
|
||||||
|
9. Two creations give two different keys and ids.
|
||||||
|
10. With `expires_at` 30 days ahead -> `201`, echoed instant.
|
||||||
|
11. Invalid bodies (table): not-json -> `400` `apperr.BodyErrorMessage`; `{}`, `{"name":""}` -> `400`,
|
||||||
|
body contains `'Name'` and `required`; 61-char name -> `400`, contains `max`; `expires_at`
|
||||||
|
"yesterday" -> `400` `BodyErrorMessage`; past `expires_at` -> `400` `apperr.APIKeyExpiryErrorMessage`.
|
||||||
|
Each: repository still empty.
|
||||||
|
12. Body `{"name":"sneaky","user_id":1,"role":"owner"}` with admin 2 -> `201`; stored `UserID` 2; that
|
||||||
|
key on `POST /v1/user/invite` -> `403` `apperr.OwnerRequiredErrorMessage`, no invite.
|
||||||
|
13. Access table: no credentials -> `401`; user 4 cookie -> `403` `apperr.VerificationRequiredErrorMessage`;
|
||||||
|
stale `token_version` -> `401`. Each: repository empty.
|
||||||
|
|
||||||
|
## Shown once
|
||||||
|
14. After case 8, `GET /v1/api-key` -> entry keys exactly `id`, `user_id`, `name`, `prefix`, `status`,
|
||||||
|
`created_at`, `last_used_at`, `expires_at`, `revoked_at`; assert the response bytes contain neither
|
||||||
|
the raw key nor the stored hash. Also assert the raw key and hash are absent from the `DELETE`
|
||||||
|
response and from every error body in this file.
|
||||||
|
15. There is no route that returns a key again: `GET /v1/api-key/{id}` -> `404` or `405` (whatever the
|
||||||
|
router yields; assert not `200`).
|
||||||
|
|
||||||
|
## Authentication
|
||||||
|
16. Table over `GET /v1/settings`, `GET /v1/user`, `PATCH /v1/user/me`, `POST /v1/article`,
|
||||||
|
`PATCH /v1/article/{id}/publish`, `DELETE /v1/article/{id}`, `GET /v1/media`, `DELETE /v1/media/{id}`
|
||||||
|
with only the Bearer key of admin 2 -> `200` each; the stored side effects (author, display name)
|
||||||
|
belong to user 2.
|
||||||
|
17. Public article routes: seed offline article 5, online article 6. Key -> list has both, `GET /5` is
|
||||||
|
`200`. No credentials -> list has only 6, `GET /5` is `404`. `Bearer rcms_unknown` on `GET /v1/article`
|
||||||
|
-> `401` `apperr.UnauthorizedErrorMessage`.
|
||||||
|
18. Owner key `POST /v1/user/invite` -> `201`, `invited_by` 1. Admin key -> `403`
|
||||||
|
`apperr.OwnerRequiredErrorMessage`, no invite and no mail.
|
||||||
|
19. Table of 401 cases on `GET /v1/settings`, all with body `apperr.UnauthorizedErrorMessage` exactly (the
|
||||||
|
stored-hash case has no `rcms_` prefix, so it takes the jwt path: assert status `401` only):
|
||||||
|
unknown well-formed key; expired (clock one second past `expires_at`); revoked; creator deleted from
|
||||||
|
the user fake; creator unverified (set `IsVerified=false` in the fake); `Bearer rcms_`; one
|
||||||
|
character changed; the stored hash sent as the key. Assert each also leaves `touchCalls == 0`.
|
||||||
|
Without an `rcms_` key the existing `jwtauth.Authenticator` response is unchanged: assert status `401`.
|
||||||
|
20. A key whose `ExpiresAt` equals the clock's now is rejected; one second later than now is accepted.
|
||||||
|
21. Cookie path unchanged: valid cookie -> `200`; valid jwt in `Authorization: Bearer` with no cookie ->
|
||||||
|
`200`; stale `token_version` -> `401`; no credentials on a protected route -> `401`.
|
||||||
|
22. Precedence: valid key of admin 3 plus an owner cookie on `POST /v1/user/invite` -> `403`
|
||||||
|
(acts as admin 3); `Bearer rcms_unknown` plus an owner cookie on `GET /v1/settings` -> `401`.
|
||||||
|
23. Role is read live: change the stored role of user 2 from admin to owner in the fake (test-only) and
|
||||||
|
assert the key is now owner-capable, then back, and assert it is not. This pins "never more
|
||||||
|
rights than the creator's current rights".
|
||||||
|
24. `GET /v1/auth/me` with only admin 2's key -> `200`, body byte-equal to the body admin 2's cookie gets
|
||||||
|
on the same route, describing user 2. `Bearer rcms_unknown` on `GET /v1/auth/me` -> `401`
|
||||||
|
`apperr.UnauthorizedErrorMessage`.
|
||||||
|
|
||||||
|
## Session-only routes (RequireSession)
|
||||||
|
25. Table, each with body `apperr.SessionRequiredErrorMessage`, status `403`, assert the underlying use
|
||||||
|
cases (key repository, verify, cancel registration, update status/check/download/restart) were
|
||||||
|
not invoked and the key repository is unchanged:
|
||||||
|
- owner 1's active key on `POST /v1/api-key`, `GET /v1/api-key`, `DELETE /v1/api-key/1`,
|
||||||
|
`POST /v1/auth/verify`, `DELETE /v1/auth/register`, `GET /v1/system/update`,
|
||||||
|
`POST /v1/system/update/check`, `POST /v1/system/update/download`, `POST /v1/system/update/restart`;
|
||||||
|
- a revoked key on `GET /v1/api-key`;
|
||||||
|
- an unknown well-formed `rcms_...` key on `POST /v1/system/update/check`;
|
||||||
|
- the bare string `rcms_` on `DELETE /v1/auth/register`.
|
||||||
|
The 403 comes before any authentication, so assert the same 403 for an owner key and a garbage key.
|
||||||
|
26. Session routes unchanged for sessions: owner cookie on `POST /v1/api-key`, `GET /v1/api-key`,
|
||||||
|
`GET /v1/system/update`, `POST /v1/system/update/check` -> the same status and body as before this
|
||||||
|
feature; no credentials -> status `401` (existing Authenticator); a jwt in `Authorization: Bearer`
|
||||||
|
(not starting with `rcms_`) -> the same result as the cookie.
|
||||||
|
27. Public auth routes with an owner key attached: `POST /v1/auth/login` with wrong credentials -> `403`
|
||||||
|
`apperr.LogsErrorMessage`, no `jwt` Set-Cookie; `POST /v1/auth/password-reset/confirm` with a wrong
|
||||||
|
code -> the same response as without the key, and the key is not rejected with
|
||||||
|
`SessionRequiredErrorMessage`. The user's stored password hash and `TokenVersion` are unchanged.
|
||||||
|
|
||||||
|
## Password reset revokes keys
|
||||||
|
28. Seed user 2 with active keys "a" and "b" (each `200` on `GET /v1/settings`), user 3 with key "c", and a
|
||||||
|
reset code for user 2 (hash of "reset-code-1", unexpired). `POST /v1/auth/password-reset/confirm`
|
||||||
|
`{"email":"dev@example.com","code":"reset-code-1","password":"newpassword1"}` -> `200`; then keys "a"
|
||||||
|
and "b" get `401` `apperr.UnauthorizedErrorMessage` on `GET /v1/settings`.
|
||||||
|
29. Same seed: key "c" still gets `200` and has no `revoked_at`.
|
||||||
|
30. Same seed with the fake clock at T: log in as user 2 with the new password, `GET /v1/api-key` with the
|
||||||
|
new cookie; "a" and "b" have status `revoked` and `revoked_at` equal to T.
|
||||||
|
31. A key of user 2 already revoked at T0 keeps `revoked_at` T0 after a reset at a later T; the active
|
||||||
|
key gets T.
|
||||||
|
32. Failed confirms (table: wrong code; expired code; unknown email) -> status not `200`; key "a" has no
|
||||||
|
`revoked_at`, still `200` on `GET /v1/settings`, and `revokeAllCalls` is empty.
|
||||||
|
|
||||||
|
## Listing
|
||||||
|
33. Admin 2 sees only own keys; owner 1 sees all, newest first, each with its `user_id`.
|
||||||
|
34. Status table: active never used (`active`, nulls), active used (timestamp kept), expired
|
||||||
|
(`expired`), revoked (`revoked`, `revoked_at` set), expired-and-revoked (`revoked`).
|
||||||
|
|
||||||
|
## Revoke
|
||||||
|
35. Own key -> `204`, empty body; the key then gets `401` on `GET /v1/settings`; the list shows `revoked`.
|
||||||
|
36. Second `DELETE` -> `204`, `revoked_at` unchanged.
|
||||||
|
37. Admin 2 revoking admin 3's key -> `404` `apperr.APIKeyNotFoundErrorMessage`; the key still works.
|
||||||
|
Owner revoking it -> `204`; it then gets `401`.
|
||||||
|
38. Ids `abc`, `-1`, `4294967296` -> `400` `apperr.IdUint32ErrorMessage`; unknown id -> `404`.
|
||||||
|
39. Repository failure on `Revoke` -> `500` "Internal server error"; the key still works.
|
||||||
|
|
||||||
|
## last_used_at
|
||||||
|
40. Use-case level with the fake clock: first auth at T writes T; at T+30s no write
|
||||||
|
(`touchCalls` unchanged); at T+61s writes T+61s.
|
||||||
|
41. `TouchLastUsed` failing -> the request still returns `200`.
|
||||||
|
42. Rejected keys (case 19) never write.
|
||||||
|
|
||||||
|
## Rate limit
|
||||||
|
43. Mirror a group using the new per-key limiter with a limit of 2 (an exported constructor taking max
|
||||||
|
attempts and window): third request with key A -> `429`, body `apperr.TooManyRequestsErrorMessage`,
|
||||||
|
`Retry-After` header; key B and a cookie request still `200`; invalid keys stay `401`, never `429`.
|
||||||
|
44. Through `api.InitBackendRoutes`, send 121 requests with one key to `GET /v1/settings` -> the 121st is
|
||||||
|
`429`, the first 120 are `200`.
|
||||||
|
|
||||||
|
## CORS
|
||||||
|
45. Through `api.InitRoutes` with `CorsAllowedOrigins` `["https://app.example.com"]`: `OPTIONS /v1/article/1`
|
||||||
|
with `Origin` and `Access-Control-Request-Method: PATCH` -> success, `Access-Control-Allow-Methods`
|
||||||
|
includes `PATCH`; with `TRACE` it is not allowed.
|
||||||
|
|
||||||
|
## Use case level (no HTTP)
|
||||||
|
46. `CreateAPIKey` with `stubKeyGenerator`: repository receives the hash and the prefix and the user id;
|
||||||
|
the raw key appears only in the return value; a generator error -> returned, nothing stored; past
|
||||||
|
expiry -> `errors.Is(err, apikey.ErrExpiryNotInFuture)`.
|
||||||
|
47. `AuthenticateAPIKey`: each invalid case in 19 and 20 -> `errors.Is(err, apikey.ErrAPIKeyInvalid)`; a
|
||||||
|
valid key returns the user; an unexpected repository error is returned and is not `ErrAPIKeyInvalid`.
|
||||||
|
48. `ListAPIKeys` for admin and owner; `RevokeAPIKey` own, other's (`ErrAPIKeyNotFound` for admin),
|
||||||
|
owner any, unknown (`ErrAPIKeyNotFound`).
|
||||||
|
49. `ResetPasswordUseCase` built over `mockUserRepo`, `stubHasher`, `mockAPIKeyRepo` and a fake clock at T:
|
||||||
|
a successful reset for user 2 -> exactly one `RevokeAllByUser(2, T)` and user 3's keys untouched; a
|
||||||
|
wrong or expired code -> the existing sentinel and `revokeAllCalls` empty; `RevokeAllByUser`
|
||||||
|
failing -> that error is returned (the password was already changed).
|
||||||
|
50. `mockAPIKeyRepo.RevokeAllByUser` semantics: sets `RevokedAt` only on that user's not-yet-revoked
|
||||||
|
keys.
|
||||||
|
51. SHA-256 generator: raw matches the regex, `Hash(raw)` equals the generated hash, two generated keys
|
||||||
|
differ, prefix is the first 12 characters.
|
||||||
|
|
||||||
|
## Manual verification (not exercised by the Go tests)
|
||||||
|
- Real SQLite: start `task dev:api`, confirm `AutoMigrate` creates the api_keys table with a unique index
|
||||||
|
on the hashed key, create a key, restart, and check it still authenticates.
|
||||||
|
- With `curl`, run `Authorization: Bearer <key>` against a running server for an article create, a media
|
||||||
|
upload, an owner invite and `GET /v1/auth/me`, and confirm `PATCH` works from a browser origin listed
|
||||||
|
in `CORS_ALLOWED_ORIGINS`.
|
||||||
|
- Confirm the full key is shown only in the creation response and appears in no server log
|
||||||
|
(`ENVIRONMENT=development` enables httplog).
|
||||||
|
- A real reverse proxy: confirm `Authorization` is forwarded and `Retry-After` reaches the client.
|
||||||
|
- A real password reset by email: confirm the keys stop working after the link is used.
|
||||||
@@ -0,0 +1,352 @@
|
|||||||
|
Feature: API keys screen
|
||||||
|
|
||||||
|
As a verified RenewCMS owner or admin
|
||||||
|
I want /integration/api-keys to list my API keys, create new ones and revoke them
|
||||||
|
So that a script or service can call the API with my rights, and I can cut it off at any time
|
||||||
|
|
||||||
|
Background:
|
||||||
|
Given /integration/api-keys is a verified route (meta.auth "verified") rendered as ApiKeysPage
|
||||||
|
with CreateApiKeyModal, ApiKeyReveal and a revoke confirmation dialog, inside
|
||||||
|
DashboardShell, per docs/design/routes.md
|
||||||
|
And the screen is a sub-page of Integration, per docs/design/screens/integration.md
|
||||||
|
And the screen calls, with relative URLs through useApi only, GET /v1/api-key,
|
||||||
|
POST /v1/api-key and DELETE /v1/api-key/{id}
|
||||||
|
And a GET /v1/api-key entry has the fields id, user_id, name, prefix (12 characters), status
|
||||||
|
("active", "expired" or "revoked"), created_at, last_used_at, expires_at and revoked_at, and
|
||||||
|
never a key or a hash, per features/api_keys.feature
|
||||||
|
And an owner's entries also carry created_by_name, the creator's display name or username (see
|
||||||
|
the API scenarios below)
|
||||||
|
And the list arrives newest first; an owner receives every user's keys, an admin only their own
|
||||||
|
And the PageHeader shows breadcrumb "Integration › API keys" (Integration links to
|
||||||
|
/integration), title "API keys" and a primary "Create key" button on the right at desktop
|
||||||
|
And the description reads "Keys act as the user who created them. As an owner you see
|
||||||
|
everyone's keys." for an owner, and "Keys act as you, with your role. You only see your own
|
||||||
|
keys." for an admin; a session without a role gets the admin rendering
|
||||||
|
And the table, on desktop, has the columns Name, Key, Status, Created by (owner only), Created,
|
||||||
|
Last used, Expires and an action column, in a UTable with a 36 px header and 48 px rows
|
||||||
|
And below md, each key is a card: name and status badge, prefix in monospace, then
|
||||||
|
"Created {date}[ by {name}] · Last used {date} · Expires {date}", then a 44 px "Revoke" button
|
||||||
|
And the Key column and the card show the prefix cut to its first 9 characters followed by "…",
|
||||||
|
for example "rcms_Kf3x…", and the full key is never shown in the list
|
||||||
|
And the revoke text uses the same 9-character prefix plus "…"
|
||||||
|
And dates are absolute and formatted for the current locale, for example "12 Mar 2026" in
|
||||||
|
English; a null expires_at reads "None" and a null last_used_at reads "Never"
|
||||||
|
And a Created by cell with an empty created_by_name shows "—"
|
||||||
|
And the Status badge is a UBadge: active success soft, expired warning soft, revoked neutral
|
||||||
|
with a muted row
|
||||||
|
And "Revoke" is offered on active and expired keys, never on revoked keys
|
||||||
|
And a note with an info icon always closes the page: "Resetting a user's password revokes all of
|
||||||
|
their keys."
|
||||||
|
And the Integration page (/integration, features/integration.feature) gains a "Manage API
|
||||||
|
keys" link to /integration/api-keys (see the Integration link scenario)
|
||||||
|
And on /integration/api-keys the sidebar and drawer item "Integration" carries
|
||||||
|
aria-current="page"
|
||||||
|
And every visible string goes through t(...), with the English text as the key and its French
|
||||||
|
entry in web/src/i18n/messages.ts
|
||||||
|
And the screen uses Nuxt UI components and design tokens only, with no raw colors
|
||||||
|
And the owner fixture is, newest first as the board draws it:
|
||||||
|
| name | prefix | status | created by | created | last used | expires |
|
||||||
|
| Website build | rcms_Kf3x… | active | Marta Alves | 12 Mar 2026 | 3 Oct 2026 | None |
|
||||||
|
| Nightly media import | rcms_Mq7b… | active | Jonas | 2 Apr 2026 | 3 Oct 2026 | 31 Dec 2026 |
|
||||||
|
| Staging preview | rcms_Zt2d… | expired | Marta Alves | 14 Jun 2026 | 20 Aug 2026 | 30 Aug 2026 |
|
||||||
|
| Old migration script | rcms_Hn5w… | revoked | Inès Duarte | 3 Apr 2026 | 9 May 2026 | None |
|
||||||
|
And the admin fixture (user "Jonas") is:
|
||||||
|
| name | prefix | status | created | last used | expires |
|
||||||
|
| Nightly media import | rcms_Mq7b… | active | 2 Apr 2026 | 3 Oct 2026 | 31 Dec 2026 |
|
||||||
|
| Old CI token | rcms_Lp9c… | revoked | 18 Jan 2026 | 2 Feb 2026 | None |
|
||||||
|
|
||||||
|
Scenario: Owner: list
|
||||||
|
Given the session role is "owner"
|
||||||
|
And GET /v1/api-key answers 200 with the owner fixture
|
||||||
|
When the user navigates to /integration/api-keys
|
||||||
|
Then the four rows show in fixture order with the columns Name, Key, Status, Created by,
|
||||||
|
Created, Last used, Expires
|
||||||
|
And "Staging preview" shows an "expired" badge and "Revoke"
|
||||||
|
And "Old migration script" shows a "revoked" badge, a muted row and no "Revoke"
|
||||||
|
And the description is the owner description
|
||||||
|
|
||||||
|
Scenario: Admin: own keys only
|
||||||
|
Given the session role is "admin"
|
||||||
|
And GET /v1/api-key answers 200 with the admin fixture
|
||||||
|
When the user navigates to /integration/api-keys
|
||||||
|
Then the two rows show with no "Created by" column
|
||||||
|
And on mobile the cards read "Created 2 Apr 2026 · Last used 3 Oct 2026 · Expires 31 Dec 2026"
|
||||||
|
without " by {name}"
|
||||||
|
And the description is the admin description
|
||||||
|
|
||||||
|
Scenario: Loading
|
||||||
|
Given GET /v1/api-key is pending
|
||||||
|
When the user navigates to /integration/api-keys
|
||||||
|
Then four skeleton rows are drawn in the table (two-bar cards below md) and the table has
|
||||||
|
aria-busy "true"
|
||||||
|
And the header "Create key" button is shown
|
||||||
|
|
||||||
|
Scenario: Empty
|
||||||
|
Given GET /v1/api-key answers 200 with []
|
||||||
|
When the user navigates to /integration/api-keys
|
||||||
|
Then a panel shows title "No API keys yet", text "Create a key to call the API from a script or
|
||||||
|
service." and a primary "Create key" button
|
||||||
|
And no table is drawn
|
||||||
|
|
||||||
|
Scenario Outline: Error on load
|
||||||
|
Given GET /v1/api-key fails with <failure>
|
||||||
|
When the user navigates to /integration/api-keys
|
||||||
|
Then an alert (role "alert") shows "Couldn't load your API keys" and "Check your connection and
|
||||||
|
try again." with a "Try again" action
|
||||||
|
And no table, no cards and no empty panel are drawn
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| failure |
|
||||||
|
| status 500 |
|
||||||
|
| a network error |
|
||||||
|
|
||||||
|
Scenario: Try again after an error
|
||||||
|
Given the load failed and the error alert is shown
|
||||||
|
When the user activates "Try again"
|
||||||
|
Then GET /v1/api-key is requested again and, on 200, the list replaces the alert
|
||||||
|
|
||||||
|
Scenario Outline: Session problems use the app-wide handling
|
||||||
|
Given GET /v1/api-key answers <status>
|
||||||
|
When the user navigates to /integration/api-keys
|
||||||
|
Then <outcome>
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| status | outcome |
|
||||||
|
| 401 | the user lands on /login?redirect=/integration/api-keys&reason=expired |
|
||||||
|
| 403 | the user lands on /register/pending |
|
||||||
|
|
||||||
|
Scenario: Create key: modal opened
|
||||||
|
Given the list is shown
|
||||||
|
When the user activates "Create key"
|
||||||
|
Then a modal titled "Create API key" opens with the text "The key acts as you, with your role. It
|
||||||
|
is shown in full once."
|
||||||
|
And it has a Name field with a "0 / 60" counter and help "Required. Up to 60 characters."
|
||||||
|
And it has an "Expiry date (optional)" date input with help "Optional. Must be in the future.
|
||||||
|
Leave it empty for a key that does not expire."
|
||||||
|
And it has the buttons "Cancel" and "Create key"
|
||||||
|
And Name has focus
|
||||||
|
|
||||||
|
Scenario Outline: Create key: validation
|
||||||
|
Given the Create API key modal is open
|
||||||
|
When the user submits with name "<name>" and expiry "<expiry>"
|
||||||
|
Then no request is sent
|
||||||
|
And <name_error>
|
||||||
|
And <expiry_error>
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| name | expiry | name_error | expiry_error |
|
||||||
|
| | 12 Mar 2026 | Name shows the error "Enter a name." in red | Expiry shows the error "Choose a date in the future." in red |
|
||||||
|
| | | Name shows the error "Enter a name." in red | Expiry shows no error |
|
||||||
|
| Deploy | 12 Mar 2026 | Name shows no error | Expiry shows the error "Choose a date in the future." in red |
|
||||||
|
|
||||||
|
Scenario: Create key: name too long
|
||||||
|
Given the Create API key modal is open
|
||||||
|
When the user types a name of 75 characters
|
||||||
|
Then the counter reads "75 / 60" in the error color
|
||||||
|
And Name shows the error "Use 60 characters or fewer." in red
|
||||||
|
And submitting sends no request
|
||||||
|
|
||||||
|
Scenario: Create key: success reveals the key once
|
||||||
|
Given the Create API key modal is open
|
||||||
|
When the user submits name "Nightly media import" and an empty expiry
|
||||||
|
Then exactly one POST /v1/api-key is sent with body {"name": "Nightly media import"} and no
|
||||||
|
expires_at
|
||||||
|
And on 201 the form modal is replaced by a modal titled "Your new API key" with the text
|
||||||
|
"\"Nightly media import\" is ready. Copy the key and store it somewhere safe."
|
||||||
|
And a warning alert (UAlert, color warning, triangle-alert icon) reads "You won't be able to
|
||||||
|
see this key again."
|
||||||
|
And the full key from the response is shown in a monospace box with a "Copy" button (icon copy)
|
||||||
|
And the note "Closing this window discards the key from the screen. Copy it first." is shown
|
||||||
|
And the only button is a primary "Done"
|
||||||
|
|
||||||
|
Scenario: Create key: with an expiry
|
||||||
|
Given the Create API key modal is open
|
||||||
|
And the local date is D
|
||||||
|
When the user submits name "temp" and the expiry date D + 30 days
|
||||||
|
Then the POST body carries name "temp" and expires_at equal to 23:59:59 local time on D + 30
|
||||||
|
days, as an RFC3339 instant with the local offset
|
||||||
|
|
||||||
|
Scenario Outline: The expiry date is checked against the same instant the API checks
|
||||||
|
Given the Create API key modal is open and the current time is T
|
||||||
|
When the user submits a name and the expiry date <date>
|
||||||
|
Then <outcome>
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| date | outcome |
|
||||||
|
| today | the request is sent, because 23:59:59 today is after T |
|
||||||
|
| yesterday | no request is sent and Expiry shows "Choose a date in the future." |
|
||||||
|
| tomorrow | the request is sent |
|
||||||
|
|
||||||
|
Scenario: One-time reveal: copied
|
||||||
|
Given the key reveal is open
|
||||||
|
When the user activates "Copy"
|
||||||
|
Then the full key is written to the clipboard
|
||||||
|
And the button shows icon check and text "Copied" in the success color, announced to assistive
|
||||||
|
technology
|
||||||
|
When 2 seconds elapse
|
||||||
|
Then the button reverts to icon copy and text "Copy"
|
||||||
|
|
||||||
|
Scenario: One-time reveal: Done discards the key
|
||||||
|
Given the key reveal is open
|
||||||
|
When the user activates "Done"
|
||||||
|
Then the modal closes
|
||||||
|
And the full key is no longer in the DOM, the component state, the URL or any storage
|
||||||
|
And the new key is listed first with its 9-character prefix and "…" only, status "active",
|
||||||
|
created by the current user (owner view), last used "Never", expires per the request, and no
|
||||||
|
second GET /v1/api-key is made
|
||||||
|
And reopening "Create key" shows an empty form
|
||||||
|
|
||||||
|
Scenario Outline: Dismissing the modals
|
||||||
|
Given <modal> is open
|
||||||
|
When the user <action>
|
||||||
|
Then <outcome>
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| modal | action | outcome |
|
||||||
|
| the key reveal | presses Escape | the modal closes and the key is discarded, as for Done |
|
||||||
|
| the key reveal | clicks the backdrop | the modal stays open |
|
||||||
|
| the Create key form | presses Escape | the modal closes with no request |
|
||||||
|
| the Create key form | clicks the backdrop | the modal stays open |
|
||||||
|
|
||||||
|
Scenario: Create key: Cancel discards the form
|
||||||
|
Given the Create API key modal is open with typed values
|
||||||
|
When the user activates "Cancel"
|
||||||
|
Then the modal closes without a request, focus returns to the opening button, and reopening it
|
||||||
|
shows an empty form
|
||||||
|
|
||||||
|
Scenario: Revoke: confirm
|
||||||
|
Given the owner list is shown
|
||||||
|
When the user activates "Revoke" on "Nightly media import"
|
||||||
|
Then a dialog titled "Revoke this key?" opens with the text "\"Nightly media import\"
|
||||||
|
(rcms_Mq7b…) will stop working right away. Requests that use it answer 401. This can't be
|
||||||
|
undone."
|
||||||
|
And its buttons are "Keep key" and a destructive "Revoke key"
|
||||||
|
And "Keep key" closes the dialog with no request and the row unchanged
|
||||||
|
|
||||||
|
Scenario: Revoked
|
||||||
|
Given the revoke dialog is open for "Nightly media import" (id 2)
|
||||||
|
When the user activates "Revoke key"
|
||||||
|
Then exactly one DELETE /v1/api-key/2 is sent
|
||||||
|
And on 204 the dialog closes and the row stays listed with status "revoked", a muted row and no
|
||||||
|
"Revoke" button
|
||||||
|
And a success toast shows title "Key revoked" and text "\"Nightly media import\" can no longer
|
||||||
|
be used."
|
||||||
|
And no second GET /v1/api-key is made
|
||||||
|
|
||||||
|
Scenario: Mobile Create key button, not drawn on board
|
||||||
|
Given the viewport is below md
|
||||||
|
When the list, the loading skeleton or the error alert is shown
|
||||||
|
Then a primary full-width 48 px "Create key" button is pinned to the bottom of the screen
|
||||||
|
And it is hidden while any modal or dialog is open, and in the Empty state where the panel has
|
||||||
|
its own "Create key" button
|
||||||
|
And the header has no "Create key" button below md
|
||||||
|
|
||||||
|
Scenario: Integration page links to the keys screen
|
||||||
|
Given the user is on /integration
|
||||||
|
Then a "Manage API keys" link (UButton variant link, arrow-right trailing icon) is shown below
|
||||||
|
the three info notes
|
||||||
|
When the user activates it
|
||||||
|
Then the user lands on /integration/api-keys and the sidebar "Integration" item keeps
|
||||||
|
aria-current="page"
|
||||||
|
|
||||||
|
Scenario: Language: every string has a French entry
|
||||||
|
Given the language is "fr"
|
||||||
|
When the user opens each state of the screen
|
||||||
|
Then every visible string is the French message and none falls back to English
|
||||||
|
And dates are formatted for "fr"
|
||||||
|
|
||||||
|
Scenario: Create key: sending, not drawn on board, no visual state
|
||||||
|
Given the Create API key modal is open with a valid name
|
||||||
|
When the user submits and POST /v1/api-key is pending
|
||||||
|
Then the primary button reads "Creating…", Name, Expiry and "Cancel" are disabled
|
||||||
|
And Escape does not close the modal
|
||||||
|
|
||||||
|
Scenario Outline: Create key: failed, not drawn on board, no visual state
|
||||||
|
Given the Create API key modal is open with name "Nightly media import"
|
||||||
|
When POST /v1/api-key fails with <failure>
|
||||||
|
Then an alert in the modal reads "<copy>"
|
||||||
|
And the typed values are kept, the form is enabled again, no row is added, and no field error
|
||||||
|
is shown
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| failure | copy |
|
||||||
|
| status 500 | Couldn't create the key. Try again in a moment. |
|
||||||
|
| a network error | Couldn't reach RenewCMS. Check your connection and try again. |
|
||||||
|
| status 429 | Too many requests. Wait a moment, then try again. |
|
||||||
|
| status 400 | Something in the form isn't valid. Check the highlighted fields. |
|
||||||
|
|
||||||
|
Scenario: Create key: retry after failure, not drawn on board, no visual state
|
||||||
|
Given a failed create left the modal open
|
||||||
|
When the user submits again and POST answers 201
|
||||||
|
Then the reveal opens and the row is added
|
||||||
|
|
||||||
|
Scenario: Revoke: sending, not drawn on board, no visual state
|
||||||
|
Given the revoke dialog is open
|
||||||
|
When the user activates "Revoke key" and DELETE is pending
|
||||||
|
Then "Revoke key" reads "Revoking…", both buttons are disabled, and Escape does not close the
|
||||||
|
dialog
|
||||||
|
|
||||||
|
Scenario Outline: Revoke: failed, not drawn on board, no visual state
|
||||||
|
Given the revoke dialog is open for "Nightly media import"
|
||||||
|
When DELETE fails with <failure>
|
||||||
|
Then a notice in the dialog reads "<copy>"
|
||||||
|
And the dialog stays open, the buttons are enabled again, and the row is unchanged
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| failure | copy |
|
||||||
|
| status 500 | Couldn't revoke the key. Try again in a moment. |
|
||||||
|
| a network error | Couldn't reach RenewCMS. Check your connection and try again. |
|
||||||
|
|
||||||
|
Scenario: Revoke: key already gone, 404, not drawn on board, no visual state
|
||||||
|
Given the revoke dialog is open for "Nightly media import" (id 2)
|
||||||
|
When DELETE /v1/api-key/2 answers 404
|
||||||
|
Then the dialog closes, the row is removed from the list, and an error toast reads "That key no
|
||||||
|
longer exists."
|
||||||
|
|
||||||
|
Scenario: Last used, never, not drawn on board, no visual state
|
||||||
|
Given an entry whose last_used_at is null
|
||||||
|
Then its Last used cell and its mobile card text read "Never"
|
||||||
|
|
||||||
|
Scenario: API: an owner's list carries the creator's name
|
||||||
|
Given owner 1 "marta" with display name "Marta Alves", admin 2 "dev" with display name "Dev Two"
|
||||||
|
and admin 3 "pat" with an empty display name
|
||||||
|
And keys "a" by user 1, "b" by user 2 and "c" by user 3
|
||||||
|
When owner 1 sends GET /v1/api-key with a jwt cookie
|
||||||
|
Then each entry has the key created_by_name
|
||||||
|
And entry "a" has "Marta Alves", "b" has "Dev Two" and "c" has "pat"
|
||||||
|
And the other nine fields are unchanged from features/api_keys.feature
|
||||||
|
|
||||||
|
Scenario: API: a whitespace-only display name falls back to the username
|
||||||
|
Given admin 3 "pat" with display name " " and a key "c"
|
||||||
|
When owner 1 sends GET /v1/api-key
|
||||||
|
Then entry "c" has created_by_name "pat"
|
||||||
|
|
||||||
|
Scenario: API: an admin's list is unchanged
|
||||||
|
Given admin 2 with keys "a" and "b"
|
||||||
|
When admin 2 sends GET /v1/api-key with a jwt cookie
|
||||||
|
Then every entry has exactly the keys id, user_id, name, prefix, status, created_at,
|
||||||
|
last_used_at, expires_at, revoked_at
|
||||||
|
And no entry has created_by_name
|
||||||
|
|
||||||
|
Scenario: API: a key whose creator no longer exists
|
||||||
|
Given a key whose user record was deleted
|
||||||
|
When owner 1 sends GET /v1/api-key
|
||||||
|
Then its entry has created_by_name ""
|
||||||
|
And the response status is 200 and the other entries are unaffected
|
||||||
|
|
||||||
|
Scenario: API: a failing user lookup fails the list
|
||||||
|
Given the user repository fake returns an unexpected error on Get for a creator
|
||||||
|
When owner 1 sends GET /v1/api-key
|
||||||
|
Then the response status is 500 and the body is "Internal server error"
|
||||||
|
|
||||||
|
Scenario: API: the creator name is resolved once per user
|
||||||
|
Given owner 1 has 3 keys and admin 2 has 2 keys
|
||||||
|
When owner 1 sends GET /v1/api-key
|
||||||
|
Then the user repository received one Get per distinct creator, not one per key
|
||||||
|
|
||||||
|
Scenario: Use case: ListAPIKeys returns the creator name only to an owner
|
||||||
|
Given a fake apikey.Repository and a fake user.Repository
|
||||||
|
When ListAPIKeys is called for an owner
|
||||||
|
Then every APIKeyEntry carries the creator's name
|
||||||
|
When ListAPIKeys is called for an admin
|
||||||
|
Then every APIKeyEntry has an empty creator name and the handler omits the field
|
||||||
@@ -0,0 +1,235 @@
|
|||||||
|
# QA: API keys screen
|
||||||
|
|
||||||
|
Two parts: the Go API change (HTTP-level, in `test/`) and the SPA (Vitest and visual).
|
||||||
|
|
||||||
|
## What changes in the backend
|
||||||
|
|
||||||
|
Only `GET /v1/api-key` called by an owner changes: each entry gains `created_by_name`, the creator's
|
||||||
|
display name (trimmed, non-empty) or else username, and `""` when the creator no longer exists.
|
||||||
|
Admin entries keep exactly the nine existing fields and never carry `created_by_name`.
|
||||||
|
`features/api_keys.feature` is not edited. Its exact-fields scenario is made as an admin and stays
|
||||||
|
true. No domain or persistence change: `ListAPIKeysUseCase` already holds `user.Repository` and
|
||||||
|
resolves each distinct creator once through `Get`.
|
||||||
|
|
||||||
|
## Go: created_by_name on GET /v1/api-key
|
||||||
|
|
||||||
|
Extend `test/api_keys_http_test.go`. Build the handler from `NewHandler(...)` over use cases wired
|
||||||
|
to the existing in-memory fakes (apikey.Repository, user.Repository, KeyGenerator, fake clock).
|
||||||
|
Mount it on a fresh `chi.NewRouter()` that mirrors `api/router.go`, wrapped in `jwtauth.Verifier`
|
||||||
|
and `jwtauth.Authenticator` with a test `jwtauth.New("HS256", ...)`; call
|
||||||
|
`validator.InitValidator()`; exercise it with `httptest`. No live server, no real SQLite, no real
|
||||||
|
SMTP. Users: owner 1 "marta" (display name "Marta Alves"), admin 2 "dev" ("Dev Two"), admin 3
|
||||||
|
"pat" (empty display name), all verified.
|
||||||
|
|
||||||
|
1. **Owner sees names** - keys a (user 1), b (user 2), c (user 3); owner cookie GET /v1/api-key;
|
||||||
|
assert 200, every entry has `created_by_name`, a "Marta Alves", b "Dev Two", c "pat", and the
|
||||||
|
other nine fields as before (newest first).
|
||||||
|
2. **Whitespace display name** - user 3 display name " "; assert "pat".
|
||||||
|
3. **Admin unchanged** - admin 2 cookie; assert every entry has exactly the nine existing fields
|
||||||
|
(use `apiKeyAssertExactFields`) and no `created_by_name`. Check that the existing exact-fields
|
||||||
|
test at line 341 is made as an admin; if it is made as an owner, update it and report it.
|
||||||
|
4. **Deleted creator** - key whose user was removed from the fake; owner GET; assert 200 and
|
||||||
|
`created_by_name` "" for it.
|
||||||
|
5. **User lookup fails** - the fake user repository returns an error on Get for a creator; assert
|
||||||
|
500 and body "Internal server error".
|
||||||
|
6. **One lookup per creator** - the fake counts Get calls; owner with 3 + 2 keys over 2 creators;
|
||||||
|
assert the creator lookups equal the distinct creators (plus the requester's own Get).
|
||||||
|
7. **Use case level** - ListAPIKeys for an owner returns entries with the creator name; for an
|
||||||
|
admin returns empty creator names; the other existing ListAPIKeys tests pass unchanged.
|
||||||
|
8. **Regression** - the existing api_keys tests still pass; list order, statuses, 401 and 403
|
||||||
|
behaviour are unchanged.
|
||||||
|
|
||||||
|
Run with `task test`; one test with `task test -- -run 'TestName'`.
|
||||||
|
|
||||||
|
## Automated SPA (Vitest + Vue Test Utils, `task test:web`)
|
||||||
|
|
||||||
|
Mock `useApi`'s `request` for GET /v1/api-key, POST /v1/api-key and DELETE /v1/api-key/{id} per
|
||||||
|
case. Mount ApiKeysPage inside DashboardShell with a resolved verified session (id 1, "marta",
|
||||||
|
display name "Marta Alves", role "owner") and a test router at /integration/api-keys; admin cases
|
||||||
|
use role "admin", username "jonas". Mocked owner entries carry `created_by_name`. Stub
|
||||||
|
`navigator.clipboard.writeText` per case. No test freezes the system date; specs assert on the
|
||||||
|
fixtures' absolute dates only, and the expiry cases build their dates from the real clock. Run
|
||||||
|
layout cases at desktop and below-md (mock `matchMedia`).
|
||||||
|
|
||||||
|
1. **Owner: list** - breadcrumb (with the Integration link), title, owner description, header
|
||||||
|
labels, rows in fixture order with every cell (prefix cut to 9 characters plus "…", Created by
|
||||||
|
from `created_by_name`), badge words, "Revoke" on rows 1 to 3 and not row 4, row 4 muted, the
|
||||||
|
note; the below-md cards. An entry with an empty `created_by_name` shows "—".
|
||||||
|
2. **Admin: own keys only** - no "Created by" header or cell, admin description, two rows, cards
|
||||||
|
without " by {name}"; a session with no role gets the same rendering.
|
||||||
|
3. **Loading** - unresolved GET; 4 skeleton rows, aria-busy "true", header "Create key"; resolve
|
||||||
|
and assert rows.
|
||||||
|
4. **Empty** - `[]`; the panel copy and its "Create key", no table.
|
||||||
|
5. **Error, Examples-driven** - ApiError(500), then NetworkError; alert copy as drawn, "Try again",
|
||||||
|
no rows; click "Try again" and assert the second request and the rows.
|
||||||
|
6. **401 and 403** - the app-wide redirects, no alert on the page.
|
||||||
|
7. **Create key: opened** - title, text, "0 / 60", helps, buttons, focus on Name.
|
||||||
|
8. **Create key: validation, Examples-driven** - the three Outline rows; error text, no request,
|
||||||
|
errors clear when fixed.
|
||||||
|
9. **Create key: name too long** - 75 characters; counter, error class and text, no request.
|
||||||
|
10. **Create key: success** - one POST with `{"name":"Nightly media import"}` and no expires_at
|
||||||
|
key; the reveal: title, text, warning alert, key equal to the mocked `key`, "Copy", note, only
|
||||||
|
"Done".
|
||||||
|
11. **Create key: expiry** - date D + 30 days; assert expires_at is 23:59:59 local on that day
|
||||||
|
with the local offset. Examples today (sent), yesterday (blocked), tomorrow (sent); build the
|
||||||
|
dates from `new Date()` in the test.
|
||||||
|
12. **Reveal: copied** - fake timers; click "Copy"; writeText with the full key, icon check,
|
||||||
|
"Copied", aria-live announcement; advance 2 s; "Copy" again.
|
||||||
|
13. **Reveal: Done and Escape discard** - assert the modal is gone, the key string appears nowhere
|
||||||
|
in `wrapper.html()`, the router URL, localStorage or sessionStorage; the new row shows the
|
||||||
|
prefix only, status "active", "Never", created by the session user; no second GET; a reopened
|
||||||
|
form is empty. A backdrop click leaves the reveal open.
|
||||||
|
14. **Create key: Cancel and Escape** - no request, empty on reopen, focus back on the opener;
|
||||||
|
a backdrop click does not close.
|
||||||
|
15. **Revoke: confirm and Keep key** - dialog copy with the 9-character prefix, both buttons;
|
||||||
|
"Keep key" closes with no request.
|
||||||
|
16. **Revoked** - confirm; one DELETE with the key's id; row "revoked", muted, no "Revoke"; toast
|
||||||
|
title and text; no second GET.
|
||||||
|
17. **Not drawn: Create sending** - pending POST; "Creating…", disabled fields and Cancel, Escape
|
||||||
|
ignored.
|
||||||
|
18. **Not drawn: Create failed, Examples-driven** - ApiError(500) "Couldn't create the key. Try
|
||||||
|
again in a moment.", NetworkError "Couldn't reach RenewCMS. Check your connection and try
|
||||||
|
again.", ApiError(429) "Too many requests. Wait a moment, then try again.", ApiError(400)
|
||||||
|
"Something in the form isn't valid. Check the highlighted fields."; values kept, form
|
||||||
|
re-enabled, no row added; submit again, resolve 201, assert the reveal.
|
||||||
|
19. **Not drawn: Revoke sending** - "Revoking…", both buttons disabled, Escape ignored.
|
||||||
|
20. **Not drawn: Revoke failed, Examples-driven** - ApiError(500) "Couldn't revoke the key. Try
|
||||||
|
again in a moment." and NetworkError "Couldn't reach RenewCMS. Check your connection and try
|
||||||
|
again."; the notice in the open dialog, row unchanged; retry succeeds.
|
||||||
|
21. **Not drawn: Revoke 404** - the dialog closes, the row is removed, the error toast "That key no
|
||||||
|
longer exists.".
|
||||||
|
22. **Not drawn: Last used "Never"** - null `last_used_at`, desktop cell and mobile card.
|
||||||
|
23. **Mobile pinned button** - below md the pinned 48 px "Create key" exists in list, loading and
|
||||||
|
error; hidden while a modal is open and in Empty; no header button below md.
|
||||||
|
24. **Integration link and navigation** - on /integration assert "Manage API keys" is a link to
|
||||||
|
/integration/api-keys below the three info notes; navigate; assert the sidebar and drawer
|
||||||
|
"Integration" item has aria-current="page" on /integration/api-keys. Update the existing
|
||||||
|
integration specs (features/integration.qa.md case 1) for the extra link.
|
||||||
|
25. **French** - `setLocale('fr')`; walk cases 1, 4, 7, 10, 15, 16, 17, 21; no visible English
|
||||||
|
source string remains; dates use the French format.
|
||||||
|
26. **Messages** - every new `t()` key has a French entry (extend the i18n spec pattern).
|
||||||
|
|
||||||
|
Un-run web tests are reported as NOT RUN, never as passing.
|
||||||
|
|
||||||
|
## Visual (`task visual:check -- integration-api-keys`, desktop and mobile, light and dark)
|
||||||
|
|
||||||
|
Reference: docs/design/screens/integration.md, board `docs/design/source/RenewCMS Screens API
|
||||||
|
keys.dc.html`, exact values in `docs/design/source/ApiKeysPage.dc.html`. Add each state's setup to
|
||||||
|
`web/visual/states.ts` with the board's own sample data (mocked GET /v1/api-key responses include
|
||||||
|
`created_by_name` and 12-character prefixes whose first 9 characters match the board). Hard gate:
|
||||||
|
every capture of every state within 10 %.
|
||||||
|
|
||||||
|
Sample data: the owner and admin fixtures from the feature's Background; Create modal name
|
||||||
|
"Nightly media import" (20 / 60) and expiry 31 Dec 2026; validation: empty name (0 / 60) and
|
||||||
|
expiry 12 Mar 2026; too long: "Nightly import of the new media library from the Brussels office
|
||||||
|
file server" (75 / 60); reveal key rcms_Kf3x9QwL0aBcT7nV2uYdE5sHjR8mPz4WqXg6C1oIyNe for
|
||||||
|
"Nightly media import"; revoke and toast for "Nightly media import" (rcms_Mq7b…).
|
||||||
|
|
||||||
|
No state is clock-sensitive, since every date is fixed text. The Create sample expiry 31 Dec 2026
|
||||||
|
becomes a past date after that day, but the state only displays it, so it gets no skip.
|
||||||
|
|
||||||
|
States:
|
||||||
|
- [ ] Owner: list
|
||||||
|
- [ ] Admin: own keys only
|
||||||
|
- [ ] Loading (the setup holds the request)
|
||||||
|
- [ ] Empty
|
||||||
|
- [ ] Error
|
||||||
|
- [ ] Create key
|
||||||
|
- [ ] Create key: validation
|
||||||
|
- [ ] Create key: name too long
|
||||||
|
- [ ] One-time reveal
|
||||||
|
- [ ] One-time reveal: copied (timer-driven, so it is checked)
|
||||||
|
- [ ] Revoke: confirm
|
||||||
|
- [ ] Revoked (list with the revoked row and the toast)
|
||||||
|
- [ ] Layout from the page component, not components.md: 36 px header, 48 px rows, 20 px status
|
||||||
|
badge; desktop modal 480 px wide 120 px from the top; mobile modal full width, bottom-aligned,
|
||||||
|
buttons stacked with Cancel under the primary; mobile card Revoke 44 px; toast 320 px wide
|
||||||
|
bottom-right on desktop and 16 px inset on mobile.
|
||||||
|
- [ ] Not drawn on the board, no visual state, Vitest only: Create sending, Create failed (500,
|
||||||
|
network, 429, 400), Revoke sending, Revoke failed, Revoke 404, "Never", the dismissal rules,
|
||||||
|
and the Integration "Manage API keys" link.
|
||||||
|
|
||||||
|
Risk: the mobile pinned "Create key" button is not on the board, and the Integration link is not
|
||||||
|
on the board's frames for the current Integration page. Either may push a mobile or Integration
|
||||||
|
capture over 10 %. Re-run `task visual:check -- integration` and the API keys screen. If either
|
||||||
|
fails, the user must decide: an approved per-state exception needs `approvedBy`, or a design
|
||||||
|
update.
|
||||||
|
|
||||||
|
Manual checks screenshots cannot cover:
|
||||||
|
- Keyboard and focus order: Tab reaches "Create key", then each "Revoke" in row order; modal focus
|
||||||
|
starts on Name, is trapped, and returns to the opener on close; the reveal's initial focus lands
|
||||||
|
on "Copy".
|
||||||
|
- Hover and motion: outline and primary button hover; modal motion; skeleton pulse stopped under
|
||||||
|
reduced motion.
|
||||||
|
|
||||||
|
## Manual verification
|
||||||
|
|
||||||
|
- Real round trip against `task dev`: create a key, copy it, run
|
||||||
|
`curl -H "Authorization: Bearer <key>" <origin>/v1/auth/me` and get 200; revoke it from the
|
||||||
|
screen and get 401; confirm the key gets 403 "This action needs a real session." on
|
||||||
|
/v1/api-key.
|
||||||
|
- Owner and admin: as owner confirm the Created by names (display name, else username); as admin
|
||||||
|
confirm only your own keys and no Created by column.
|
||||||
|
- Reset-password revocation: reset a user's password and confirm their keys show "revoked" after
|
||||||
|
reload.
|
||||||
|
- Clipboard on a real HTTPS or localhost origin.
|
||||||
|
|
||||||
|
## French strings for web/src/i18n/messages.ts
|
||||||
|
|
||||||
|
Keyed by the English text. `{0}` and `{1}` are the `t()` placeholders.
|
||||||
|
|
||||||
|
- API keys = Clés d'API
|
||||||
|
- Integration › API keys = Intégration › Clés d'API
|
||||||
|
- Create key = Créer une clé
|
||||||
|
- Name = Nom
|
||||||
|
- Key = Clé
|
||||||
|
- Status = Statut
|
||||||
|
- Created by = Créée par
|
||||||
|
- Created = Créée le
|
||||||
|
- Last used = Dernière utilisation
|
||||||
|
- Expires = Expire le
|
||||||
|
- active = active
|
||||||
|
- expired = expirée
|
||||||
|
- revoked = révoquée
|
||||||
|
- Revoke = Révoquer
|
||||||
|
- None = Aucune
|
||||||
|
- Never = Jamais
|
||||||
|
- Keys act as the user who created them. As an owner you see everyone's keys. = Les clés agissent comme l'utilisateur qui les a créées. En tant que propriétaire, vous voyez les clés de tout le monde.
|
||||||
|
- Keys act as you, with your role. You only see your own keys. = Les clés agissent en votre nom, avec votre rôle. Vous ne voyez que vos propres clés.
|
||||||
|
- Resetting a user's password revokes all of their keys. = Réinitialiser le mot de passe d'un utilisateur révoque toutes ses clés.
|
||||||
|
- No API keys yet = Aucune clé d'API pour l'instant
|
||||||
|
- Create a key to call the API from a script or service. = Créez une clé pour appeler l'API depuis un script ou un service.
|
||||||
|
- Couldn't load your API keys = Impossible de charger vos clés d'API
|
||||||
|
- Check your connection and try again. = Vérifiez votre connexion et réessayez.
|
||||||
|
- Try again = Réessayer
|
||||||
|
- Create API key = Créer une clé d'API
|
||||||
|
- The key acts as you, with your role. It is shown in full once. = La clé agit en votre nom, avec votre rôle. Elle n'est affichée en entier qu'une seule fois.
|
||||||
|
- Required. Up to 60 characters. = Obligatoire. 60 caractères maximum.
|
||||||
|
- Expiry date (optional) = Date d'expiration (facultative)
|
||||||
|
- Optional. Must be in the future. Leave it empty for a key that does not expire. = Facultative. Doit être dans le futur. Laissez vide pour une clé qui n'expire pas.
|
||||||
|
- Enter a name. = Saisissez un nom.
|
||||||
|
- Use 60 characters or fewer. = Utilisez 60 caractères ou moins.
|
||||||
|
- Choose a date in the future. = Choisissez une date dans le futur.
|
||||||
|
- Cancel = Annuler
|
||||||
|
- Your new API key = Votre nouvelle clé d'API
|
||||||
|
- "{0}" is ready. Copy the key and store it somewhere safe. = « {0} » est prête. Copiez la clé et conservez-la en lieu sûr.
|
||||||
|
- You won't be able to see this key again. = Vous ne pourrez plus revoir cette clé.
|
||||||
|
- Copy = Copier
|
||||||
|
- Copied = Copié
|
||||||
|
- Closing this window discards the key from the screen. Copy it first. = Fermer cette fenêtre supprime la clé de l'écran. Copiez-la d'abord.
|
||||||
|
- Done = Terminé
|
||||||
|
- Revoke this key? = Révoquer cette clé ?
|
||||||
|
- "{0}" ({1}) will stop working right away. Requests that use it answer 401. This can't be undone. = « {0} » ({1}) cessera de fonctionner immédiatement. Les requêtes qui l'utilisent recevront une réponse 401. Cette action est irréversible.
|
||||||
|
- Keep key = Garder la clé
|
||||||
|
- Revoke key = Révoquer la clé
|
||||||
|
- Key revoked = Clé révoquée
|
||||||
|
- "{0}" can no longer be used. = « {0} » ne peut plus être utilisée.
|
||||||
|
- Creating… = Création…
|
||||||
|
- Revoking… = Révocation…
|
||||||
|
- Couldn't create the key. Try again in a moment. = Impossible de créer la clé. Réessayez dans un instant.
|
||||||
|
- Couldn't reach RenewCMS. Check your connection and try again. = Impossible de joindre RenewCMS. Vérifiez votre connexion et réessayez.
|
||||||
|
- Too many requests. Wait a moment, then try again. = Trop de requêtes. Patientez un instant, puis réessayez.
|
||||||
|
- Something in the form isn't valid. Check the highlighted fields. = Un élément du formulaire n'est pas valide. Vérifiez les champs signalés.
|
||||||
|
- Couldn't revoke the key. Try again in a moment. = Impossible de révoquer la clé. Réessayez dans un instant.
|
||||||
|
- That key no longer exists. = Cette clé n'existe plus.
|
||||||
|
- Manage API keys = Gérer les clés d'API
|
||||||
@@ -0,0 +1,229 @@
|
|||||||
|
Feature: Article body content negotiation on read
|
||||||
|
|
||||||
|
As a headless frontend developer
|
||||||
|
I want article routes to return the body as markdown (default), html or a typed json block array
|
||||||
|
So that my client can render it without handling editor HTML
|
||||||
|
|
||||||
|
Background:
|
||||||
|
Given article bodies are stored as Tiptap HTML
|
||||||
|
And storage, the POST /v1/article body and the PATCH /v1/article/{id} body stay HTML and are unchanged
|
||||||
|
And internal/domain/article defines BodyFormat with the values "markdown", "html" and "json"
|
||||||
|
And internal/domain/article defines the port BodyRenderer and the sentinel ErrUnsupportedBodyFormat
|
||||||
|
And ParseBodyFormat matches case-insensitively, treats an empty value as "markdown", and returns ErrUnsupportedBodyFormat otherwise
|
||||||
|
And the use cases receive the BodyRenderer through their constructors, the handler only reads the "format" query value, and only api/dependecyInjection.go builds the converter
|
||||||
|
And every article object in a response has the snake_case fields id, title, body, body_format, is_online, created_at, updated_at
|
||||||
|
And body_format is "markdown", "html" or "json" and always names the format of body
|
||||||
|
And for markdown and html, body is a JSON string; for json, body is a JSON array of blocks (not an escaped string)
|
||||||
|
And the covered routes are GET /v1/article/, GET /v1/article/{id}, POST /v1/article/, PATCH /v1/article/{id}, PATCH /v1/article/{id}/publish and PATCH /v1/article/{id}/unpublish
|
||||||
|
And visibility is unchanged: anonymous and unverified callers see only online articles, and an offline article reads as 404 "Article not found"
|
||||||
|
And an unsupported format answers 400 with apperr.ArticleBodyFormatErrorMessage as plain text, before any article lookup or write
|
||||||
|
And an invalid id answers apperr.IdUint32ErrorMessage first, ahead of the format check
|
||||||
|
And a repeated "format" parameter uses its first value
|
||||||
|
And a renderer failure answers 500 "Internal server error"
|
||||||
|
And article 1 is online, titled "Backyard Renovation Update", with body "<h2>Plan</h2><p>Replace the <strong>old</strong> deck.</p>"
|
||||||
|
|
||||||
|
Scenario Outline: Single read negotiates the body format
|
||||||
|
When an anonymous client sends GET /v1/article/1<query>
|
||||||
|
Then the response status is 200
|
||||||
|
And "body" is <body>
|
||||||
|
And "body_format" is "<body_format>"
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| query | body | body_format |
|
||||||
|
| | "## Plan\n\nReplace the **old** deck." | markdown |
|
||||||
|
| ?format= | "## Plan\n\nReplace the **old** deck." | markdown |
|
||||||
|
| ?format=markdown | "## Plan\n\nReplace the **old** deck." | markdown |
|
||||||
|
| ?format=MarkDown | "## Plan\n\nReplace the **old** deck." | markdown |
|
||||||
|
| ?format=html | "<h2>Plan</h2><p>Replace the <strong>old</strong> deck.</p>" | html |
|
||||||
|
| ?format=HTML | "<h2>Plan</h2><p>Replace the <strong>old</strong> deck.</p>" | html |
|
||||||
|
| ?format=json | [{"type":"heading","level":2,"children":[{"type":"text","text":"Plan","marks":[]}]},{"type":"paragraph","children":[{"type":"text","text":"Replace the ","marks":[]},{"type":"text","text":"old","marks":[{"type":"bold"}]},{"type":"text","text":" deck.","marks":[]}]}] | json |
|
||||||
|
| ?format=JSON | the same array as ?format=json | json |
|
||||||
|
|
||||||
|
Scenario: List read negotiates every element
|
||||||
|
Given the repository also holds online article 3 with body "<p>Second</p>"
|
||||||
|
When an anonymous client sends GET /v1/article/
|
||||||
|
Then every element has body_format "markdown" and article 3 has body "Second"
|
||||||
|
When an anonymous client sends GET /v1/article/?format=html
|
||||||
|
Then every element has body_format "html" and its stored HTML as body
|
||||||
|
When an anonymous client sends GET /v1/article/?format=json
|
||||||
|
Then every element has body_format "json" and article 3 has body [{"type":"paragraph","children":[{"type":"text","text":"Second","marks":[]}]}]
|
||||||
|
|
||||||
|
Scenario Outline: An unsupported format is rejected
|
||||||
|
When an anonymous client sends GET <path>
|
||||||
|
Then the response status is 400
|
||||||
|
And the response body is apperr.ArticleBodyFormatErrorMessage followed by a newline
|
||||||
|
And no use case reads or renders an article
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| path |
|
||||||
|
| /v1/article/1?format=pdf |
|
||||||
|
| /v1/article/?format=xml |
|
||||||
|
| /v1/article/9999?format=pdf |
|
||||||
|
| /v1/article/1?format=md |
|
||||||
|
|
||||||
|
Scenario: An invalid id is reported before an invalid format
|
||||||
|
When an anonymous client sends GET /v1/article/abc?format=pdf
|
||||||
|
Then the response status is 400
|
||||||
|
And the response body is apperr.IdUint32ErrorMessage followed by a newline
|
||||||
|
|
||||||
|
Scenario: The first repeated format parameter wins
|
||||||
|
When an anonymous client sends GET /v1/article/1?format=html&format=json
|
||||||
|
Then "body_format" is "html"
|
||||||
|
|
||||||
|
Scenario: Offline articles stay hidden whatever the format
|
||||||
|
Given article 2 is offline
|
||||||
|
When an anonymous client sends GET /v1/article/2?format=json
|
||||||
|
Then the response status is 404 and the body is "Article not found"
|
||||||
|
|
||||||
|
Scenario Outline: Authenticated routes negotiate the response body
|
||||||
|
Given a valid jwt cookie for a verified user with id 1
|
||||||
|
When the client sends <method> <path> with <request_body>
|
||||||
|
Then the response status is <status>
|
||||||
|
And "body_format" is "<body_format>"
|
||||||
|
And the stored body is the HTML that was sent, never markdown or json
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| method | path | request_body | status | body_format |
|
||||||
|
| POST | /v1/article/ | {"title":"Deck","body":"<p>A</p>"} | 201 | markdown |
|
||||||
|
| POST | /v1/article/?format=html | {"title":"Deck","body":"<p>A</p>"} | 201 | html |
|
||||||
|
| POST | /v1/article/?format=json | {"title":"Deck","body":"<p>A</p>"} | 201 | json |
|
||||||
|
| PATCH | /v1/article/1 | {"body":"<p>B</p>"} | 200 | markdown |
|
||||||
|
| PATCH | /v1/article/1?format=json | {"body":"<p>B</p>"} | 200 | json |
|
||||||
|
| PATCH | /v1/article/1/publish | | 200 | markdown |
|
||||||
|
| PATCH | /v1/article/1/unpublish?format=html | | 200 | html |
|
||||||
|
|
||||||
|
Scenario: An unsupported format on a write route changes nothing
|
||||||
|
Given a valid jwt cookie for a verified user with id 1
|
||||||
|
When the client sends PATCH /v1/article/1?format=pdf with {"body":"<p>B</p>"}
|
||||||
|
Then the response status is 400
|
||||||
|
And the stored body of article 1 is unchanged
|
||||||
|
When the client sends POST /v1/article/?format=pdf with {"title":"Deck","body":"<p>A</p>"}
|
||||||
|
Then the response status is 400 and no article is created
|
||||||
|
|
||||||
|
Scenario: The authenticated list includes offline articles in the negotiated format
|
||||||
|
Given a valid jwt cookie for a verified user and offline article 2
|
||||||
|
When the client sends GET /v1/article/?format=json
|
||||||
|
Then the array contains articles 1 and 2 with body_format "json"
|
||||||
|
|
||||||
|
Scenario: A converter failure answers 500
|
||||||
|
Given the BodyRenderer fails on its next call
|
||||||
|
When an anonymous client sends GET /v1/article/1
|
||||||
|
Then the response status is 500 and the body is "Internal server error"
|
||||||
|
|
||||||
|
Scenario Outline: Markdown fidelity for Tiptap output
|
||||||
|
Given the stored body is <html>
|
||||||
|
When converted with the format "markdown"
|
||||||
|
Then the body is <markdown>
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| html | markdown |
|
||||||
|
| <h1>T</h1><h3>S</h3> | # T\n\n### S |
|
||||||
|
| <p><strong>b</strong> <em>i</em></p> | **b** *i* |
|
||||||
|
| <p><a href="https://example.com/x">link</a></p> | [link](https://example.com/x) |
|
||||||
|
| <ul><li><p>a</p></li><li><p>b</p></li></ul> | - a\n- b |
|
||||||
|
| <ol><li><p>a</p></li><li><p>b</p></li></ol> | 1. a\n2. b |
|
||||||
|
| <ul><li data-indent="2"><p>a</p></li></ul> | - a |
|
||||||
|
| <blockquote><p>q</p></blockquote> | > q |
|
||||||
|
| <pre><code class="language-go">x := 1</code></pre> | ```go\nx := 1\n``` |
|
||||||
|
| <hr> | --- |
|
||||||
|
| <img src="/static/uploadedImages/a.png" alt="A"> |  |
|
||||||
|
| <p>ok</p><script>alert(1)</script><style>p{}</style> | ok |
|
||||||
|
| <p>x<span style="color:red">y</span></p> | xy |
|
||||||
|
| <p>use <code>go test</code></p> | use `go test` |
|
||||||
|
|
||||||
|
Scenario Outline: Json block shapes, one row per block and mark type
|
||||||
|
Given the stored body is <html>
|
||||||
|
When converted with the format "json"
|
||||||
|
Then the body is <json>
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| html | json |
|
||||||
|
| <h1>T</h1> | [{"type":"heading","level":1,"children":[{"type":"text","text":"T","marks":[]}]}] |
|
||||||
|
| <h6>S</h6> | [{"type":"heading","level":6,"children":[{"type":"text","text":"S","marks":[]}]}] |
|
||||||
|
| <p>plain</p> | [{"type":"paragraph","children":[{"type":"text","text":"plain","marks":[]}]}] |
|
||||||
|
| <p></p> | [{"type":"paragraph","children":[]}] |
|
||||||
|
| <p><strong>b</strong></p> | [{"type":"paragraph","children":[{"type":"text","text":"b","marks":[{"type":"bold"}]}]}] |
|
||||||
|
| <p><em>i</em></p> | [{"type":"paragraph","children":[{"type":"text","text":"i","marks":[{"type":"italic"}]}]}] |
|
||||||
|
| <p><a href="https://example.com/x">l</a></p> | [{"type":"paragraph","children":[{"type":"text","text":"l","marks":[{"type":"link","href":"https://example.com/x"}]}]}] |
|
||||||
|
| <p><a href="/a"><strong><em>x</em></strong></a></p> | [{"type":"paragraph","children":[{"type":"text","text":"x","marks":[{"type":"link","href":"/a"},{"type":"bold"},{"type":"italic"}]}]}] |
|
||||||
|
| <p>a<br>b</p> | [{"type":"paragraph","children":[{"type":"text","text":"a\nb","marks":[]}]}] |
|
||||||
|
| <ul><li><p>a</p></li><li><p>b</p></li></ul> | [{"type":"list","ordered":false,"items":[[{"type":"paragraph","children":[{"type":"text","text":"a","marks":[]}]}],[{"type":"paragraph","children":[{"type":"text","text":"b","marks":[]}]}]]}] |
|
||||||
|
| <ol><li><p>a</p></li></ol> | [{"type":"list","ordered":true,"items":[[{"type":"paragraph","children":[{"type":"text","text":"a","marks":[]}]}]]}] |
|
||||||
|
| <ul><li>bare</li></ul> | [{"type":"list","ordered":false,"items":[[{"type":"paragraph","children":[{"type":"text","text":"bare","marks":[]}]}]]}] |
|
||||||
|
| <ul><li><p>a</p><ul><li><p>n</p></li></ul></li></ul> | a list item whose blocks are the paragraph "a" followed by a nested list block with ordered false and the item "n" |
|
||||||
|
| <ul><li data-indent="2"><p>a</p></li></ul> | the same output as without data-indent |
|
||||||
|
| <blockquote><p>q</p></blockquote> | [{"type":"blockquote","children":[{"type":"paragraph","children":[{"type":"text","text":"q","marks":[]}]}]}] |
|
||||||
|
| <pre><code class="language-go">x := 1</code></pre> | [{"type":"code","language":"go","text":"x := 1"}] |
|
||||||
|
| <pre><code>raw</code></pre> | [{"type":"code","language":"","text":"raw"}] |
|
||||||
|
| <hr> | [{"type":"hr"}] |
|
||||||
|
| <img src="/static/uploadedImages/a.png" alt="A"> | [{"type":"image","src":"/static/uploadedImages/a.png","alt":"A"}] |
|
||||||
|
| <img src="/static/uploadedImages/a.png"> | [{"type":"image","src":"/static/uploadedImages/a.png","alt":""}] |
|
||||||
|
| <p>x<img src="/i.png" alt="I">y</p> | [{"type":"paragraph","children":[{"type":"text","text":"x","marks":[]}]},{"type":"image","src":"/i.png","alt":"I"},{"type":"paragraph","children":[{"type":"text","text":"y","marks":[]}]}] |
|
||||||
|
| <p>x<span style="color:red">y</span></p> | [{"type":"paragraph","children":[{"type":"text","text":"xy","marks":[]}]}] |
|
||||||
|
| <p>use <code>go test</code></p> | [{"type":"paragraph","children":[{"type":"text","text":"use go test","marks":[]}]}] |
|
||||||
|
| <p>ok</p><script>alert(1)</script><style>p{}</style> | [{"type":"paragraph","children":[{"type":"text","text":"ok","marks":[]}]}] |
|
||||||
|
|
||||||
|
Scenario Outline: Text alignment survives the conversion
|
||||||
|
Given the stored body is <html>
|
||||||
|
When converted with the format "markdown"
|
||||||
|
Then the body is <markdown>
|
||||||
|
When converted with the format "json"
|
||||||
|
Then the body is <json>
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| html | markdown | json |
|
||||||
|
| <p style="text-align: center">a</p> | <div style="text-align: center">
|
||||||
|
|
||||||
|
a
|
||||||
|
|
||||||
|
</div> | [{"type":"paragraph","align":"center","children":[{"type":"text","text":"a","marks":[]}]}] |
|
||||||
|
| <h2 style="text-align:right">T</h2> | <div style="text-align: right">
|
||||||
|
|
||||||
|
## T
|
||||||
|
|
||||||
|
</div> | [{"type":"heading","level":2,"align":"right","children":[{"type":"text","text":"T","marks":[]}]}] |
|
||||||
|
| <p style="text-align: JUSTIFY">a</p> | <div style="text-align: justify">
|
||||||
|
|
||||||
|
a
|
||||||
|
|
||||||
|
</div> | [{"type":"paragraph","align":"justify","children":[{"type":"text","text":"a","marks":[]}]}] |
|
||||||
|
| <p style="text-align: left">a</p> | a | [{"type":"paragraph","children":[{"type":"text","text":"a","marks":[]}]}] |
|
||||||
|
| <p style="text-align: start">a</p> | a | the same output as the left row |
|
||||||
|
| <p style="text-align: center"></p> | an empty string | [{"type":"paragraph","align":"center","children":[]}] |
|
||||||
|
|
||||||
|
Scenario Outline: Plain text that looks like markdown stays plain text
|
||||||
|
Given the stored body is <html>
|
||||||
|
When converted with the format "markdown"
|
||||||
|
Then the body is <markdown>
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| html | markdown |
|
||||||
|
| <p># not a heading</p> | \# not a heading |
|
||||||
|
| <p>#tag</p> | #tag |
|
||||||
|
| <p>- not a list</p> | \- not a list |
|
||||||
|
| <p>+ not a list</p> | \+ not a list |
|
||||||
|
| <p>> not a quote</p> | \> not a quote |
|
||||||
|
| <p>1. not a list</p> | 1\. not a list |
|
||||||
|
| <p>2) not a list</p> | 2\) not a list |
|
||||||
|
| <p>---</p> | \--- |
|
||||||
|
| <p>a - b</p> | a - b |
|
||||||
|
| <p>a * b _c_</p> | a \* b \_c\_ |
|
||||||
|
| <p>a<br>- b</p> | a\n\- b |
|
||||||
|
|
||||||
|
Scenario: The editor lets the author align text
|
||||||
|
Given the article editor registers the TextAlign extension for paragraphs and headings
|
||||||
|
Then the left, center, right and justify toolbar buttons are enabled
|
||||||
|
And clicking center writes style="text-align: center;" on the current paragraph or heading
|
||||||
|
And paragraphs and headings that were never aligned carry no style attribute
|
||||||
|
|
||||||
|
Scenario: The SPA asks for html explicitly
|
||||||
|
Given no visual change is expected, so docs/design is not consulted
|
||||||
|
When EditorView loads an article, or ArticleView or HomeView load the list
|
||||||
|
Then each request is /v1/article/{id}?format=html or /v1/article/?format=html
|
||||||
|
And the draft save PATCH, the publish and unpublish PATCH and the create POST also carry ?format=html, so a converter failure cannot fail a save
|
||||||
|
And the editor and the image counts receive HTML exactly as before
|
||||||
|
|
||||||
|
Scenario: The documentation reflects the contract
|
||||||
|
Then docs/api has an article read page covering format, the markdown default, body_format, the json block schema, the 400 message and the breaking default change
|
||||||
|
And web/src/views/IntegrationView.vue snippets show ?format
|
||||||
|
And docs/releases has a note stating the default flip and that the SPA sends format=html
|
||||||
@@ -0,0 +1,46 @@
|
|||||||
|
# QA procedure: article_body_format
|
||||||
|
|
||||||
|
Package: `test` (black-box). New files: `test/article_body_format_test.go`, `test/markdown_converter_test.go`, `test/json_blocks_converter_test.go`. No live server, no real SQLite file, no real SMTP.
|
||||||
|
|
||||||
|
## Setup
|
||||||
|
1. Call `validator.InitValidator()` once.
|
||||||
|
2. Reuse `mockArticleRepo` and `mockUserRepo`. Add a fake `fakeBodyRenderer` with a unique type name. It records each call's format and the html it received. For markdown it returns "MD:"+html. For html it returns the html unchanged. For json it returns `[{"type":"paragraph","children":[{"type":"text","text":"FAKE","marks":[]}]}]`. It has a failure switch.
|
||||||
|
3. Wire the real use cases over the fakes, passing the renderer. Update every existing test that builds these use cases for the new constructor signatures. Build `article.NewHandler(...)`.
|
||||||
|
4. Mount a fresh `chi.NewRouter()` mirroring `api/router.go` for `/v1/article`: `jwtauth.Verifier` on the group, GET `/` and `/{id}` public, and `Authenticator` + `RequireCurrentToken` + `RequireVerifiedUser` for POST, DELETE and PATCH.
|
||||||
|
5. Mint a jwt cookie for user_id 1 with `token.Encode(map[string]any{"user_id": uint32(1)})`. Seed a verified user. Seed articles 1 (online) and 2 (offline).
|
||||||
|
|
||||||
|
## HTTP checks (fake renderer)
|
||||||
|
6. Single read matrix: for each of none, `?format=`, markdown, MarkDown, html, HTML, json, JSON, assert status 200, `body_format`, the renderer's recorded format and the stored HTML passed in. For json, decode `body` and assert it is a JSON array (not a string).
|
||||||
|
7. List with none, `?format=html` and `?format=json`: every element has the matching `body_format`.
|
||||||
|
8. `format=pdf`, `xml` and `md` on single, list and unknown-id paths return 400 with `apperr.ArticleBodyFormatErrorMessage + "\n"`. The renderer and the repo are not called.
|
||||||
|
9. `GET /v1/article/abc?format=pdf` returns 400 with `apperr.IdUint32ErrorMessage + "\n"`.
|
||||||
|
10. `?format=html&format=json` returns html.
|
||||||
|
11. `GET /v1/article/2?format=json` anonymous returns 404 `"Article not found\n"`.
|
||||||
|
12. Write-route matrix with a cookie (POST, PATCH, publish, unpublish, each with none, html and json where listed): assert status, `body_format`, and that the repo holds the HTML that was sent.
|
||||||
|
13. `PATCH /v1/article/1?format=pdf` and `POST /v1/article/?format=pdf` with a cookie return 400. The repo is unchanged and no article is created.
|
||||||
|
14. Authenticated `GET /v1/article/?format=json` includes articles 1 and 2.
|
||||||
|
15. Renderer failure switch, then `GET /v1/article/1` returns 500 `"Internal server error\n"`.
|
||||||
|
|
||||||
|
## Domain
|
||||||
|
16. `ParseBodyFormat`: "", markdown, MARKDOWN, html, Html, json, JSON are accepted (empty returns markdown). pdf, md and " html" return `errors.Is(err, ErrUnsupportedBodyFormat)`.
|
||||||
|
|
||||||
|
## Converter tests (real library, real Tiptap HTML samples)
|
||||||
|
17. `test/markdown_converter_test.go`: every row of the markdown fidelity table, plus a combined document (heading, paragraph with marks, list, image, code block, quote, hr). Assert exact output. For format html, assert the input comes back byte-identical.
|
||||||
|
17b. Alignment and escaping: every row of the alignment and plain-text tables, for markdown and json, in `test/markdown_converter_test.go` and `test/json_blocks_converter_test.go`. `test/body_converter_documents_test.go` covers the combined hostile document (no raw script, style, iframe or span leaks in markdown or json), its block types, and code block text extraction.
|
||||||
|
18. `test/json_blocks_converter_test.go`: every row of the json shapes table. Assert by unmarshalling both sides and comparing with deep equality. This also asserts `marks` is `[]` rather than null or absent, `ordered` is a bool, and code `language` is "" when absent. Also include a combined document with nested list, blockquote and an image inside a paragraph. Assert that script and style content never appears, and that no raw HTML survives in any output for any format except html.
|
||||||
|
19. `test/json_blocks_converter_test.go` also asserts that html "" produces `[]`, and that the output is a non-null JSON array.
|
||||||
|
|
||||||
|
## SPA (Vitest, `task test:web`)
|
||||||
|
20. Mock `/v1/article/12?format=html` and assert `EditorView` requests that URL and loads the HTML body into the draft.
|
||||||
|
21. Assert `useArticles.listArticles` requests `/v1/article/?format=html`.
|
||||||
|
22. Assert the `ArticleView` image count is computed from the HTML.
|
||||||
|
23. Assert `useArticleDraft.save` sends PATCH `/v1/article/{id}?format=html` with the JSON body.
|
||||||
|
24. Reported as NOT RUN if there is no runner. No visual check applies, because no visual change is expected.
|
||||||
|
|
||||||
|
## Docs
|
||||||
|
25. Check that a docs/api article read page, the IntegrationView snippets and a docs/releases note exist as described.
|
||||||
|
|
||||||
|
## Manual verification
|
||||||
|
- In the embedded SPA, edit and save an article against a real SQLite file and confirm the stored body is still HTML.
|
||||||
|
- `curl` the public list and a single article with no format, `?format=html` and `?format=json` against a built binary.
|
||||||
|
- No SMTP involvement.
|
||||||
@@ -59,9 +59,9 @@ Feature: Articles list screen
|
|||||||
remaining articles, and raises an info toast (icon info, id "article-not-found-{id}"): title
|
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
|
"That article no longer exists" text "It was deleted somewhere else, so we removed it from
|
||||||
the list."
|
the list."
|
||||||
And "Delete…" opens ConfirmDialog: title "Delete this article?" text "\"{title}\" and its
|
And "Delete…" opens ConfirmDialog: title "Delete this article?" text "\"{title}\" will be
|
||||||
{n} images will be deleted. This can't be undone." (a components.md convention: the row's
|
deleted. Its images stay in your library. This can't be undone." (the second sentence is
|
||||||
title plus its image count, "and its image" for exactly 1 and no image clause at all for 0),
|
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
|
"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
|
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
|
confirm button reads "Deleting…" with a loading indicator, and aria-busy is set
|
||||||
@@ -72,7 +72,7 @@ Feature: Articles list screen
|
|||||||
And a successful delete (204) closes the dialog, removes the row, moves focus to the next row
|
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
|
(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
|
success toast (icon circle-check, id "article-deleted-{id}"): title "Article deleted" text
|
||||||
"\"{title}\" and its images are gone."; this is also where a delete initiated from the editor
|
"\"{title}\" is gone."; this is also where a delete initiated from the editor
|
||||||
ends up
|
ends up
|
||||||
And the list, sorted by last updated with the most recently updated article first, holds
|
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
|
these 6 articles by default: id 1 "How we price a bathroom renovation" (online, updated "2
|
||||||
@@ -231,7 +231,7 @@ Feature: Articles list screen
|
|||||||
Given the Default state has loaded, and id 4 "Winter checklist for timber windows" has 3 images
|
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
|
When the user chooses "Delete…" from id 4's row menu
|
||||||
Then ConfirmDialog opens: title "Delete this article?" text "\"Winter checklist for timber
|
Then ConfirmDialog opens: 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
|
windows\" will be deleted. Its images stay in your library. This can't be undone.", "Cancel" and "Delete
|
||||||
article" (danger)
|
article" (danger)
|
||||||
|
|
||||||
Scenario: Delete in progress — the dialog cannot be dismissed while the request is in flight
|
Scenario: Delete in progress — the dialog cannot be dismissed while the request is in flight
|
||||||
@@ -256,4 +256,4 @@ Feature: Articles list screen
|
|||||||
Then the dialog closes, id 4's row is removed from the list, and focus moves to the next row
|
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 the tabs read "All 5" "Online 4" "Drafts 1"
|
||||||
And a success toast appears: icon circle-check, id "article-deleted-4", title "Article
|
And a success toast appears: icon circle-check, id "article-deleted-4", title "Article
|
||||||
deleted", text "\"Winter checklist for timber windows\" and its images are gone."
|
deleted", text "\"Winter checklist for timber windows\" is gone."
|
||||||
@@ -114,7 +114,7 @@ as listed), unless a scenario's Examples row substitutes a smaller fixture.
|
|||||||
18. **Deleted** — continuing from 16 (a fresh attempt), resolve the DELETE 204; assert 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
|
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
|
4" "Drafts 1"; assert a toast with id "article-deleted-4", icon circle-check, title "Article
|
||||||
deleted", text "\"Winter checklist for timber windows\" and its images are gone."
|
deleted", text "\"Winter checklist for timber windows\" is gone."
|
||||||
|
|
||||||
## Visual (manual verification — desktop and mobile, light and dark)
|
## Visual (manual verification — desktop and mobile, light and dark)
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,87 @@
|
|||||||
|
Feature: Container-aware update guidance
|
||||||
|
|
||||||
|
As the owner of a RenewCMS site running in Docker
|
||||||
|
I want Settings to say "update by pulling a new image" instead of "Not prepared"
|
||||||
|
So that I never see a browser-update flow that cannot work in a container
|
||||||
|
|
||||||
|
Background:
|
||||||
|
Given browser updates need Linux with systemd and the helper that "renewcms enable-browser-updates" configures
|
||||||
|
And a binary replaced inside a container is lost when the container is recreated,
|
||||||
|
so in a container the update is a new image: "docker compose pull && docker compose up -d"
|
||||||
|
And config.Settings gains Container bool, read from the env var RENEWCMS_CONTAINER (default "false", set to "true" by the Dockerfile and docker-compose.yml)
|
||||||
|
And RENEWCMS_CONTAINER is added to envDefaults in cmd/server/main.go, to .env.example and to docs/configuration.md; it is not in requiredEnvVars
|
||||||
|
And only "true" (case-insensitive) enables container mode; any other value means false
|
||||||
|
And the update status use case receives the bool through its constructor from api/dependecyInjection.go; internal/domain/update stays stdlib only
|
||||||
|
And the update check, update-status.json and the release feed work unchanged in container mode
|
||||||
|
And GET /v1/system/update gains a 13th key, container (bool), after started_at; the other 12 keys are unchanged
|
||||||
|
And in container mode can_apply is false for everyone, even if update-helper.json exists in the data directory
|
||||||
|
And POST /v1/system/update/download and /restart keep their guards and answer 409 because can_apply is false (existing behaviour, not re-specified)
|
||||||
|
And errors stay plain text from http.Error
|
||||||
|
And the user approved the copy below and the 13th key on 2026-10-05; docs/design is read-only for agents, so the design files are updated by the user, and the visual gate for container states stays PENDING until a board frame exists
|
||||||
|
|
||||||
|
Scenario Outline: The status carries the container flag
|
||||||
|
Given RENEWCMS_CONTAINER is "<value>"
|
||||||
|
When a verified user sends GET /v1/system/update
|
||||||
|
Then the JSON key container is <flag>
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| value | flag |
|
||||||
|
| true | true |
|
||||||
|
| TRUE | true |
|
||||||
|
| false | false |
|
||||||
|
| | false |
|
||||||
|
| yes | false |
|
||||||
|
|
||||||
|
Scenario: Container mode disables apply even with a helper
|
||||||
|
Given RENEWCMS_CONTAINER is "true" and HelperDetector reports the helper installed
|
||||||
|
When the owner sends GET /v1/system/update
|
||||||
|
Then can_apply is false and container is true
|
||||||
|
And a newer stored result still reports available true, latest and notes
|
||||||
|
|
||||||
|
Scenario: The check still works in a container
|
||||||
|
Given container mode and a feed that reports "v2.9.0-beta" newer than the running "v2.8.0-beta"
|
||||||
|
When the owner sends POST /v1/system/update/check
|
||||||
|
Then the status is 200 and available is true and the result is stored in update-status.json
|
||||||
|
|
||||||
|
Scenario Outline: Download and restart are refused in a container
|
||||||
|
Given container mode and a stored newer release
|
||||||
|
When the owner sends POST <path>
|
||||||
|
Then the status is 409 and no job starts and the fetcher and the restart request writer are not called
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| path |
|
||||||
|
| /v1/system/update/download |
|
||||||
|
| /v1/system/update/restart |
|
||||||
|
|
||||||
|
Scenario: Host installs are unchanged
|
||||||
|
Given RENEWCMS_CONTAINER is unset
|
||||||
|
Then container is false and can_apply follows the helper as before
|
||||||
|
And "Not prepared" still shows its "renewcms enable-browser-updates" command
|
||||||
|
|
||||||
|
Scenario: Settings, owner, container, update available (route /settings)
|
||||||
|
Given GET /v1/system/update resolves available true, container true, can_apply false, latest "v2.9.0-beta"
|
||||||
|
Then the block uses the "Not prepared" frame's layout: icon info, tone info
|
||||||
|
And the title reads "Version 2.9.0-beta is available"
|
||||||
|
And the text reads "You have v2.8.0-beta. This site runs in Docker, so it updates by pulling a new image. Run the commands below on the server."
|
||||||
|
And a server-command block reads "docker compose pull && docker compose up -d" with the Copy button ("Copied" with a check for 2 s, announced)
|
||||||
|
And a link "How to update" with arrow-up-right points to docs/docker.md
|
||||||
|
And no Update, Restart or "Check for updates" button is rendered
|
||||||
|
And the "renewcms enable-browser-updates" command and its note are not rendered
|
||||||
|
|
||||||
|
Scenario: Settings, owner, container, up to date
|
||||||
|
Given container true and available false
|
||||||
|
Then "You're up to date" shows as in the existing Up to date state, the Restart button is not rendered and the container hint is not rendered
|
||||||
|
And "Check for updates" is still offered
|
||||||
|
|
||||||
|
Scenario: Settings, admin, container
|
||||||
|
Given the session role is "admin", container true and available true
|
||||||
|
Then the existing Admin view shows unchanged ("Only the owner can update RenewCMS.") with no command block
|
||||||
|
|
||||||
|
Scenario: Settings, non-container, no helper
|
||||||
|
Given container false and can_apply false
|
||||||
|
Then the existing "Not prepared" state shows unchanged
|
||||||
|
|
||||||
|
Scenario: The shipped Docker setup turns container mode on
|
||||||
|
Given the Dockerfile and docker-compose.yml
|
||||||
|
Then both set RENEWCMS_CONTAINER=true
|
||||||
|
And docs/docker.md and docs/configuration.md describe the variable
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
# QA: Container update guidance
|
||||||
|
|
||||||
|
## Automated (Go, test/, httptest)
|
||||||
|
1. Fakes: in-memory update status store, fake FeedClient, fake HelperDetector, fake JobStore and restart writer, validator.InitValidator(). Mount NewSystemRouter on a fresh chi.NewRouter() with jwtauth.Verifier + Authenticator and a test jwtauth.New("HS256", ...).
|
||||||
|
2. Parse RENEWCMS_CONTAINER through config.NewSettingsFromEnv with t.Setenv over the table in the feature (true, TRUE, false, empty, yes).
|
||||||
|
3. GET status: container key present and equal to the table; the other 12 keys are unchanged.
|
||||||
|
4. Container true with a helper present: can_apply false for the owner.
|
||||||
|
5. POST check in container mode: 200, available true, stored.
|
||||||
|
6. POST download and restart in container mode: 409, no fake called.
|
||||||
|
7. Container false: the existing updates_* tests still pass.
|
||||||
|
8. An admin receives can_apply false and container true.
|
||||||
|
|
||||||
|
## SPA (Vitest, mocked /v1)
|
||||||
|
- Container + available: the block, command, Copy, "How to update", and no buttons. Reuse the "Not prepared" sample data from the board.
|
||||||
|
- Container + up to date: no Restart.
|
||||||
|
- Admin: the existing admin view.
|
||||||
|
- Non-container "Not prepared": unchanged.
|
||||||
|
- Visual: container states are PENDING until a board frame exists; report as PENDING, never as passing. Existing states must still pass `task visual:check -- settings`.
|
||||||
|
|
||||||
|
## Manual (real Docker, ./docker-compose.yml)
|
||||||
|
1. `docker compose up -d --build`; confirm RENEWCMS_CONTAINER=true with `docker compose exec renewcms env`.
|
||||||
|
2. Point UPDATE_FEED_URL at a feed with a newer release; log in as owner; /settings shows the container block, no Update or Restart.
|
||||||
|
3. The Copy button puts the exact command on the clipboard.
|
||||||
|
4. Run the shown command on a host that has a newer image; Settings shows the new version afterwards.
|
||||||
|
5. Run the binary on the host without the variable: "Not prepared" shows the old command.
|
||||||
@@ -17,7 +17,7 @@ Feature: DashboardShell wordmark, sidebar collapse and the UserMenu
|
|||||||
AuthShell uses) followed by the "RenewCMS" wordmark text, not the plain
|
AuthShell uses) followed by the "RenewCMS" wordmark text, not the plain
|
||||||
<span class="font-semibold">RenewCMS</span> the shell renders today
|
<span class="font-semibold">RenewCMS</span> the shell renders today
|
||||||
And the sidebar's #default slot is a UNavigationMenu orientation="vertical" :collapsed bound
|
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 and Integration, in that order
|
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
|
And the sidebar's #footer slot renders a UserMenu component, not the plain
|
||||||
<span>Log out</span> text the shell renders today
|
<span>Log out</span> text the shell renders today
|
||||||
And UserMenu is the account menu specified in features/profile_page.feature, anchored to a
|
And UserMenu is the account menu specified in features/profile_page.feature, anchored to a
|
||||||
|
|||||||
@@ -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.
|
||||||
@@ -0,0 +1,45 @@
|
|||||||
|
Feature: Docker deployment
|
||||||
|
RenewCMS can run in a container built from the repository. The container
|
||||||
|
reuses the existing configuration contract in cmd/server/main.go
|
||||||
|
(requiredEnvVars, envDefaults); no new variables are introduced.
|
||||||
|
|
||||||
|
Background:
|
||||||
|
Given the image is built with the default build, without the nofrontend tag
|
||||||
|
And the container runs the binary directly as PID 1 under a non-root user
|
||||||
|
And the environment sets DB_FILE and UPLOAD_DIR to paths on a named volume
|
||||||
|
And the required variables PUBLIC_URL, JWT_SECRET, SMTP_LOGIN, SMTP_SENDER, SMTP_PASSWORD, SMTP_HOST and SMTP_PORT come from an env file at runtime
|
||||||
|
|
||||||
|
Scenario: Healthy start
|
||||||
|
When the container starts with every required variable set
|
||||||
|
Then it logs "RenewCMS <version> (production) listening on :8080"
|
||||||
|
And GET /healthz on the published port returns 200 with the body "ok"
|
||||||
|
|
||||||
|
Scenario: Frontend and API are both served
|
||||||
|
When the container is running
|
||||||
|
Then GET / returns 200 with the SPA index.html
|
||||||
|
And GET /v1/auth/registration returns 200 with a JSON body
|
||||||
|
|
||||||
|
Scenario Outline: A missing required variable stops the container
|
||||||
|
When the container starts without <variable>
|
||||||
|
Then the process exits with a non-zero status
|
||||||
|
And the log contains "Environment variable <variable> is not set"
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| variable |
|
||||||
|
| PUBLIC_URL |
|
||||||
|
| JWT_SECRET |
|
||||||
|
| SMTP_LOGIN |
|
||||||
|
| SMTP_SENDER |
|
||||||
|
| SMTP_PASSWORD |
|
||||||
|
| SMTP_HOST |
|
||||||
|
| SMTP_PORT |
|
||||||
|
|
||||||
|
Scenario: Data survives container recreation
|
||||||
|
Given an account was registered while the container was running
|
||||||
|
When the container is removed and recreated on the same named volume
|
||||||
|
Then the same account can log in
|
||||||
|
|
||||||
|
Scenario: Graceful shutdown on SIGTERM
|
||||||
|
When the container receives SIGTERM
|
||||||
|
Then the log contains "shutting down..."
|
||||||
|
And the container exits with status 0 within 10 seconds
|
||||||
@@ -0,0 +1,98 @@
|
|||||||
|
# QA: Docker deployment
|
||||||
|
|
||||||
|
Packaging and docs only. There is no Go test in test/ and no Vitest spec for this slice. All steps are manual command steps run from a clean checkout on a machine with Docker and Compose v2. Record results in the Notes table. Anything not run is reported NOT RUN, never PASS.
|
||||||
|
|
||||||
|
## Preconditions
|
||||||
|
- Clean checkout, no bin/, tmp/, node_modules or internal/infrastructure/assets/dist present.
|
||||||
|
- docker.env created from docker.env.example. JWT_SECRET is generated (openssl rand -hex 32) and SMTP values are real or placeholders. Nothing is committed.
|
||||||
|
- For local HTTP trial, ENVIRONMENT=development (otherwise the Secure cookie is not stored over HTTP).
|
||||||
|
|
||||||
|
## Static checks (no Docker daemon needed)
|
||||||
|
1. Dockerfile, .dockerignore and docker-compose.yml contain no comment lines (no line starting with `#`, no trailing ` #`).
|
||||||
|
2. .dockerignore lists tmp/, bin/, node_modules (also web/node_modules), .git, internal/infrastructure/assets/dist, .env and docker.env.
|
||||||
|
3. Dockerfile: three stages (bun, go, final). The Go build sets CGO_ENABLED=0, has no `-tags nofrontend`, and uses `-ldflags` containing `-X main.version=` from a build arg. The final stage has USER non-root, exec-form ENTRYPOINT (no `sh -c`), and no ENV, ARG or COPY holding JWT_SECRET or any SMTP_* value.
|
||||||
|
4. docker-compose.yml: one service, a named volume mounted at the data directory, a `ports` entry, `env_file`, a healthcheck on /healthz, `stop_grace_period` >= 15s.
|
||||||
|
5. git diff --stat shows no change under api/, internal/, web/src/, cmd/ and test/. Only Dockerfile, .dockerignore, docker-compose.yml, docker.env.example, Taskfile.yml, .gitignore, README.md and docs/ changed. No new env var appears in cmd/server/main.go.
|
||||||
|
6. docs/docker.md exists and is linked from README.md and docs/deployment.md.
|
||||||
|
7. `task --list` shows docker:build, docker:run, docker:up, docker:down and docker:logs.
|
||||||
|
|
||||||
|
## Build
|
||||||
|
8. `task docker:build` succeeds from the clean checkout, with no pre-built SPA.
|
||||||
|
9. `docker run --rm <image> --version` prints the version, which is not `dev`.
|
||||||
|
10. `docker image ls` size recorded. Flag it if it is above roughly 40 MB.
|
||||||
|
11. `docker image inspect` shows a non-root User, and `docker run --rm --entrypoint id <image>` shows uid not 0.
|
||||||
|
12. `docker history --no-trunc <image>` contains none of the values in docker.env.
|
||||||
|
|
||||||
|
## Run
|
||||||
|
13. `task docker:up` starts the service. `docker compose ps` shows it healthy within the healthcheck start period.
|
||||||
|
14. `curl -i http://localhost:8080/healthz` returns 200 and body `ok`.
|
||||||
|
15. `curl -i http://localhost:8080/` returns 200 text/html, and the SPA loads in a browser.
|
||||||
|
16. `curl -i http://localhost:8080/v1/auth/registration` returns 200 with JSON.
|
||||||
|
17. Logs show the listening line, and no permission error creating DB_FILE or UPLOAD_DIR on the volume.
|
||||||
|
18. Register an account in the SPA, then upload an image, to confirm both the DB and UPLOAD_DIR are writable by the container user.
|
||||||
|
|
||||||
|
## Persistence
|
||||||
|
19. `docker compose down` (no -v), then `task docker:up`. The account from step 18 can log in and the image is still served.
|
||||||
|
20. `docker compose down -v` removes the volume, and the next start gives an empty instance. Documented in docs/docker.md.
|
||||||
|
21. The backup procedure in docs/docker.md is followed once and restores into a fresh volume.
|
||||||
|
|
||||||
|
## Failure and shutdown
|
||||||
|
22. For each required variable in turn, remove it from the env file and run `docker compose up`. The container exits non-zero and the log contains `Environment variable <NAME> is not set`.
|
||||||
|
23. `docker compose stop` (timed) completes in under 10 s, the log contains `shutting down...`, and the exit code is 0. This proves PID 1 receives SIGTERM.
|
||||||
|
24. Break the healthcheck (stop the app inside the container, or point it at the wrong port): the service becomes unhealthy.
|
||||||
|
|
||||||
|
## SMTP (manual, needs real SMTP)
|
||||||
|
25. With an external SMTP host, trigger a registration or password-reset email and confirm delivery.
|
||||||
|
26. With a host MTA via host.docker.internal, repeat. On Linux this needs the extra_hosts mapping documented.
|
||||||
|
27. Confirm the failure mode is documented when SMTP is unreachable.
|
||||||
|
|
||||||
|
## Reverse proxy and TLS (manual)
|
||||||
|
28. Put Caddy or nginx in front, per docs/docker.md, with ENVIRONMENT=production over HTTPS. Log in and confirm the Secure cookie is accepted.
|
||||||
|
29. Set TRUSTED_PROXIES to the proxy address as seen by the container and confirm the login rate limiter uses X-Real-IP.
|
||||||
|
|
||||||
|
## Upgrade
|
||||||
|
30. Follow docs/docker.md: back up, rebuild with `task docker:build`, `task docker:up`. Data is intact and `--version` shows the new version.
|
||||||
|
31. Confirm docs state that browser-update Restart is unsupported in Docker (Settings shows "Not prepared").
|
||||||
|
|
||||||
|
## Notes to record
|
||||||
|
| Item | Value |
|
||||||
|
| --- | --- |
|
||||||
|
| Image size | |
|
||||||
|
| Base images and tags used | |
|
||||||
|
| Container uid | |
|
||||||
|
| Build time (cold) | |
|
||||||
|
| Docker and Compose versions | |
|
||||||
|
| Steps 25-29 run? | |
|
||||||
|
|
||||||
|
Not run in this slice: CI, registry publishing, Kubernetes or Helm, multi-arch. SPA tests and visual checks are out of scope.
|
||||||
|
|
||||||
|
## Results
|
||||||
|
Run on Windows 11, Docker 29.8.1, Compose 5.5.1, with a throwaway docker.env (fake secrets, ENVIRONMENT=development) that was deleted afterwards.
|
||||||
|
|
||||||
|
| Steps | Result |
|
||||||
|
| --- | --- |
|
||||||
|
| 1-7, 31 | PASS |
|
||||||
|
| 8 | PASS after a fix: `bun run build` failed in the image because vue-tsc cannot resolve .vue modules under the Bun-only node fallback; the Dockerfile now runs `bun run build-only`. vue-tsc passes on the host and under real node 22 |
|
||||||
|
| 9, 11, 12 | PASS (version v2.8.0-beta-dirty, uid 10001, entrypoint exec form, no secret names in history) |
|
||||||
|
| 10 | 54.5 MB, above the 40 MB flag (binary 29.9 MB on alpine 3.22) |
|
||||||
|
| 13-17 | PASS (healthy, /healthz 200 ok, / 200 text/html, /v1/auth/registration 200 JSON, no permission errors) |
|
||||||
|
| 18-19 | PASS (register, verify, login, image upload to /data/uploads as uid 10001; all survive `down` and recreate; uploaded image still served) |
|
||||||
|
| 20 | PASS (`down -v` removed the volume) |
|
||||||
|
| 21 | PASS (tar backup, `down -v`, restore, login and media list intact) |
|
||||||
|
| 22 | PASS for all 7 vars (exit 2, `Environment variable X is not set`) |
|
||||||
|
| 23 | PASS (stop 0.4 s, exit 0, `shutting down...` logged) |
|
||||||
|
| 24 | PASS (wrong-port healthcheck reports unhealthy) |
|
||||||
|
| 25 | PARTIAL: mail delivered over STARTTLS to a Mailpit container on the compose network with the CA trusted via SSL_CERT_FILE; no real external host |
|
||||||
|
| 26-29 | NOT RUN (host MTA, Caddy/nginx TLS, TRUSTED_PROXIES) |
|
||||||
|
| 30 | NOT RUN as a before/after upgrade |
|
||||||
|
| `task docker:run` | PASS (healthz 200, graceful stop, separate volume renewcms-data) |
|
||||||
|
|
||||||
|
Notes
|
||||||
|
| Item | Value |
|
||||||
|
| --- | --- |
|
||||||
|
| Image size | 54.5 MB |
|
||||||
|
| Base images and tags used | oven/bun:1-alpine, golang:1.27.1-alpine, alpine:3.22 |
|
||||||
|
| Container uid | 10001 |
|
||||||
|
| Build time (cold) | not measured, layers were partly cached; about 18 s warm |
|
||||||
|
| Docker and Compose versions | 29.8.1, 5.5.1 |
|
||||||
|
| Steps 25-29 run? | 25 partial, 26-29 no |
|
||||||
@@ -0,0 +1,71 @@
|
|||||||
|
Feature: Publish the RenewCMS image to a registry so an upgrade is "docker compose pull"
|
||||||
|
|
||||||
|
As a maintainer
|
||||||
|
I want one task that builds and pushes a versioned multi-arch image
|
||||||
|
So that site operators upgrade with "docker compose pull && docker compose up -d" and never build from source
|
||||||
|
|
||||||
|
Background:
|
||||||
|
Given there is no CI pipeline on purpose; publishing is a maintainer-run task, like "task release"
|
||||||
|
And the registry is the Gitea registry of git.floriansylvain.fr and REGISTRY_IMAGE defaults to "git.floriansylvain.fr/fsylvain/renewcms"
|
||||||
|
And the Dockerfile and docker-compose.yml from docker-deployment exist and are unchanged except where stated here
|
||||||
|
And Taskfile.yml gains "docker:publish", with variables REGISTRY_IMAGE and VERSION (default: git describe --tags)
|
||||||
|
And "docker:publish" refuses to run, before building anything, when REGISTRY_IMAGE is empty, when VERSION is not an exact tag "vX.Y.Z" or "vX.Y.Z-<pre>", or when the work tree is dirty
|
||||||
|
And the build is "docker buildx build --platform linux/amd64,linux/arm64 --build-arg VERSION=<tag>"; the tag is baked in through the existing version ldflags path, so the image's "renewcms --version" prints the tag
|
||||||
|
And tags pushed for vX.Y.Z-<pre>: "vX.Y.Z-<pre>" and "X.Y.Z-<pre>" and the moving tag "<pre-name>" (for example "beta"); "latest" is NOT moved
|
||||||
|
And tags pushed for vX.Y.Z: "vX.Y.Z", "X.Y.Z", "X.Y", and "latest"
|
||||||
|
And the maintainer authenticates beforehand with "docker login git.floriansylvain.fr"; the task never reads, stores or echoes a password or token, and never passes credentials on a command line
|
||||||
|
And no secret, .env, signing key or JWT_SECRET is copied into the image (already enforced by .dockerignore; checked again here)
|
||||||
|
And no image signing or attestation is part of this slice; the Ed25519 key signs release binaries only
|
||||||
|
And "task docker:publish -- --dry-run" builds for the host platform only with "--load", pushes nothing, needs no login and prints the tags it would push
|
||||||
|
And docker-compose.yml uses "image: ${RENEWCMS_IMAGE:-git.floriansylvain.fr/fsylvain/renewcms:beta}" (the default tag is "beta" because "latest" does not exist until the first stable release; it is changed to "latest" then) and its "build:" block moves to docker-compose.build.yml, used as "docker compose -f docker-compose.yml -f docker-compose.build.yml up -d --build"
|
||||||
|
And docs/docker.md, docs/deployment.md and README.md document pull-based upgrade, the build override, the tag scheme and the maintainer publish steps; no comments in any file
|
||||||
|
And the real push is a manual item: it needs a registry account and network
|
||||||
|
|
||||||
|
Scenario Outline: Tags for a version
|
||||||
|
Given VERSION is "<version>"
|
||||||
|
When "task docker:publish -- --dry-run" runs
|
||||||
|
Then it prints exactly these tags: <tags>
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| version | tags |
|
||||||
|
| v2.9.0 | v2.9.0, 2.9.0, 2.9, latest |
|
||||||
|
| v2.9.0-beta | v2.9.0-beta, 2.9.0-beta, beta |
|
||||||
|
| v2.9.0-rc.1 | v2.9.0-rc.1, 2.9.0-rc.1, rc |
|
||||||
|
|
||||||
|
Scenario Outline: Refusals before any build
|
||||||
|
Given <condition>
|
||||||
|
When "task docker:publish" runs
|
||||||
|
Then it exits non-zero with a message naming the problem and docker is not invoked
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| condition |
|
||||||
|
| REGISTRY_IMAGE is empty |
|
||||||
|
| VERSION is "dev" |
|
||||||
|
| VERSION is "2.9.0" (no leading v) |
|
||||||
|
| the work tree has uncommitted changes |
|
||||||
|
|
||||||
|
Scenario: Dry run builds and loads a working image
|
||||||
|
When "task docker:publish -- --dry-run" runs with VERSION "v2.9.0-beta"
|
||||||
|
Then an image is loaded locally for the host platform and no registry is contacted
|
||||||
|
And running it prints "v2.9.0-beta" for --version
|
||||||
|
And it serves GET /healthz as ok with the env from docker.env.example
|
||||||
|
And it runs as the non-root user with the data volume as in docker-deployment
|
||||||
|
|
||||||
|
Scenario: No secrets in the image
|
||||||
|
Given the dry-run image
|
||||||
|
Then "docker history" and a file listing show no .env, no release.key, no JWT_SECRET value and no SMTP password
|
||||||
|
|
||||||
|
Scenario: Compose pulls by default
|
||||||
|
Given docker-compose.yml with RENEWCMS_IMAGE unset
|
||||||
|
Then "docker compose config" shows the image "git.floriansylvain.fr/fsylvain/renewcms:beta" and no build section
|
||||||
|
And with RENEWCMS_IMAGE set to a tag, that tag is used
|
||||||
|
And with docker-compose.build.yml added, the build section is present and the image builds from the local Dockerfile
|
||||||
|
|
||||||
|
Scenario: Upgrade is a pull
|
||||||
|
Given a running stack on tag "v2.8.0-beta" with data in the volume
|
||||||
|
When the operator runs "docker compose pull && docker compose up -d" after a newer tag is pushed
|
||||||
|
Then the container is recreated on the new image and the articles, uploads and database in the volume are intact
|
||||||
|
And GET /v1/settings reports the new version
|
||||||
|
|
||||||
|
Scenario: Docs say the same thing
|
||||||
|
Then docs/docker.md, docs/deployment.md and README.md each show the pull upgrade, the tag scheme and the maintainer flow, and none claims CI exists
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
# QA: Docker image publishing
|
||||||
|
|
||||||
|
Everything runs on the real local Docker daemon, with no registry push. On Windows use MSYS_NO_PATHCONV=1 under Git Bash and put the Docker bin on PATH (memory: docker-windows-gotchas).
|
||||||
|
|
||||||
|
## Automated / scripted
|
||||||
|
1. Refusals: run "task docker:publish" with REGISTRY_IMAGE empty, VERSION=dev, VERSION=2.9.0, and a dirty tree; assert non-zero exit and that no docker build started (compare "docker buildx ls" and the image list before and after).
|
||||||
|
2. Tag table: run "task docker:publish -- --dry-run" with VERSION=v2.9.0, v2.9.0-beta and v2.9.0-rc.1 (the VERSION override is accepted only with --dry-run); compare the printed tags with the feature.
|
||||||
|
3. Dry run: the image is loaded; "docker run --rm <image> --version" prints the tag; start the stack from docker.env.example and check GET /healthz is ok, and "docker exec <ctr> id -u" is not 0.
|
||||||
|
4. Secrets: "docker history --no-trunc" and a file search for .env and release.key inside the image are clean; grep the layers for the sample JWT_SECRET value.
|
||||||
|
5. Compose: "docker compose config" with and without RENEWCMS_IMAGE, and with the build override.
|
||||||
|
6. Upgrade simulation: tag two local images v-old and v-new, run the stack on v-old, write an article, switch RENEWCMS_IMAGE to v-new, "docker compose up -d", and verify the article and the new version.
|
||||||
|
7. Docs: grep the three docs for "docker compose pull", the tag scheme, and the absence of CI claims.
|
||||||
|
8. No credentials: grep Taskfile.yml and docs for token or password literals; the task must not call "docker login".
|
||||||
|
|
||||||
|
## Manual (user performs; needs the registry)
|
||||||
|
- `docker login git.floriansylvain.fr`; "task docker:publish" with a real tag; confirm "docker buildx imagetools inspect <image>:<tag>" lists linux/amd64 and linux/arm64.
|
||||||
|
- On a clean machine, "docker compose pull && docker compose up -d" against the pushed image; confirm /settings shows the new version and the container guidance from container_update_guidance.
|
||||||
|
- Confirm the moving "beta" tag points at the intended digest and that "latest" did not move for a prerelease.
|
||||||
|
|
||||||
|
## Results
|
||||||
|
- 1 Refusals: PASS (coder and hardener runs).
|
||||||
|
- 2 Tag table: PASS (v2.9.0, v2.9.0-beta, v2.9.0-rc.1; re-seen with v2.9.0-beta and v2.9.1-beta, tags "vX, X, beta").
|
||||||
|
- 3 Dry run: PASS (--version prints the tag, /healthz ok, uid 10001).
|
||||||
|
- 4 Secrets: PASS.
|
||||||
|
- 5 Compose: PASS.
|
||||||
|
- 6 Upgrade simulation: PASS. Local images v2.9.0-beta and v2.9.1-beta, stack on the old tag, register + verify (mail captured over TLS by Mailpit) + login, article created (201), RENEWCMS_IMAGE switched, "docker compose up -d" recreated the container on the same volume. Old cookie still accepted, login 200, article 1 intact, GET /v1/settings reports v2.9.1-beta (was v2.9.0-beta).
|
||||||
|
- 7 Docs: PASS.
|
||||||
|
- 8 No credentials: PASS.
|
||||||
|
- Manual items: NOT RUN (need the registry): docker login, real multi-arch push and imagetools inspect, "docker compose pull" against the pushed image, moving beta/latest tag checks, builder failure paths of a real run.
|
||||||
@@ -9,8 +9,10 @@ Feature: Crop and resize step in the editor's image uploader
|
|||||||
Given ImageUploader inserts a crop-and-resize step between the idle file picker and the
|
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
|
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,
|
features/editor_image_upload.feature; that feature's idle, dragging-over, rejected,
|
||||||
uploading, inserted and failed states and its POST /v1/article/{articleId}/image contract
|
uploading, inserted and failed states and its POST /v1/media/ contract are unchanged and
|
||||||
are unchanged and out of scope here
|
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 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
|
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")
|
description "{filename} · {size}" (e.g. "north-wall.jpg · 3.9 MB")
|
||||||
@@ -32,8 +34,8 @@ Feature: Crop and resize step in the editor's image uploader
|
|||||||
crop is narrower than the chosen width, an info row reads "The crop is {crop width} px
|
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."
|
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
|
And the footer offers "Choose another file" (discards this step and returns to the idle file
|
||||||
picker with no adjustments carried over) and "Upload image" (uploads the cropped, resized
|
picker, with the tabs, with no adjustments carried over) and "Upload image" (uploads the cropped, resized
|
||||||
file through the unchanged POST /v1/article/{articleId}/image flow)
|
file through the unchanged POST /v1/media/ flow)
|
||||||
And "Rotate" turns the image 90° clockwise each activation, cycling 0°→90°→180°→270°→0°, and
|
And "Rotate" turns the image 90° clockwise each activation, cycling 0°→90°→180°→270°→0°, and
|
||||||
width presets apply to the post-rotation image
|
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
|
And "Reset" returns the ratio to Original, the width to 1600 px, the crop frame to the whole
|
||||||
@@ -43,7 +45,7 @@ Feature: Crop and resize step in the editor's image uploader
|
|||||||
Given ImageUploader is open in the idle state for article 12
|
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,
|
When the user chooses a file named "north-wall.jpg", content type "image/jpeg", size 3.9 MB,
|
||||||
natural dimensions 4032 × 3024 px
|
natural dimensions 4032 × 3024 px
|
||||||
Then no request is sent to POST /v1/article/12/image
|
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 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
|
And the crop frame starts as the whole image, ratio "Original" is selected, and width
|
||||||
"1600 px" is selected
|
"1600 px" is selected
|
||||||
@@ -53,7 +55,7 @@ Feature: Crop and resize step in the editor's image uploader
|
|||||||
Scenario: An SVG skips the crop step and uploads immediately
|
Scenario: An SVG skips the crop step and uploads immediately
|
||||||
Given ImageUploader is open in the idle state for article 12
|
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
|
When the user chooses a file named "diagram.svg", content type "image/svg+xml", size 40 KB
|
||||||
Then POST /v1/article/12/image is sent immediately with that file
|
Then POST /v1/media/ is sent immediately with that file
|
||||||
And the crop-and-resize step is never shown
|
And the crop-and-resize step is never shown
|
||||||
|
|
||||||
Scenario Outline: Choosing an aspect ratio locks the frame to it
|
Scenario Outline: Choosing an aspect ratio locks the frame to it
|
||||||
@@ -108,7 +110,7 @@ Feature: Crop and resize step in the editor's image uploader
|
|||||||
Scenario: "Choose another file" returns to the file picker without uploading
|
Scenario: "Choose another file" returns to the file picker without uploading
|
||||||
Given the crop-and-resize step is open for "north-wall.jpg"
|
Given the crop-and-resize step is open for "north-wall.jpg"
|
||||||
When the user activates "Choose another file"
|
When the user activates "Choose another file"
|
||||||
Then no request is sent to POST /v1/article/12/image
|
Then no request is sent to POST /v1/media/
|
||||||
And the idle state is shown again, with the file picker available
|
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
|
Scenario: A newly chosen file opens a fresh crop step, not the previous file's adjustments
|
||||||
@@ -123,7 +125,7 @@ Feature: Crop and resize step in the editor's image uploader
|
|||||||
Given the crop-and-resize step is open for "north-wall.jpg" with ratio "Original", width
|
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"
|
"1600 px" and the mono line "Uploads as 1600 × 1200 px · about 420 KB"
|
||||||
When the user activates "Upload image"
|
When the user activates "Upload image"
|
||||||
Then POST /v1/article/12/image is sent with a single file under the field name "file" whose
|
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
|
pixel dimensions are 1600 × 1200 and whose size is about 420 KB, not the original
|
||||||
4032 × 3024, 3.9 MB file
|
4032 × 3024, 3.9 MB file
|
||||||
And the uploading state shows "Uploading 0.0 of 420 KB"
|
And the uploading state shows "Uploading 0.0 of 420 KB"
|
||||||
|
|||||||
@@ -18,7 +18,7 @@ it renders internally (canvas/OffscreenCanvas is a coder implementation detail).
|
|||||||
"1600 px" selected, mono line "Uploads as 1600 × 1200 px · about 420 KB", footer "Choose
|
"1600 px" selected, mono line "Uploads as 1600 × 1200 px · about 420 KB", footer "Choose
|
||||||
another file" / "Upload image".
|
another file" / "Upload image".
|
||||||
2. **An SVG bypasses the step** — choose `diagram.svg` (image/svg+xml, 40 KB); assert an XHR to
|
2. **An SVG bypasses the step** — choose `diagram.svg` (image/svg+xml, 40 KB); assert an XHR to
|
||||||
`/v1/article/12/image` is created immediately and the crop step never renders.
|
`/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,
|
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
|
select each ratio pill; assert the frame's reported rect and the mono line's output size match
|
||||||
the feature's Examples table.
|
the feature's Examples table.
|
||||||
|
|||||||
@@ -1,148 +1,90 @@
|
|||||||
Feature: Removing an inline image from the editor
|
Feature: Removing an inline image from the article
|
||||||
|
|
||||||
As a verified RenewCMS owner writing an article
|
As a verified RenewCMS owner writing an article
|
||||||
I want to remove an image I've already inserted into the article body,
|
I want to take an image out of the article body, from a button or with Backspace or Delete
|
||||||
either through an explicit delete button or by pressing Backspace/Delete
|
So that an unwanted image leaves the article without deleting the file from my library
|
||||||
on the selected image, directly from the editor
|
|
||||||
So that a mistaken or unwanted image doesn't have to stay in the article
|
|
||||||
forever, and removing it behaves like every other destructive action in
|
|
||||||
RenewCMS: it asks for confirmation first, however the user starts it
|
|
||||||
|
|
||||||
Background:
|
Background:
|
||||||
Given docs/design/ has no board or state for removing an inline image;
|
Given this slice is SPA only for this file; the Go alias deletion is in
|
||||||
this feature was added at the user's explicit request ahead of design
|
features/remove_legacy_article_image_alias.feature
|
||||||
coverage, reusing the editor's existing visual language rather than
|
And docs/design/screens/media-picker.md now covers this flow ("Remove image: confirm" and
|
||||||
inventing new components: the trash icon and error color already used
|
"Removed"); it supersedes the earlier version of this feature, which had no design
|
||||||
by the article "Delete" button, and the ConfirmDialog component
|
coverage and used a red confirm that deleted through DELETE /v1/article/{id}/image/{imageId}
|
||||||
already used by "Delete this article?" (docs/design/screens/editor.md's
|
And removing an image is a body edit only: no API call of any kind is sent, before, during
|
||||||
"Delete: confirm" state)
|
or after the confirm, and the library and every other article are untouched
|
||||||
And this slice changes ArticleEditor's exposed insertImage(src, alt) to
|
And ArticleEditor keeps its exposed insertImage(src, alt, imageId) and removeImage(imageId),
|
||||||
insertImage(src, alt, imageId), stamping the inserted <img> node with
|
its "request-remove-image" event with the image id, and its Backspace and Delete handling,
|
||||||
the image's numeric id as a data-image-id attribute, persisted in the
|
which still intercepts the keys before Tiptap deletes the node
|
||||||
saved article body HTML; EditorView passes the id it now receives from
|
And an image already in a body from before data-image-id existed has no id, shows no
|
||||||
a successful upload (features/remove_article_image.feature's change to
|
"Remove image" button and is not intercepted by Backspace or Delete (unchanged)
|
||||||
POST .../image's 201 body) through to insertImage
|
And selecting an image node that carries data-image-id shows a button "Remove image" at the
|
||||||
And an image already present in an article's body from before this slice
|
image's top-right corner (8 px from the top and right): trash-2 icon at 14 px, neutral,
|
||||||
has no data-image-id attribute and so shows no delete affordance and
|
28 px high, 12 px medium text, a 1 px accented border and the page background; deselecting
|
||||||
is not intercepted by Backspace/Delete, until it is removed and
|
|
||||||
re-added
|
|
||||||
And selecting an image node that does carry a data-image-id attribute
|
|
||||||
shows a small delete button anchored to the image's top-right corner,
|
|
||||||
icon i-lucide-trash-2, color error, matching the article Delete
|
|
||||||
button's icon and color; deselecting the image (clicking elsewhere)
|
|
||||||
hides it
|
hides it
|
||||||
And there are two equivalent triggers for the same removal flow:
|
And EditorView reacts to "request-remove-image" by opening ConfirmDialog with tone "neutral",
|
||||||
activating that delete button, and pressing Backspace or Delete while
|
title "Remove this image from the article?", description "It's removed from this article
|
||||||
the image node is selected (a Tiptap NodeSelection on the image).
|
only. The file stays in your library and in any other article that uses it.", confirmLabel
|
||||||
Tiptap's native node deletion on Backspace/Delete is intercepted
|
"Remove image" and cancelLabel "Cancel"; the confirm button is primary, not red
|
||||||
before it reaches the document (e.g. via a keyboard-shortcut/keydown
|
And the body of the confirm is a bordered row with a 56 × 42 px thumbnail of the image, its
|
||||||
handler registered on the Image node or at the editor level, checked
|
filename, and "Stays in the library · {size}", for example "north-wall.jpg" and "Stays in
|
||||||
first while an image node is selected) so the key press never removes
|
the library · 3.9 MB"
|
||||||
the node directly; instead it triggers exactly the same flow as the
|
And the filename and size come from the images the SPA has seen this session, kept by image
|
||||||
button
|
id: those inserted from either tab and those loaded in the Library list
|
||||||
And either trigger emits ArticleEditor's new "request-remove-image"
|
And confirming runs removeImage(imageId), moves useArticleDraft to "dirty", closes the
|
||||||
event with the node's numeric image id; ArticleEditor does not call
|
dialog and shows the toast; the action cannot fail, so there is no inline error
|
||||||
the API or show any dialog itself, mirroring how "request-image"
|
And a thumbnail uses the image's src from the node
|
||||||
already only opens ImageUploader from EditorView
|
|
||||||
And EditorView reacts to "request-remove-image" by opening the existing
|
|
||||||
ConfirmDialog component with title "Remove this image?", description
|
|
||||||
"This image will be removed from the article. This can't be undone.",
|
|
||||||
confirmLabel "Remove image", cancelLabel "Cancel", pendingLabel
|
|
||||||
"Removing…", tone "danger" — the same component and tone already used
|
|
||||||
for "Delete this article?"
|
|
||||||
And ConfirmDialog's action calls DELETE /v1/article/{articleId}/image/
|
|
||||||
{imageId} through useApi (not the raw XMLHttpRequest used for upload,
|
|
||||||
since there is no progress to observe)
|
|
||||||
And on success (204) the action removes the image node from
|
|
||||||
ArticleEditor's content via a new exposed removeImage(imageId) method,
|
|
||||||
which moves useArticleDraft's state to "dirty" the same way any other
|
|
||||||
body edit does; ConfirmDialog then closes and a toast appears: color
|
|
||||||
success, icon i-lucide-circle-check, title "Image removed",
|
|
||||||
description "Save to keep this change."
|
|
||||||
And on any failure (404 for either the article or the image, 500, or a
|
|
||||||
network failure) the action throws, so ConfirmDialog shows its own
|
|
||||||
inline error "Couldn't remove the image, so it's still there. Try
|
|
||||||
again in a moment." and stays open; the image node is not removed and
|
|
||||||
the draft's dirty state is unchanged
|
|
||||||
And a 401 is handled entirely by useApi's global handling
|
|
||||||
(features/api_client_global_error_handling.feature) and is out of
|
|
||||||
scope for new scenarios here
|
|
||||||
And once the confirm dialog is open, its cancel/confirm/failure
|
|
||||||
behaviour (covered below) is identical regardless of which trigger
|
|
||||||
opened it, so those scenarios are written once, against the button
|
|
||||||
trigger, and are not duplicated per trigger
|
|
||||||
|
|
||||||
Scenario: Selecting an inserted image reveals its delete button
|
Scenario: Selecting an inserted image reveals "Remove image"
|
||||||
Given the user is on /article/12/edit with an image in the body carrying
|
Given the user is on /article/12/edit with an image in the body carrying data-image-id "1"
|
||||||
data-image-id "10"
|
|
||||||
When the user clicks that image
|
When the user clicks that image
|
||||||
Then a delete button (trash icon, error color) appears at the image's
|
Then a button "Remove image" with a trash-2 icon shows at the image's top-right corner
|
||||||
top-right corner
|
|
||||||
When the user clicks elsewhere in the editor
|
When the user clicks elsewhere in the editor
|
||||||
Then the delete button is no longer shown
|
Then the button is no longer shown
|
||||||
|
|
||||||
Scenario Outline: Either trigger opens the confirm dialog and sends no request yet, without letting Tiptap delete the node itself
|
Scenario: An image without data-image-id has no button
|
||||||
Given the image with data-image-id "10" is selected on /article/12/edit
|
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>
|
When the user <triggers-removal>
|
||||||
Then a dialog titled "Remove this image?" opens, with description "This
|
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."
|
||||||
image will be removed from the article. This can't be undone.",
|
And its body shows the thumbnail, "north-wall.jpg" and "Stays in the library · 3.9 MB"
|
||||||
cancel "Cancel" and confirm "Remove image"
|
And its buttons read "Cancel" and a primary "Remove image"
|
||||||
And no request has been sent to DELETE /v1/article/12/image/10
|
And no request has been sent
|
||||||
And the image node is still present in the editor's content (Tiptap's
|
And the image node is still in the editor's content (Tiptap's native deletion did not run)
|
||||||
native node deletion did not run)
|
|
||||||
|
|
||||||
Examples:
|
Examples:
|
||||||
| triggers-removal |
|
| triggers-removal |
|
||||||
| activates the image's delete button |
|
| activates the "Remove image" button |
|
||||||
| presses Backspace with the image node selected |
|
| presses Backspace with the image node selected |
|
||||||
| presses Delete with the image node selected |
|
| presses Delete with the image node selected |
|
||||||
|
|
||||||
Scenario: Cancelling the confirm dialog changes nothing
|
Scenario: The confirm for an image the session has not seen
|
||||||
Given the confirm dialog is open for image id 10 on /article/12/edit
|
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"
|
When the user activates "Cancel"
|
||||||
Then the dialog closes
|
Then the dialog closes, no request has been sent, the image is still in the content, and the draft's dirty state is unchanged
|
||||||
And no request has been sent to DELETE /v1/article/12/image/10
|
|
||||||
And the image is still present in the editor's content
|
|
||||||
And the draft's dirty state is unchanged
|
|
||||||
|
|
||||||
Scenario: Confirming removes the image, marks the draft dirty, and shows a success toast
|
Scenario: Confirming removes the image from the body only
|
||||||
Given the confirm dialog is open for image id 10 on /article/12/edit,
|
Given the confirm is open for image id 1 on /article/12/edit, the draft in the Saved state
|
||||||
the draft in the Saved state
|
|
||||||
When the user activates "Remove image"
|
When the user activates "Remove image"
|
||||||
Then DELETE /v1/article/12/image/10 is sent
|
Then the dialog closes and the image leaves the editor's content
|
||||||
When that request resolves 204
|
And SaveStatus reads "Unsaved changes" and Save is enabled
|
||||||
Then the dialog closes
|
And a toast appears: color success, icon i-lucide-circle-check, title "Image removed", description "It's still in your library."
|
||||||
And the image is removed from the editor's content
|
And no request of any kind has been sent
|
||||||
And SaveStatus reads "Unsaved changes" and the Save button becomes
|
|
||||||
enabled
|
|
||||||
And a toast appears: color success, icon i-lucide-circle-check, title
|
|
||||||
"Image removed", description "Save to keep this change."
|
|
||||||
|
|
||||||
Scenario Outline: A failed removal keeps the image and shows the dialog's inline error
|
Scenario: A removal started by Backspace behaves like one started by the button
|
||||||
Given the confirm dialog is open for image id 10 on /article/12/edit
|
Given the confirm is open for image id 1, opened by Backspace, the draft in the Saved state
|
||||||
When the user activates "Remove image"
|
When the user activates "Remove image"
|
||||||
And DELETE /v1/article/12/image/10 <failure>
|
Then the outcome is the same as above
|
||||||
Then the dialog stays open, showing the inline error "Couldn't remove
|
|
||||||
the image, so it's still there. Try again in a moment."
|
|
||||||
And the image is still present in the editor's content
|
|
||||||
And the draft's dirty state is unchanged
|
|
||||||
|
|
||||||
Examples:
|
Scenario: The removed image can be picked again
|
||||||
| failure |
|
Given image id 1 was removed from the body this session
|
||||||
| resolves with a 404 response |
|
When the user opens the Library tab
|
||||||
| resolves with a 500 response |
|
Then "north-wall.jpg" no longer carries "In this article"
|
||||||
| never reaches the server |
|
|
||||||
|
|
||||||
Scenario: Confirming a removal started by Backspace/Delete behaves exactly like confirming one started by the button
|
|
||||||
Given the confirm dialog is open for image id 10 on /article/12/edit,
|
|
||||||
opened by pressing Backspace with the image node selected, the draft
|
|
||||||
in the Saved state
|
|
||||||
When the user activates "Remove image"
|
|
||||||
Then DELETE /v1/article/12/image/10 is sent
|
|
||||||
When that request resolves 204
|
|
||||||
Then the dialog closes
|
|
||||||
And the image is removed from the editor's content
|
|
||||||
And SaveStatus reads "Unsaved changes" and the Save button becomes
|
|
||||||
enabled
|
|
||||||
And a toast appears: color success, icon i-lucide-circle-check, title
|
|
||||||
"Image removed", description "Save to keep this change."
|
|
||||||
@@ -1,88 +1,25 @@
|
|||||||
# QA: Removing an inline image from the editor
|
# QA: Removing an inline image from the article
|
||||||
|
|
||||||
## Automated (Vitest + Vue Test Utils, `task test:web`)
|
## Automated (Vitest + Vue Test Utils, `task test:web`)
|
||||||
|
|
||||||
Mount EditorPage inside DashboardShell at `/article/12/edit` with the
|
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.
|
||||||
editor_core.qa.md fixture article (id 12, "How we price a bathroom
|
|
||||||
renovation", is_online false), GET already resolved 200, and a body
|
|
||||||
containing `<img src="/static/uploadedImages/before.png" data-image-id="10"
|
|
||||||
alt="">`. Mock `useApi`'s `request` for `DELETE /v1/article/12/image/10`
|
|
||||||
(fetch-based, not XHR — reuse whatever mock
|
|
||||||
`api_client_global_error_handling.qa.md` already sets up for `request`).
|
|
||||||
|
|
||||||
1. **Selecting the image reveals the delete button** — click the image
|
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.
|
||||||
node; assert a delete button (trash icon, error color) renders anchored
|
2. **No id, no button** - an image without `data-image-id`: no button, and a Backspace keydown does not open the dialog.
|
||||||
to it; click elsewhere in the editor; assert the button is gone.
|
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.
|
||||||
2. **Activating the delete button opens the confirm dialog** — select the
|
4. **Unseen image** - id 7 not in the record; assert the row shows the thumbnail and "Stays in the library" only.
|
||||||
image, activate its delete button; assert a dialog titled "Remove this
|
5. **Cancel changes nothing.**
|
||||||
image?", description "This image will be removed from the article. This
|
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.
|
||||||
can't be undone.", cancel "Cancel", confirm "Remove image"; assert no
|
7. **Backspace-opened confirm** gives the same outcome as 6.
|
||||||
request was sent yet; assert the image node is still present (Tiptap's
|
8. **Removed image loses its tag** - open the Library after step 6; assert "north-wall.jpg" has no "In this article" tag.
|
||||||
native deletion did not run).
|
|
||||||
3. **Backspace on the selected image opens the same confirm dialog instead
|
|
||||||
of deleting the node** — select the image node (NodeSelection), fire a
|
|
||||||
`keydown` for `Backspace`; assert the same dialog as step 2 opens;
|
|
||||||
assert no request was sent yet; assert the image node is still present
|
|
||||||
in the editor's document (i.e. the keydown was intercepted before
|
|
||||||
Tiptap's default node-deletion ran, not just undone afterwards).
|
|
||||||
4. **Delete on the selected image opens the same confirm dialog instead of
|
|
||||||
deleting the node** — same as step 3 but firing `keydown` for `Delete`.
|
|
||||||
5. **Cancelling changes nothing** — from the open dialog (opened via the
|
|
||||||
button), click "Cancel"; assert the dialog closes, no request was sent,
|
|
||||||
the image node is still in the editor's content, and SaveStatus/dirty
|
|
||||||
state is unchanged.
|
|
||||||
6. **Confirming removes the image, marks dirty, and toasts (button
|
|
||||||
trigger)** — from the open dialog (Saved state), click "Remove image";
|
|
||||||
assert a DELETE request to `/v1/article/12/image/10` was made; resolve
|
|
||||||
it 204; assert the dialog closes, the image node is gone from the
|
|
||||||
editor's content, SaveStatus reads "Unsaved changes" and Save is
|
|
||||||
enabled, and a toast appears with color success, icon
|
|
||||||
`i-lucide-circle-check`, title "Image removed", description "Save to
|
|
||||||
keep this change."
|
|
||||||
7. **Confirming removes the image the same way when opened via
|
|
||||||
Backspace/Delete** — repeat step 6's assertions, but open the dialog via
|
|
||||||
the Backspace keydown from step 3 instead of the button; assert the
|
|
||||||
outcome (request, node removal, dirty state, toast) is identical.
|
|
||||||
8. **A failed removal keeps the image and shows the inline error,
|
|
||||||
Examples-driven** — for a 404 response, a 500 response, and a rejected/
|
|
||||||
network-failure request: from the open dialog (button trigger), click
|
|
||||||
"Remove image"; resolve/reject accordingly; assert the dialog stays open
|
|
||||||
showing the inline error "Couldn't remove the image, so it's still
|
|
||||||
there. Try again in a moment."; assert the image node is still present
|
|
||||||
and the draft's dirty state is unchanged.
|
|
||||||
|
|
||||||
## Visual
|
## Visual: `task visual:check -- media-picker`
|
||||||
|
|
||||||
No `docs/design/` board or state exists for this trigger (see the feature's
|
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.
|
||||||
Background). Per the user's explicit direction this slice ships the SPA
|
|
||||||
behaviour anyway, but `task visual:check -- editor` has nothing to compare
|
|
||||||
it against, so no visual capture is added for it — this is an intentional
|
|
||||||
gap, `skip: no-design-coverage` (distinct from `skip: clock-sensitive`), not
|
|
||||||
a QA oversight. If a board for this state is added to `docs/design/` later,
|
|
||||||
it needs its own follow-up slice to add the visual check.
|
|
||||||
|
|
||||||
- [ ] Keyboard/focus: once a delete button is shown, it is reachable by Tab
|
- [ ] 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.
|
||||||
and activates on Enter/Space; pressing Backspace/Delete with the
|
|
||||||
image node selected but focus elsewhere in the page does not trigger
|
|
||||||
removal (only an actual Tiptap NodeSelection on the image should);
|
|
||||||
ConfirmDialog's existing focus trap and cancel-button-default-focus
|
|
||||||
behaviour (already covered by the article-delete flow) applies
|
|
||||||
unchanged regardless of which trigger opened it.
|
|
||||||
|
|
||||||
## Manual verification
|
## Manual verification
|
||||||
|
|
||||||
- **Real DELETE round trip against a running server** — Vitest only mocks
|
- **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).
|
||||||
`useApi`'s request; confirm a real removal (204/404/500) against
|
- **Save after removal** against `task dev`: remove an image, save, reload; the image is gone from the article and still listed in `/media`.
|
||||||
`task dev` with a live SQLite file and the real
|
|
||||||
`DELETE /v1/article/{id}/image/{imageId}` handler, since
|
|
||||||
`features/remove_article_image.feature`'s httptest suite covers the
|
|
||||||
handler in isolation but never through this SPA flow.
|
|
||||||
- **Real keyboard behaviour** — confirm in a real browser that selecting an
|
|
||||||
image (click) and pressing Backspace/Delete opens the confirm dialog
|
|
||||||
rather than deleting the node, including with an IME or on a platform
|
|
||||||
where Backspace/Delete semantics differ, since jsdom's `keydown`
|
|
||||||
simulation doesn't exercise Tiptap's real ProseMirror keymap precedence.
|
|
||||||
- **Design review of the delete-button/ConfirmDialog approach** — since
|
|
||||||
there is no board for this state, once a board is added, re-verify this
|
|
||||||
implementation still matches it (or update the implementation to match);
|
|
||||||
until then this is a best-effort, design-team-unreviewed UI.
|
|
||||||
@@ -1,136 +1,191 @@
|
|||||||
Feature: Wiring the editor's image upload flow
|
Feature: The editor's Upload tab uploads to the library
|
||||||
|
|
||||||
As a verified RenewCMS owner writing an article
|
As a verified RenewCMS owner writing an article
|
||||||
I want the editor's image button (and dropping a file onto the editor) to open an upload
|
I want the Upload tab of the "Add an image" dialog to check my file, spot duplicates,
|
||||||
modal that validates the file, shows progress, and inserts the result at my cursor
|
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
|
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
|
feedback when a file is rejected or the upload fails
|
||||||
|
|
||||||
Background:
|
Background:
|
||||||
Given EditorView.vue listens for ArticleEditor's "request-image" event and, on it, opens
|
Given this slice is SPA only for this file: the API from the media library slice is used
|
||||||
ImageUploader (a UModal titled "Add an image") with the current article's id
|
unchanged
|
||||||
And dropping a file directly onto the editor surface also opens ImageUploader, with that
|
And EditorView listens for ArticleEditor's "request-image" event and opens ImageUploader
|
||||||
file already provided to it instead of an empty idle state
|
(a UModal titled "Add an image") with the picker tabs, whose Library tab is specified in
|
||||||
And ImageUploader validates a chosen or dropped file in the browser, checking both its MIME
|
features/editor_media_picker.feature
|
||||||
type and its file extension against png/jpeg/webp/svg, and that its size is at most
|
And dropping a file onto the editor surface opens ImageUploader on the Upload tab with that
|
||||||
10 × 1024 × 1024 bytes, before sending anything
|
file already provided, and no list request is sent until the Library tab is opened
|
||||||
And a file that passes validation is uploaded via a new useImageUpload composable, using
|
And this file supersedes these statements of the earlier version: the upload goes to
|
||||||
XMLHttpRequest (not useApi) so upload progress is observable, as multipart/form-data with
|
POST /v1/media/ and no longer to POST /v1/article/{articleId}/image; the 201 body is the
|
||||||
the file under the field name "file", to POST /v1/article/{articleId}/image, per
|
library item { id, filename, url, size, content_type, width, height, sha256, uploaded_by,
|
||||||
features/upload_article_image.feature's already-implemented and already-mounted contract
|
created_at, used_in, duplicate }; there is no article id in any upload request and no 404
|
||||||
And a 201 response's {"location": "..."} is inserted into ArticleEditor's content at the
|
for a deleted article on upload
|
||||||
current cursor position via an exposed insertImage(src, alt) method, with alt ""; this
|
And ImageUploader validates a chosen or dropped file in the browser with validateImageFile
|
||||||
moves useArticleDraft's state to "dirty" the same way any other body edit does
|
from web/src/lib/imageUpload.ts, size first (10485760 bytes allowed, one byte more is too
|
||||||
And closing the modal while an upload is in flight aborts the XMLHttpRequest
|
large), then MIME type and extension must both be allowed (png, jpeg, webp, svg), before
|
||||||
And a 401 response is handled entirely by useApi's global handling
|
hashing or sending anything
|
||||||
(features/api_client_global_error_handling.feature) and is out of scope for new scenarios
|
And a file that passes validation is hashed with hashFile from web/src/lib/fileHash.ts (the
|
||||||
here; the same is true of a 404 (the article was deleted elsewhere), which the editor's
|
lib shared with MediaPage), and GET /v1/media/?hash=<sha256 hex> is sent through useApi;
|
||||||
existing not-found handling already covers (features/editor_core.feature)
|
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
|
||||||
|
|
||||||
Scenario: Opening the uploader from the toolbar's image button shows the idle state
|
Rule: Opening
|
||||||
Given the user is on /article/12/edit with the editor focused
|
|
||||||
When the user activates the toolbar's "Image" button
|
|
||||||
Then ImageUploader opens titled "Add an image"
|
|
||||||
And it shows "Drop an image here", a "Choose file" action, and the help text
|
|
||||||
"PNG, JPEG, WEBP, SVG · max 10 MB"
|
|
||||||
And its cancel action reads "Cancel"
|
|
||||||
And no request has been sent
|
|
||||||
|
|
||||||
Scenario: Dragging a file over the editor surface shows the dragging-over state
|
Scenario: The toolbar's image button opens on Upload when the library is empty
|
||||||
Given ImageUploader is open in the idle state
|
Given the user is on /article/12/edit with the editor focused
|
||||||
When the user drags a file over the drop zone
|
And GET /v1/media/?limit=24 resolves 200 with no item
|
||||||
Then the drop zone reads "Drop to upload"
|
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 valid file onto the editor opens the uploader already uploading it
|
Scenario: Dropping a file opens Upload with the file
|
||||||
Given the user is on /article/12/edit with the editor focused and ImageUploader is not open
|
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
|
When the user drops a file named "before.png", content type "image/png", size 3.9 MB, onto the editor surface
|
||||||
the editor surface
|
Then ImageUploader opens on the Upload tab
|
||||||
Then ImageUploader opens titled "Add an image"
|
And GET /v1/media/?hash=<sha256 of the file> is sent, and no request to GET /v1/media/?limit=24 is sent
|
||||||
And POST /v1/article/12/image is sent with that file under the field name "file"
|
And when the lookup resolves 200 with no item the crop and resize step shows for "before.png"
|
||||||
And the uploading state is shown, not the idle state
|
And no POST /v1/media/ has been sent
|
||||||
|
|
||||||
Scenario Outline: Choosing a file the browser can reject never sends a request
|
Scenario: Dragging a file over the drop zone shows the dragging-over state
|
||||||
Given ImageUploader is open in the idle state for article 12
|
Given ImageUploader is open on the Upload tab in the idle state
|
||||||
When the user chooses a file named "<filename>", content type "<content_type>", size <size>
|
When the user drags a file over the drop zone
|
||||||
Then no request is sent to POST /v1/article/12/image
|
Then the drop zone reads "Drop to upload"
|
||||||
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:
|
Rule: Browser checks, nothing is sent
|
||||||
| 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
|
Scenario Outline: Choosing a file the browser can reject sends nothing
|
||||||
Given ImageUploader is in the rejected state for a file named "plan.pdf"
|
Given ImageUploader is open in the idle state
|
||||||
When the user activates "Choose another file"
|
When the user chooses a file named "<filename>", content type "<content_type>", size <size>
|
||||||
Then the idle state is shown again, with the file picker available
|
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"
|
||||||
|
|
||||||
Scenario: A valid upload shows progress and its cancel action reads "Cancel upload"
|
Examples:
|
||||||
Given ImageUploader is open in the idle state for article 12
|
| filename | content_type | size | description |
|
||||||
When the user chooses a file named "north-wall.jpg", content type "image/jpeg", size 3.9 MB
|
| plan.pdf | application/pdf | 1.2 MB | Use a PNG, JPEG, WEBP or SVG image, up to 10 MB. |
|
||||||
Then POST /v1/article/12/image is sent with that file under the field name "file"
|
| disguised.png | application/pdf | 1.2 MB | Use a PNG, JPEG, WEBP or SVG image, up to 10 MB. |
|
||||||
And the uploading state shows "north-wall.jpg 0%" and "Uploading 0.0 of 3.9 MB"
|
| north-wall.tif | image/png | 14.2 MB | north-wall.tif is 14.2 MB. Images can be up to 10 MB. |
|
||||||
And its cancel action reads "Cancel upload"
|
|
||||||
When the upload reports 2.4 MB sent of 3.9 MB
|
|
||||||
Then the uploading state shows "north-wall.jpg 62%" and "Uploading 2.4 of 3.9 MB"
|
|
||||||
|
|
||||||
Scenario: Closing the dialog during an upload cancels it
|
Scenario: "Choose another file" from the rejected state returns to idle
|
||||||
Given ImageUploader is uploading a file named "north-wall.jpg" to article 12
|
Given ImageUploader is in the rejected state for "plan.pdf"
|
||||||
When the user activates "Cancel upload" (or otherwise closes the modal)
|
When the user activates "Choose another file"
|
||||||
Then the in-flight XMLHttpRequest is aborted
|
Then the idle state is shown again, with the tabs
|
||||||
And the modal closes
|
|
||||||
And the editor's body is unchanged and remains in its previous dirty/clean state
|
|
||||||
|
|
||||||
Scenario: A successful upload inserts the image at the cursor and marks the draft dirty
|
Rule: Already in your library
|
||||||
Given the user is on /article/12/edit in the Saved state and ImageUploader is uploading a
|
|
||||||
file named "north-wall.jpg" to article 12
|
|
||||||
When POST /v1/article/12/image resolves 201 with {"location": "/static/uploadedImages/north-wall.jpg"}
|
|
||||||
Then the uploading state briefly shows "Image added"
|
|
||||||
And the image at "/static/uploadedImages/north-wall.jpg" is inserted into the editor's
|
|
||||||
content at the cursor via insertImage
|
|
||||||
And SaveStatus reads "Unsaved changes" and the Save button becomes 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 modal closes 600 ms after the response resolves
|
|
||||||
|
|
||||||
Scenario Outline: A server-side upload failure keeps the article unchanged and offers a retry
|
Scenario: A file whose content exists shows the duplicate card and sends nothing
|
||||||
Given ImageUploader is uploading a file named "north-wall.jpg" to article 12
|
Given ImageUploader is open in the idle state
|
||||||
When POST /v1/article/12/image <failure>
|
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)
|
||||||
Then the failed state shows the title "Upload failed"
|
When the user chooses a valid file named "north-wall.jpg" of 3.9 MB
|
||||||
And its text reads "The server didn't accept the file. Your article hasn't changed."
|
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 its confirm action reads "Try again"
|
And the card has the buttons "Use existing" (primary) and "Upload anyway", stacked and full width below md
|
||||||
And the editor's body is unchanged, and no image is inserted
|
And no POST /v1/media/ has been sent and the crop step has not opened
|
||||||
|
|
||||||
Examples:
|
Scenario: Several matches name the oldest one
|
||||||
| failure |
|
Given the hash lookup resolves 200 with several images
|
||||||
| resolves with a 500 response |
|
Then the card names the oldest match
|
||||||
| never reaches the server |
|
|
||||||
|
|
||||||
Scenario: "Try again" re-attempts the upload with the same file
|
Scenario: A match without a known uploader drops the "by" part
|
||||||
Given ImageUploader is in the failed state for a file named "north-wall.jpg", article 12,
|
Given the matched image's uploaded_by is empty
|
||||||
after a 500 response
|
Then the text reads "north-wall.jpg matches an image uploaded on 12 Sep 2026."
|
||||||
When the user activates "Try again"
|
|
||||||
Then POST /v1/article/12/image is sent again with that same file under the field name "file"
|
|
||||||
And the uploading state is shown
|
|
||||||
|
|
||||||
Scenario: A server 400 for a type the client should have caught shows the same rejected copy
|
Scenario: "Use existing" goes to the alt text step for the existing image
|
||||||
Given ImageUploader is uploading a file named "notes.pdf" to article 12 (a type that
|
Given the duplicate card is showing for image id 1
|
||||||
defensively passed the browser's own check, e.g. a MIME type the browser misreported)
|
When the user activates "Use existing"
|
||||||
When POST /v1/article/12/image resolves 400
|
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
|
||||||
Then the rejected state shows the title "\"notes.pdf\" can't be used"
|
And no POST /v1/media/ has been sent
|
||||||
And its text reads "Use a PNG, JPEG, WEBP or SVG image, up to 10 MB."
|
|
||||||
And its confirm action reads "Choose another file"
|
|
||||||
And the editor's body is unchanged, and no image is inserted
|
|
||||||
|
|
||||||
Scenario: A server 400 for a size the client should have caught shows the same size-named copy
|
Scenario: "Upload anyway" continues to crop and upload
|
||||||
Given ImageUploader is uploading a file named "north-wall.tif" to article 12 (a file that
|
Given the duplicate card is showing for "north-wall.jpg" (4032 × 3024)
|
||||||
defensively passed the browser's own size check somehow, e.g. its reported size changed
|
When the user activates "Upload anyway"
|
||||||
between selection and send)
|
Then the crop and resize step opens for that file
|
||||||
When POST /v1/article/12/image resolves 400
|
And the hash lookup is not repeated
|
||||||
Then the rejected state shows the title "\"north-wall.tif\" can't be used"
|
And uploading from that step sends POST /v1/media/ and follows the normal states
|
||||||
And its text reads "north-wall.tif is 14.2 MB. Images can be up to 10 MB."
|
|
||||||
And its confirm action reads "Choose another file"
|
Scenario: "Upload anyway" for an SVG uploads immediately
|
||||||
And the editor's body is unchanged, and no image is inserted
|
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 |
|
||||||
@@ -1,90 +1,33 @@
|
|||||||
# QA: Wiring the editor's image upload flow
|
# QA: The editor's Upload tab uploads to the library
|
||||||
|
|
||||||
## Automated (Vitest + Vue Test Utils, `task test:web`)
|
## Automated (Vitest + Vue Test Utils, `task test:web`)
|
||||||
|
|
||||||
Mock `XMLHttpRequest` (a fake implementing `open`/`setRequestHeader`/`send`/`abort` and firing
|
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.
|
||||||
`upload.progress`, `load`, `error`) for `POST /v1/article/{id}/image`; useApi/fetch is not
|
|
||||||
involved in this slice. Mount EditorPage inside DashboardShell at `/article/12/edit` with the
|
|
||||||
editor_core.qa.md fixture article (id 12, title "How we price a bathroom renovation", is_online
|
|
||||||
false), GET already resolved 200.
|
|
||||||
|
|
||||||
1. **Toolbar button opens the idle state** — click the toolbar's "Image" button; assert
|
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.
|
||||||
ImageUploader opens titled "Add an image", showing "Drop an image here", "Choose file",
|
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.
|
||||||
"PNG, JPEG, WEBP, SVG · max 10 MB", cancel "Cancel"; assert no XHR was created.
|
3. **Dragging over shows "Drop to upload"**.
|
||||||
2. **Dragging over shows "Drop to upload"** — with the uploader open idle, fire a `dragover` on
|
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.
|
||||||
the drop zone; assert the text changes to "Drop to upload".
|
5. **"Choose another file" returns to idle**, with the tabs back.
|
||||||
3. **Dropping a file on the editor opens the uploader already uploading** — with the uploader
|
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.
|
||||||
closed, dispatch a `drop` event with a file `before.png` (image/png, 3.9 MB) on the editor
|
7. **Several matches name the oldest**, and **no uploader drops the "by" part**.
|
||||||
surface; assert ImageUploader opens and an XHR to `/v1/article/12/image` is created with that
|
8. **"Use existing"** - assert the Library tab is selected, image 1 selected, the alt field empty, "Insert image" enabled, and no XHR.
|
||||||
file, and the uploading state (not idle) is shown.
|
9. **"Upload anyway"** - assert the crop step opens (raster) with no second `?hash=` request; for an SVG assert the XHR is created at once.
|
||||||
4. **Rejected — Examples-driven on type, extension mismatch, and size** — for each of `plan.pdf`
|
10. **Check skipped** - Examples: `hashFile` resolves null, lookup 500, lookup rejects; assert the crop step opens with no card.
|
||||||
(application/pdf, 1.2 MB), `disguised.png` (application/pdf, 1.2 MB), and `north-wall.tif`
|
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".
|
||||||
(image/png, 14.2 MB), choose the file via the `UFileUpload`; assert no XHR is created and the
|
12. **Closing during an upload aborts** - `abort` called, dialog closed, body and dirty state unchanged.
|
||||||
rejected state shows the exact title/text/confirm/cancel copy from the feature's Examples.
|
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.
|
||||||
5. **"Choose another file" returns to idle** — from the rejected state, click "Choose another
|
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.
|
||||||
file"; assert the idle state re-renders.
|
15. **"Try again" resends the same file** with no new `?hash=` request.
|
||||||
6. **Uploading shows live progress and "Cancel upload"** — choose `north-wall.jpg` (image/jpeg,
|
16. **Sessions** - Examples from the feature; assert the same redirect `useApi` performs, with no local copy.
|
||||||
3.9 MB); assert the XHR is created with that file under field `file`; assert cancel reads
|
|
||||||
"Cancel upload"; fire an `upload.progress` event with `loaded: 2.4 * 1024 * 1024, total: 3.9 *
|
|
||||||
1024 * 1024`; assert the text reads "north-wall.jpg 62%" and "Uploading 2.4 of 3.9 MB".
|
|
||||||
7. **Closing during an upload aborts the XHR** — from the uploading state, click "Cancel
|
|
||||||
upload"; assert the fake XHR's `abort` was called, the modal closes, and the editor's body
|
|
||||||
and dirty state are unchanged from before the upload started.
|
|
||||||
8. **A 201 inserts at the cursor and marks the draft dirty** — from the uploading state, resolve
|
|
||||||
the fake XHR with status 201 and body `{"location": "/static/uploadedImages/north-wall.jpg"}`;
|
|
||||||
assert `insertImage` (or the editor's exposed method) was called with that location; assert
|
|
||||||
SaveStatus now reads "Unsaved changes" and Save is enabled; assert a toast appears with color
|
|
||||||
success, icon `i-lucide-circle-check`, title "Image added", description "Save to keep it in
|
|
||||||
the article."; advance fake timers 600 ms and assert the modal has closed.
|
|
||||||
9. **A 500 or network failure shows "Upload failed" and keeps the article unchanged, Examples-
|
|
||||||
driven** — for (a) the fake XHR firing `load` with status 500 and (b) firing `error`; assert
|
|
||||||
the failed state shows title "Upload failed", text "The server didn't accept the file. Your
|
|
||||||
article hasn't changed.", confirm "Try again"; assert no `insertImage` call and the editor's
|
|
||||||
body/dirty state is unchanged.
|
|
||||||
10. **"Try again" resends the same file** — from the failed state for `north-wall.jpg`, click
|
|
||||||
"Try again"; assert a new XHR is created for `/v1/article/12/image` with the same file, and
|
|
||||||
the uploading state is shown again.
|
|
||||||
11. **A server 400 for a type the client should have caught shows the rejected copy** — from an
|
|
||||||
uploading state for `notes.pdf`, resolve the fake XHR with status 400; assert the rejected
|
|
||||||
state shows title "\"notes.pdf\" can't be used", text "Use a PNG, JPEG, WEBP or SVG image,
|
|
||||||
up to 10 MB.", confirm "Choose another file"; assert no `insertImage` call.
|
|
||||||
12. **A server 400 for a size the client should have caught shows the size-named rejected copy**
|
|
||||||
— from an uploading state for `north-wall.tif`, resolve the fake XHR with status 400; assert
|
|
||||||
the rejected state shows title "\"north-wall.tif\" can't be used", text "north-wall.tif is
|
|
||||||
14.2 MB. Images can be up to 10 MB.", confirm "Choose another file"; assert no `insertImage`
|
|
||||||
call.
|
|
||||||
|
|
||||||
## Visual (manual verification — desktop and mobile, light and dark)
|
## Visual
|
||||||
|
|
||||||
Reference: `docs/design/screens/editor.md` states "Upload: choose", "Upload: in progress",
|
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.
|
||||||
"Upload: rejected", "Upload: inserted", and `docs/design/source/RenewCMS Screens Back-
|
|
||||||
office.dc.html`. Run `task visual:check -- editor` for each state below; add each state's mock
|
|
||||||
setup to `web/visual/states.ts` first, reusing editor_core.qa.md's fixture article (id 12, title
|
|
||||||
"How we price a bathroom renovation", draft, "Today, 11:02", 3 images) plus the sample file data
|
|
||||||
from the board: filename "north-wall.jpg", size 3.9 MB, progress 62% / 2.4 of 3.9 MB uploaded.
|
|
||||||
|
|
||||||
- [ ] Upload: choose — modal "Add an image", idle state, cancel "Cancel".
|
|
||||||
- [ ] Upload: in progress — modal "Add an image", uploading "north-wall.jpg 62%" / "Uploading
|
|
||||||
2.4 of 3.9 MB", cancel "Cancel upload".
|
|
||||||
- [ ] Upload: rejected — modal "Add an image", rejected state for a sample rejected file per the
|
|
||||||
board's script, cancel "Cancel", confirm "Choose another file".
|
|
||||||
- [ ] Upload: inserted — toast "Image added" / "Save to keep it in the article.", editor status
|
|
||||||
"draft", save "dirty".
|
|
||||||
- [ ] Mobile (all of the above at 390×844): same modal layout constraints as other editor
|
|
||||||
modals (leading arrow-left button, trailing ellipsis in the header behind it).
|
|
||||||
- [ ] Keyboard/focus: the drop zone is reachable by Tab and Enter opens the file picker; focus
|
|
||||||
moves into the modal on open and is trapped there; Esc during "Upload: in progress"
|
|
||||||
behaves like "Cancel upload" (aborts, closes); the progress bar's `role="progressbar"` /
|
|
||||||
`aria-valuenow` updates are announced without spamming on every progress tick.
|
|
||||||
- [ ] Motion: modal open/close follows the standard 240 ms timing; the success state's 600 ms
|
|
||||||
auto-close is not visually checked as a capture (it's a timing behavior, not a static
|
|
||||||
state) — cover only via the Vitest fake-timer assertion above.
|
|
||||||
|
|
||||||
## Manual verification
|
## Manual verification
|
||||||
|
|
||||||
- **Real POST round trip against a running server** — Vitest only mocks `XMLHttpRequest`;
|
- **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`.
|
||||||
confirm a real upload (200/400/401/404/500) against `task dev` with a live SQLite file and the
|
- **Real OS drag and drop** of an image onto the editor in a real browser.
|
||||||
real `POST /v1/article/{id}/image` handler, since `features/upload_article_image.feature`'s
|
- **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.
|
||||||
httptest suite covers the handler in isolation but never through this SPA flow.
|
- **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.
|
||||||
- **Real drag-and-drop from the OS file picker** — jsdom's `drop` event is synthetic; confirm a
|
|
||||||
real OS-level drag of an image file onto the editor in a real browser.
|
|
||||||
@@ -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 |
|
||||||
@@ -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.
|
||||||
@@ -11,8 +11,8 @@ Feature: A logged-in user fetches their own public profile without triggering th
|
|||||||
Background:
|
Background:
|
||||||
Given the public user struct and its converter, shared by the auth and user handlers from a
|
Given the public user struct and its converter, shared by the auth and user handlers from a
|
||||||
package under api/pkg (features/user_display_name.feature), exactly the JSON shape
|
package under api/pkg (features/user_display_name.feature), exactly the JSON shape
|
||||||
POST /v1/auth/verify returns: id, username, email, is_verified, created_at, updated_at and
|
POST /v1/auth/verify returns: id, username, email, is_verified, created_at, updated_at,
|
||||||
display_name
|
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
|
||||||
@@ -43,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
|
||||||
|
|||||||
@@ -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).
|
||||||
|
|||||||
@@ -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
|
||||||
|
|||||||
Loaded 100 of 518 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user