Compare commits
17
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0d03a27f31 | ||
|
|
63c1e7076e | ||
|
|
04dc151ed7 | ||
|
|
a1cdfce529 | ||
|
|
c41e6dbca5 | ||
|
|
9d9453c1b3 | ||
|
|
54f27ac98f | ||
|
|
0632bf53cb | ||
|
|
fe254112a2 | ||
|
|
160c0a49ce | ||
|
|
e6746f2be7 | ||
|
|
6f9ae6207a | ||
|
|
03b39e64f2 | ||
|
|
73f4b539fe | ||
|
|
a2d224240c | ||
|
|
d6566743a7 | ||
|
|
10ec74c8cf |
No files matched your search
@@ -1,11 +1,11 @@
|
|||||||
root = "."
|
root = "."
|
||||||
tmp_dir = "tmp"
|
tmp_dir = "tmp/air"
|
||||||
|
|
||||||
[build]
|
[build]
|
||||||
cmd = "go build -tags nofrontend -o ./tmp/renewcms ./cmd/server"
|
cmd = "go build -tags nofrontend -o ./tmp/air/renewcms ./cmd/server"
|
||||||
bin = "tmp/renewcms"
|
bin = "tmp/air/renewcms"
|
||||||
delay = 500
|
delay = 500
|
||||||
exclude_dir = ["tmp", "bin", "data", "web", "features", "docs", "internal/infrastructure/assets/dist", ".claude"]
|
exclude_dir = ["tmp", "tmp/air", "bin", "data", "web", "features", "docs", "internal/infrastructure/assets/dist", ".claude"]
|
||||||
exclude_regex = ["_test.go"]
|
exclude_regex = ["_test.go"]
|
||||||
include_ext = ["go", "html"]
|
include_ext = ["go", "html"]
|
||||||
log = "build-errors.log"
|
log = "build-errors.log"
|
||||||
|
|||||||
@@ -23,7 +23,7 @@ docker compose pull
|
|||||||
docker compose up -d # http://localhost:8080
|
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)**.
|
Upgrade with `docker compose pull && docker compose up -d`. The image is `git.floriansylvain.fr/fsylvain/renewcms`. Every release is a pre-release for now, so the default tag is the moving `beta`. Pin a version with `RENEWCMS_IMAGE`. Tags, building from source and publishing are in **[docs/docker.md](docs/docker.md)**.
|
||||||
|
|
||||||
### Updates from the browser
|
### Updates from the browser
|
||||||
|
|
||||||
@@ -48,10 +48,10 @@ task dev # API with hot reload + Vite HMR → http://localhost:51
|
|||||||
| [docs/docker.md](docs/docker.md) | Running RenewCMS in Docker: image, Compose, data volume, backups, reverse proxy, tags, upgrades, publishing |
|
| [docs/docker.md](docs/docker.md) | Running RenewCMS in Docker: image, Compose, data volume, backups, reverse proxy, tags, upgrades, publishing |
|
||||||
| [docs/configuration.md](docs/configuration.md) | Every environment variable |
|
| [docs/configuration.md](docs/configuration.md) | Every environment variable |
|
||||||
| [docs/architecture.md](docs/architecture.md) | Backend layering and how the SPA is embedded |
|
| [docs/architecture.md](docs/architecture.md) | Backend layering and how the SPA is embedded |
|
||||||
|
| [docs/api.md](docs/api.md) | API reference: authentication, API keys, routes and the activity log |
|
||||||
## API Usage
|
| [docs/api/articles.md](docs/api/articles.md) | Reading articles: pagination, search, `format` and body schemas |
|
||||||
|
| [docs/image-variants.md](docs/image-variants.md) | Image variants and their cache |
|
||||||
TODO
|
| [docs/release-notes.md](docs/release-notes.md) | Release notes format, the published releases and how to publish one |
|
||||||
|
|
||||||
## TODOs
|
## TODOs
|
||||||
|
|
||||||
|
|||||||
@@ -32,7 +32,7 @@ type filterQuery struct {
|
|||||||
Category string `validate:"omitempty,oneof=articles media users api_keys auth system"`
|
Category string `validate:"omitempty,oneof=articles media users api_keys auth system"`
|
||||||
Outcome string `validate:"omitempty,oneof=all success failed"`
|
Outcome string `validate:"omitempty,oneof=all success failed"`
|
||||||
Security string `validate:"omitempty,oneof=true"`
|
Security string `validate:"omitempty,oneof=true"`
|
||||||
Range string `validate:"omitempty,oneof=today 7d 30d custom"`
|
Range string `validate:"omitempty,oneof=today 7d 30d all custom"`
|
||||||
From string `validate:"max=10"`
|
From string `validate:"max=10"`
|
||||||
To string `validate:"max=10"`
|
To string `validate:"max=10"`
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -11,7 +11,9 @@ import (
|
|||||||
"fmt"
|
"fmt"
|
||||||
"log"
|
"log"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
"net/url"
|
||||||
"strconv"
|
"strconv"
|
||||||
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/go-chi/chi/v5"
|
"github.com/go-chi/chi/v5"
|
||||||
@@ -28,7 +30,7 @@ type Handler struct {
|
|||||||
|
|
||||||
type PostArticle struct {
|
type PostArticle struct {
|
||||||
Title string `json:"title" validate:"required,min=3,max=200"`
|
Title string `json:"title" validate:"required,min=3,max=200"`
|
||||||
Body string `json:"body" validate:"required,max=10000"`
|
Body string `json:"body"`
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewHandler(create *useCases.CreateArticleUseCase, get *useCases.GetArticleUseCase, list *useCases.ListArticlesUseCase, delete *useCases.DeleteArticleUseCase, update *useCases.UpdateArticleUseCase, getUser *useCases.GetUserUseCase) *Handler {
|
func NewHandler(create *useCases.CreateArticleUseCase, get *useCases.GetArticleUseCase, list *useCases.ListArticlesUseCase, delete *useCases.DeleteArticleUseCase, update *useCases.UpdateArticleUseCase, getUser *useCases.GetUserUseCase) *Handler {
|
||||||
@@ -211,7 +213,7 @@ func (h *Handler) setIsOnline(w http.ResponseWriter, r *http.Request, isOnline b
|
|||||||
}
|
}
|
||||||
|
|
||||||
type UpdateArticleBody struct {
|
type UpdateArticleBody struct {
|
||||||
Body string `json:"body" validate:"required,max=10000"`
|
Body string `json:"body"`
|
||||||
}
|
}
|
||||||
|
|
||||||
func (h *Handler) UpdateArticleBody(w http.ResponseWriter, r *http.Request) {
|
func (h *Handler) UpdateArticleBody(w http.ResponseWriter, r *http.Request) {
|
||||||
@@ -268,26 +270,89 @@ func (h *Handler) callerIsVerified(r *http.Request) bool {
|
|||||||
return currentUser.IsVerified
|
return currentUser.IsVerified
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const (
|
||||||
|
defaultListPage = 1
|
||||||
|
defaultListSize = 25
|
||||||
|
)
|
||||||
|
|
||||||
|
type listQuery struct {
|
||||||
|
Page int `validate:"gte=1"`
|
||||||
|
Size int `validate:"oneof=5 25 50 100"`
|
||||||
|
Q string `validate:"max=200"`
|
||||||
|
Status string `validate:"omitempty,oneof=online draft"`
|
||||||
|
Sort string `validate:"oneof=title:asc title:desc status:asc status:desc created_at:asc created_at:desc updated_at:asc updated_at:desc"`
|
||||||
|
}
|
||||||
|
|
||||||
|
const defaultListSort = "updated_at:desc"
|
||||||
|
|
||||||
|
func parseSort(value string) domain.Sort {
|
||||||
|
field, direction, _ := strings.Cut(value, ":")
|
||||||
|
return domain.Sort{Field: domain.SortField(field), Direction: domain.SortDirection(direction)}
|
||||||
|
}
|
||||||
|
|
||||||
|
type listResponse struct {
|
||||||
|
Items []articleResponse `json:"items"`
|
||||||
|
Total int `json:"total"`
|
||||||
|
Page int `json:"page"`
|
||||||
|
Size int `json:"size"`
|
||||||
|
Counts domain.Counts `json:"counts"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func intQueryParam(values url.Values, name string, fallback int) (int, error) {
|
||||||
|
if !values.Has(name) {
|
||||||
|
return fallback, nil
|
||||||
|
}
|
||||||
|
return strconv.Atoi(values.Get(name))
|
||||||
|
}
|
||||||
|
|
||||||
|
func readListQuery(values url.Values) (listQuery, error) {
|
||||||
|
page, err := intQueryParam(values, "page", defaultListPage)
|
||||||
|
if err != nil {
|
||||||
|
return listQuery{}, err
|
||||||
|
}
|
||||||
|
size, err := intQueryParam(values, "size", defaultListSize)
|
||||||
|
if err != nil {
|
||||||
|
return listQuery{}, err
|
||||||
|
}
|
||||||
|
status := values.Get("status")
|
||||||
|
if values.Has("status") && status == "" {
|
||||||
|
return listQuery{}, errors.New("empty status")
|
||||||
|
}
|
||||||
|
sortValue := defaultListSort
|
||||||
|
if values.Has("sort") {
|
||||||
|
sortValue = values.Get("sort")
|
||||||
|
}
|
||||||
|
return listQuery{Page: page, Size: size, Q: values.Get("q"), Status: status, Sort: sortValue}, nil
|
||||||
|
}
|
||||||
|
|
||||||
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)
|
format, ok := parseBodyFormat(w, r)
|
||||||
if !ok {
|
if !ok {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
var articles []domain.Article
|
query, err := readListQuery(r.URL.Query())
|
||||||
var err error
|
if err != nil || validator.Validate.Struct(query) != nil {
|
||||||
if h.callerIsVerified(r) {
|
http.Error(w, apperr.BodyErrorMessage, http.StatusBadRequest)
|
||||||
articles, err = h.ListUseCase.ListAllArticles(format)
|
return
|
||||||
} else {
|
|
||||||
articles, err = h.ListUseCase.ListOnlineArticles(format)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
page, err := h.ListUseCase.ListArticlesPage(useCases.ListArticlesCommand{
|
||||||
|
Format: format,
|
||||||
|
Verified: h.callerIsVerified(r),
|
||||||
|
Page: query.Page,
|
||||||
|
Size: query.Size,
|
||||||
|
Q: query.Q,
|
||||||
|
Status: query.Status,
|
||||||
|
Sort: parseSort(query.Sort),
|
||||||
|
})
|
||||||
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
|
||||||
}
|
}
|
||||||
|
|
||||||
responses := make([]articleResponse, 0, len(articles))
|
responses := make([]articleResponse, 0, len(page.Items))
|
||||||
for _, article := range articles {
|
for _, article := range page.Items {
|
||||||
response, err := toArticleResponse(article, format)
|
response, err := toArticleResponse(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)
|
||||||
@@ -296,7 +361,7 @@ func (h *Handler) ListArticles(w http.ResponseWriter, r *http.Request) {
|
|||||||
responses = append(responses, response)
|
responses = append(responses, response)
|
||||||
}
|
}
|
||||||
|
|
||||||
articlesJson, err := json.Marshal(responses)
|
articlesJson, err := json.Marshal(listResponse{Items: responses, Total: page.Total, Page: page.Page, Size: page.Size, Counts: page.Counts})
|
||||||
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
|
||||||
|
|||||||
@@ -70,9 +70,23 @@ type countsResponse struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type listResponse struct {
|
type listResponse struct {
|
||||||
Items []mediaItemResponse `json:"items"`
|
Items []mediaItemResponse `json:"items"`
|
||||||
NextCursor *string `json:"next_cursor"`
|
Total int `json:"total"`
|
||||||
Counts countsResponse `json:"counts"`
|
Page int `json:"page"`
|
||||||
|
Size int `json:"size"`
|
||||||
|
Counts countsResponse `json:"counts"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type pagingQuery struct {
|
||||||
|
Page int `validate:"gte=1"`
|
||||||
|
Size int `validate:"oneof=5 25 50 100"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func intQueryParam(values url.Values, name string, fallback int) (int, error) {
|
||||||
|
if !values.Has(name) {
|
||||||
|
return fallback, nil
|
||||||
|
}
|
||||||
|
return strconv.Atoi(values.Get(name))
|
||||||
}
|
}
|
||||||
|
|
||||||
type usageResponse struct {
|
type usageResponse struct {
|
||||||
@@ -173,7 +187,6 @@ func parseListQuery(r *http.Request) (domainImage.ListQuery, error) {
|
|||||||
query := domainImage.NewListQuery()
|
query := domainImage.NewListQuery()
|
||||||
query.Search = values.Get("q")
|
query.Search = values.Get("q")
|
||||||
query.Hash = strings.ToLower(values.Get("hash"))
|
query.Hash = strings.ToLower(values.Get("hash"))
|
||||||
query.Cursor = values.Get("cursor")
|
|
||||||
if values.Has("filter") {
|
if values.Has("filter") {
|
||||||
query.Filter = domainImage.Filter(values.Get("filter"))
|
query.Filter = domainImage.Filter(values.Get("filter"))
|
||||||
}
|
}
|
||||||
@@ -186,13 +199,19 @@ func parseListQuery(r *http.Request) (domainImage.ListQuery, error) {
|
|||||||
if values.Has("sort") {
|
if values.Has("sort") {
|
||||||
query.Sort = domainImage.Sort(values.Get("sort"))
|
query.Sort = domainImage.Sort(values.Get("sort"))
|
||||||
}
|
}
|
||||||
if values.Has("limit") {
|
page, err := intQueryParam(values, "page", domainImage.DefaultListPage)
|
||||||
limit, err := strconv.Atoi(values.Get("limit"))
|
if err != nil {
|
||||||
if err != nil {
|
return domainImage.ListQuery{}, domainImage.ErrInvalidQuery
|
||||||
return domainImage.ListQuery{}, domainImage.ErrInvalidQuery
|
|
||||||
}
|
|
||||||
query.Limit = limit
|
|
||||||
}
|
}
|
||||||
|
size, err := intQueryParam(values, "size", domainImage.DefaultListSize)
|
||||||
|
if err != nil {
|
||||||
|
return domainImage.ListQuery{}, domainImage.ErrInvalidQuery
|
||||||
|
}
|
||||||
|
if validator.Validate.Struct(pagingQuery{Page: page, Size: size}) != nil {
|
||||||
|
return domainImage.ListQuery{}, domainImage.ErrInvalidQuery
|
||||||
|
}
|
||||||
|
query.Page = page
|
||||||
|
query.Size = size
|
||||||
return query, nil
|
return query, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -219,11 +238,11 @@ func (h *Handler) List(w http.ResponseWriter, r *http.Request) {
|
|||||||
}
|
}
|
||||||
response := listResponse{
|
response := listResponse{
|
||||||
Items: items,
|
Items: items,
|
||||||
|
Total: page.Total,
|
||||||
|
Page: page.Page,
|
||||||
|
Size: page.Size,
|
||||||
Counts: countsResponse{All: page.Counts.All, Unused: page.Counts.Unused, Duplicates: page.Counts.Duplicates},
|
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)
|
writeJSON(w, http.StatusOK, response)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+17
-6
@@ -2,7 +2,8 @@
|
|||||||
|
|
||||||
The full, searchable reference is the Integration page of the running app (`/integration`). It
|
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
|
renders `web/src/data/apiCatalogue.ts`, which is the single source for this page. This file is for
|
||||||
readers without the UI.
|
readers without the UI. Reading articles (pagination, `format`, body schemas) has its own page,
|
||||||
|
[api/articles.md](api/articles.md), and API keys are covered in [api/api-keys.md](api/api-keys.md).
|
||||||
|
|
||||||
## Base URL
|
## Base URL
|
||||||
The origin that serves the app, for example `https://cms.example`. Every path starts with `/v1`,
|
The origin that serves the app, for example `https://cms.example`. Every path starts with `/v1`,
|
||||||
@@ -40,7 +41,7 @@ key never reads the audit trail. Events are append-only; there is no `POST`, `PU
|
|||||||
|
|
||||||
Query: `q`, `actor` (`user:ID`, `key:ID`, `system`), `category` (`articles`, `media`, `users`,
|
Query: `q`, `actor` (`user:ID`, `key:ID`, `system`), `category` (`articles`, `media`, `users`,
|
||||||
`api_keys`, `auth`, `system`), `outcome` (`all`, `success`, `failed`), `security` (`true`), `range`
|
`api_keys`, `auth`, `system`), `outcome` (`all`, `success`, `failed`), `security` (`true`), `range`
|
||||||
(`today`, `7d`, `30d`, `custom`; default `7d`), `from` and `to` (dates, with `custom`), `page` (from
|
(`today`, `7d`, `30d`, `all`, `custom`; default `7d`), `from` and `to` (dates, with `custom`), `page` (from
|
||||||
1) and `size` (25, 50 or 100). Any invalid value answers 400 with the body-mismatch message. Dates
|
1) and `size` (25, 50 or 100). Any invalid value answers 400 with the body-mismatch message. Dates
|
||||||
are UTC. The list answers `{ items, total, page, size }`, newest first (`created_at`, then `id`).
|
are UTC. The list answers `{ items, total, page, size }`, newest first (`created_at`, then `id`).
|
||||||
|
|
||||||
@@ -96,10 +97,20 @@ try again."; the text of the error never reaches the event, the API or the CSV.
|
|||||||
codes, article bodies, file bytes, storage paths and asset urls are never recorded.
|
codes, article bodies, file bytes, storage paths and asset urls are never recorded.
|
||||||
|
|
||||||
Article routes accept `?format=markdown|html|json` (default `markdown`). `GET /v1/media/` accepts
|
Article routes accept `?format=markdown|html|json` (default `markdown`). `GET /v1/media/` accepts
|
||||||
`q`, `hash`, `cursor`, `filter`, `sort` (`newest`, `oldest`, `name`, `largest` or `total_size`, the
|
`q`, `hash`, `filter` (`all`, `unused` or `duplicates`), `sort` (`newest`, `oldest`, `name`,
|
||||||
original plus its generated variants), `variants` (`with` or `without` generated variant files) and
|
`largest` or `total_size`, the original plus its generated variants), `variants` (`with` or
|
||||||
`limit`. Every item carries `variant_count` and `variant_size` (the index rows of the image and
|
`without` generated variant files), `page` (a whole number from 1, default 1) and `size` (5, 25, 50
|
||||||
their bytes, 0 when none); `counts` stays library-wide. Any other `variants` or `sort` value is 400.
|
or 100, default 25). The body is `{ "items": [...], "total", "page", "size", "counts" }`: `total` is
|
||||||
|
the number of images matching `q`, `hash`, `filter` and `variants` before paging, `page` and `size`
|
||||||
|
echo the values applied, and `counts` (`all`, `unused`, `duplicates`) stays library-wide, ignoring
|
||||||
|
every filter and the paging. Ordering is applied to the whole matching list before slicing, with the
|
||||||
|
image id as the final tie-break, so pages never overlap or skip. A page past the last answers 200
|
||||||
|
with `items: []` and the real `total`. Any invalid `page`, `size`, `filter`, `sort`, `variants` or
|
||||||
|
`hash` is 400 "The media query is invalid.". Every item carries `variant_count` and `variant_size`
|
||||||
|
(the index rows of the image and their bytes, 0 when none).
|
||||||
|
|
||||||
|
Breaking change: `next_cursor` is gone and no `X-Total-Count` header is sent. `cursor` and `limit`
|
||||||
|
are no longer parameters; they are ignored, never an error, and have no effect on paging.
|
||||||
|
|
||||||
## Image variants
|
## Image variants
|
||||||
Owners and admins manage named variants of the stored images. These routes are session only (no API
|
Owners and admins manage named variants of the stored images. These routes are session only (no API
|
||||||
|
|||||||
@@ -13,6 +13,37 @@ Every route that returns an article accepts the optional `format` query paramete
|
|||||||
|
|
||||||
Visibility is unchanged: anonymous and unverified callers only see online articles, and an offline article answers `404 Article not found`.
|
Visibility is unchanged: anonymous and unverified callers only see online articles, and an offline article answers `404 Article not found`.
|
||||||
|
|
||||||
|
## Pagination, search and counts
|
||||||
|
|
||||||
|
`GET /v1/article/` always answers one page inside an envelope, with or without query parameters:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"items": [],
|
||||||
|
"total": 30,
|
||||||
|
"page": 1,
|
||||||
|
"size": 25,
|
||||||
|
"counts": { "all": 30, "online": 30, "draft": 0 }
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
| Parameter | Values | Default |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| `page` | integer >= 1 | `1` |
|
||||||
|
| `size` | `5`, `25`, `50` or `100` | `25` |
|
||||||
|
| `q` | up to 200 characters, matched anywhere in the title, ignoring case and accents | none |
|
||||||
|
| `status` | `online` or `draft` | none |
|
||||||
|
| `sort` | `title`, `status`, `created_at` or `updated_at`, then `:asc` or `:desc` (lowercase, for example `title:asc`) | `updated_at:desc` |
|
||||||
|
|
||||||
|
- `items` is `[]` when empty, never `null`. Each item is the article object below.
|
||||||
|
- Items follow `sort` (default `updated_at:desc`) across the whole list before paging. `title` ignores case, `status` orders on online state (`status:asc` puts drafts first), and every ordering ends with `id` descending so pages never overlap.
|
||||||
|
- `total` is the number of visible articles matching `q` and `status`, before paging. `page` and `size` echo the values applied.
|
||||||
|
- `counts` ignores `q` and `status`, so tab counts do not move while searching. For anonymous and unverified callers `all` equals `online` and `draft` is `0`, and `status=draft` answers `items: []` and `total: 0`.
|
||||||
|
- A page beyond the last answers `200` with `items: []` and the real `total`.
|
||||||
|
- An invalid `page`, `size`, `status`, `sort` or an over-long `q` answers `400` with the plain-text message `The request cannot be processed due to a mismatch in the format of the body.` An invalid `format` is reported first.
|
||||||
|
|
||||||
|
Breaking change: this route used to answer a bare JSON array. Clients must read the `items` property.
|
||||||
|
|
||||||
## The `format` parameter
|
## The `format` parameter
|
||||||
|
|
||||||
| Value | `body` | `body_format` |
|
| Value | `body` | `body_format` |
|
||||||
|
|||||||
@@ -27,7 +27,7 @@ routes.md · components.md · states.md · foundations.md · change-list.md · a
|
|||||||
| B6 Contrast and states matrix | Done for the pairs listed; matrix drawn |
|
| B6 Contrast and states matrix | Done for the pairs listed; matrix drawn |
|
||||||
| B7 Consistency sweep | Done for the roles listed |
|
| B7 Consistency sweep | Done for the roles listed |
|
||||||
| B8 Copy glossary | Done by search; not every line re-read |
|
| B8 Copy glossary | Done by search; not every line re-read |
|
||||||
| B9 Media and picker | Badge added; filter, sort and size not folded in |
|
| B9 Media and picker | Badge added; Media pagination drawn (9 states); filter, sort and size not folded in |
|
||||||
| B10 "proposed" labels | Only article pagination and JSON export |
|
| B10 "proposed" labels | Only article pagination and JSON export |
|
||||||
|
|
||||||
## State counts (Back-office board: 341)
|
## State counts (Back-office board: 341)
|
||||||
@@ -39,7 +39,7 @@ routes.md · components.md · states.md · foundations.md · change-list.md · a
|
|||||||
| Articles: pagination | 11 |
|
| Articles: pagination | 11 |
|
||||||
| New article | 5 |
|
| New article | 5 |
|
||||||
| Editor | 41 |
|
| Editor | 41 |
|
||||||
| Media | 43 |
|
| Media | 52 |
|
||||||
| Media picker | 13 |
|
| Media picker | 13 |
|
||||||
| Integration | 8 |
|
| Integration | 8 |
|
||||||
| Activity | 9 |
|
| Activity | 9 |
|
||||||
@@ -89,7 +89,7 @@ Back-office total 341. Auth board 50 (Log in 9, Register 6, Pending 6, Verify 6,
|
|||||||
## Defaults chosen
|
## Defaults chosen
|
||||||
- Slide-over rule: only forms with a live preview and record details; on mobile always a 92% bottom sheet.
|
- Slide-over rule: only forms with a live preview and record details; on mobile always a 92% bottom sheet.
|
||||||
- Hover, active, disabled and focus tokens for the matrix (components not specified before): primary hover `--ui-text`, active `--ui-text-toned`; destructive hover opacity 0.85 and active 0.75; disabled 40% (rows 55%).
|
- Hover, active, disabled and focus tokens for the matrix (components not specified before): primary hover `--ui-text`, active `--ui-text-toned`; destructive hover opacity 0.85 and active 0.75; disabled 40% (rows 55%).
|
||||||
- Article pagination stays "proposed" until the backend returns page, size and total.
|
- Article pagination: API shape (array body, total in `X-Total-Count`) is a design assumption to confirm with the specifier.
|
||||||
- The Remove action in the link popover has no confirmation; undo restores the link.
|
- The Remove action in the link popover has no confirmation; undo restores the link.
|
||||||
- The link button is disabled when an image is selected.
|
- The link button is disabled when an image is selected.
|
||||||
- The tooltip text is "Insert link (Ctrl+K)" and "Insert link (⌘K)" on macOS.
|
- The tooltip text is "Insert link (Ctrl+K)" and "Insert link (⌘K)" on macOS.
|
||||||
@@ -118,5 +118,4 @@ Back-office total 341. Auth board 50 (Log in 9, Register 6, Pending 6, Verify 6,
|
|||||||
- Contrast was not computed for every hover and active background, only the pairs listed in foundations.md.
|
- Contrast was not computed for every hover and active background, only the pairs listed in foundations.md.
|
||||||
- The glossary pass was a search for known patterns, not a line-by-line read of every string. Titles in Title Case were not searched.
|
- The glossary pass was a search for known patterns, not a line-by-line read of every string. Titles in Title Case were not searched.
|
||||||
- The Components, Handoff and Foundations boards were not updated to mention the new tokens, CodeSnippet or the matrix.
|
- The Components, Handoff and Foundations boards were not updated to mention the new tokens, CodeSnippet or the matrix.
|
||||||
- Integration still lists "max 10000" for article bodies, as the backend does today (change-list item 11).
|
|
||||||
- The sandbox cannot export; no files were bundled.
|
- The sandbox cannot export; no files were bundled.
|
||||||
@@ -16,7 +16,8 @@ Ordered by implementation dependency: tokens and shell first, then shared compon
|
|||||||
| 10 | New article | Title only. Body removed from the modal; the editor opens straight away | Yes | Maybe: confirm `POST /v1/article/` accepts an empty `body` (it is "required" today); otherwise the frontend sends an empty string | NewArticleModal | Yes if empty body is accepted |
|
| 10 | New article | Title only. Body removed from the modal; the editor opens straight away | Yes | Maybe: confirm `POST /v1/article/` accepts an empty `body` (it is "required" today); otherwise the frontend sends an empty string | NewArticleModal | Yes if empty body is accepted |
|
||||||
| 11 | Editor | Remove the 10,000 character limit, counter, limit and over-limit states; neutral count | Yes | Yes: remove the body length validation on `POST /v1/article/` and `PATCH /v1/article/{id}` | EditorStatusBar | No |
|
| 11 | Editor | Remove the 10,000 character limit, counter, limit and over-limit states; neutral count | Yes | Yes: remove the body length validation on `POST /v1/article/` and `PATCH /v1/article/{id}` | EditorStatusBar | No |
|
||||||
| 12 | Editor | Insert-link button (default, hover, active, disabled), tooltip, LinkModal, link popover and touch sheet, rendered link, toolbar scrolling at 390 px | Yes | No (editor only) | LinkModal, LinkPopover, ToolbarButton | Yes |
|
| 12 | Editor | Insert-link button (default, hover, active, disabled), tooltip, LinkModal, link popover and touch sheet, rendered link, toolbar scrolling at 390 px | Yes | No (editor only) | LinkModal, LinkPopover, ToolbarButton | Yes |
|
||||||
| 13 | Articles | Pagination with `page` and `size` (5, 25, 50, 100; default 25), URL state, loading, error, out of range | Yes | **Yes (proposed):** `GET /v1/article/` returns everything today. It needs `page`, `size` and `total` in the response | Paginator, PageSizeSelect | No |
|
| 13 | Articles | Pagination with `page` and `size` (5, 25, 50, 100; default 25), URL state, loading, error, out of range | Yes | **Yes:** `page`, `size` on `GET /v1/article/` (same convention and 400 as Activity); total in `X-Total-Count`, array body unchanged; Integration reference updated | Paginator, PageSizeSelect | No |
|
||||||
|
| 13b | Media | Pagination under the grid and list, same Paginator and PageSizeSelect as Articles; `page` and `size` in the URL; saved size preference | Yes (9 states in the Media group) | **Yes:** `page`, `size` on `GET /v1/media/` (replaces `cursor` and `limit`); total in `X-Total-Count`, array body unchanged; Integration reference | None (reuses Paginator, PageSizeSelect) | No |
|
||||||
| 14 | Activity | Failed-action and security cards as toggles, synced chip and segment | Yes | No | FilterCardToggle | Yes |
|
| 14 | Activity | Failed-action and security cards as toggles, synced chip and segment | Yes | No | FilterCardToggle | Yes |
|
||||||
| 15 | Activity | Export menu and dialog, CSV: current view (active filters) and all activity (no filters, optional `from`/`to`). Preparing, started, failed, nothing to export, 403 | Yes | No: `GET /v1/activity/export` is implemented (CSV, synchronous, owner and admin, same filters as the list) | ExportMenu, ExportDialog | Yes |
|
| 15 | Activity | Export menu and dialog, CSV: current view (active filters) and all activity (no filters, optional `from`/`to`). Preparing, started, failed, nothing to export, 403 | Yes | No: `GET /v1/activity/export` is implemented (CSV, synchronous, owner and admin, same filters as the list) | ExportMenu, ExportDialog | Yes |
|
||||||
| 16 | Activity | JSON export (format control CSV or JSON) | Yes, one state, labelled proposed | **Yes (proposed):** `format=json` on `GET /v1/activity/export` | Segmented format control | No |
|
| 16 | Activity | JSON export (format control CSV or JSON) | Yes, one state, labelled proposed | **Yes (proposed):** `format=json` on `GET /v1/activity/export` | Segmented format control | No |
|
||||||
|
|||||||
+11
-5
@@ -5,16 +5,22 @@
|
|||||||
| /settings | Settings (Version, Media card, Media cleanup, Retention) | none | GET/PATCH /v1/media/purge-settings, GET/PATCH /v1/settings |
|
| /settings | Settings (Version, Media card, Media cleanup, Retention) | none | GET/PATCH /v1/media/purge-settings, GET/PATCH /v1/settings |
|
||||||
| /settings/media/variants | Image variants (admin) | none | GET/PATCH/DELETE /v1/image-variants, POST /v1/image-variants/{name}/purge |
|
| /settings/media/variants | Image variants (admin) | none | GET/PATCH/DELETE /v1/image-variants, POST /v1/image-variants/{name}/purge |
|
||||||
| /settings/media/cache | Cache (admin) | none | GET /v1/image-variants/cache, POST /v1/image-variants/cache/purge {scope: all|unused|variant|image} |
|
| /settings/media/cache | Cache (admin) | none | GET /v1/image-variants/cache, POST /v1/image-variants/cache/purge {scope: all|unused|variant|image} |
|
||||||
| /media | Media library | filter, sort | GET /v1/media?variants=with|without&sort=total_size |
|
| /media | Media library | page, size, q, filter, sort, view | GET /v1/media/?page=&size=&q=&filter=&variants=&sort= (page, size; total in the `X-Total-Count` header) |
|
||||||
| /media (detail) | Variants tab | none | GET /v1/media/{id}/variants, POST and DELETE /v1/media/{id}/variants/{name} |
|
| /media (detail) | Variants tab | none | GET /v1/media/{id}/variants, POST and DELETE /v1/media/{id}/variants/{name} |
|
||||||
| /articles | Articles list | page, size, tab, q | GET /v1/article/?page=&size=&q=&status= (proposed: needs backend page, size and total in the response) |
|
| /articles | Articles list | page, size, tab, q | GET /v1/article/?page=&size=&q=&status= (page, size; total in the `X-Total-Count` header; array body unchanged) |
|
||||||
| /activity | Activity | q, actor, category, outcome, security, range, from, to, page, size | GET /v1/activity (page, size), GET /v1/activity/export (shipped, CSV) |
|
| /activity | Activity | q, actor, category, outcome, security, range, from, to, page, size | GET /v1/activity (page, size), GET /v1/activity/export (shipped, CSV) |
|
||||||
| /integration | Integration | none | none |
|
| /integration | Integration | none | none |
|
||||||
| /integration/api-keys | API keys | none | GET/POST /v1/api-key, DELETE /v1/api-key/{id} |
|
| /integration/api-keys | API keys | none | GET/POST /v1/api-key, DELETE /v1/api-key/{id} |
|
||||||
|
|
||||||
## Pagination in the URL (Articles)
|
## Pagination in the URL (Articles, Media)
|
||||||
`/articles?page=2&size=50`. Parameter names follow the repo (activity already uses `page` and `size`). Allowed sizes 5, 25, 50, 100. Defaults `page=1`, `size=25`, omitted from the URL when default. Changing search, tab, filter or size resets `page` to 1. `page` above the last page redirects (replace) to the last page and shows "That page doesn't exist. Showing the last page." An invalid `size` falls back to 25.
|
`/articles?page=2&size=50` and `/media?page=7&size=50`. Parameter names follow the repo (activity already uses `page` and `size`). Allowed sizes 5, 25, 50, 100. Defaults `page=1`, `size=25`, omitted from the URL when default. Changing search, tab, filter or size resets `page` to 1. `page` above the last page redirects (replace) to the last page and shows "That page doesn't exist. Showing the last page." An invalid `size` falls back to 25.
|
||||||
**Proposed, needs backend:** `GET /v1/article/` currently returns every article. It must accept `page` and `size` and return `total` (and the page) in the response.
|
**API:** `GET /v1/article/` accepts `page` (default 1) and `size` (5, 25, 50, 100; default 25), as `GET /v1/activity` does. The body stays a JSON array so existing consumers keep working; the total comes back in `X-Total-Count` (the response shape is to be confirmed with the specifier). Anonymous callers only see online articles, and the total counts only those. Invalid `page` or `size` answers 400, the same as Activity.
|
||||||
|
|
||||||
|
**Media API:** `GET /v1/media/` takes the same `page` and `size`, with the same 400 and the total in `X-Total-Count`; the array body stays. The earlier `cursor` and `limit` parameters are replaced by them.
|
||||||
|
|
||||||
|
**Page size memory:** the size chosen on Articles, Activity or Media is remembered for the user and used when the URL has no `size`; an explicit `size` in the URL wins.
|
||||||
|
|
||||||
|
**SPA:** never shows that 400. A `size` outside 5, 25, 50, 100 or a `page` that is not a positive integer is replaced in the URL by the default (`history.replace`), silently. A `page` past the last page is replaced by the last page and the notice "That page doesn't exist. Showing the last page." appears.
|
||||||
|
|
||||||
## Activity pagination
|
## Activity pagination
|
||||||
`page` and `size`, allowed sizes 5, 25, 50, 100, default 25 (as implemented).
|
`page` and `size`, allowed sizes 5, 25, 50, 100, default 25 (as implemented).
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
# Articles
|
# Articles
|
||||||
|
|
||||||
Route: `/article`, `/articles?page=2&size=50`. API: GET /v1/article/ · PATCH …/publish · PATCH …/unpublish · DELETE /v1/article/{id} · GET /v1/article/?page=&size=&q=&status= (proposed: needs backend page, size, total in the response).
|
Route: `/article`, `/articles?page=2&size=50`. API: GET /v1/article/ · PATCH …/publish · PATCH …/unpublish · DELETE /v1/article/{id} · GET /v1/article/?page=&size=&q=&status= (page, size; total in the X-Total-Count header; invalid values are normalised in the URL, never shown as an error).
|
||||||
|
|
||||||
Rows update when the server responds, not optimistically. Search, tab and sort are stored in the query string.
|
Rows update when the server responds, not optimistically. Search, tab and sort are stored in the query string.
|
||||||
|
|
||||||
@@ -52,7 +52,7 @@ Rows update when the server responds, not optimistically. Search, tab and sort a
|
|||||||
|
|
||||||
### Articles: pagination (group "Articles: pagination", 11 states)
|
### Articles: pagination (group "Articles: pagination", 11 states)
|
||||||
|
|
||||||
Route: `/articles?page=2&size=50`. API: GET /v1/article/?page=&size=&q=&status= (proposed: needs backend page, size, total in the response).
|
Route: `/articles?page=2&size=50`. API: GET /v1/article/?page=&size=&q=&status= (page, size; total in the X-Total-Count header; invalid values are normalised in the URL, never shown as an error).
|
||||||
|
|
||||||
Page and page size live in the URL as page and size. Defaults (page 1, size 25) are omitted. Allowed sizes 5, 25, 50, 100. Search, tab or sort changes reset to page 1. Rows equal the page size; the frames draw at most 10 rows. The paginator hides when everything fits on one page; the summary stays. Mobile shows Previous, "Page N of M" and Next. Keyboard: Tab reaches page size, first, previous, each page, next, last; Enter or Space activates; the current page has aria-current="page"; ArrowDown opens the page-size list, Enter selects, Esc closes.
|
Page and page size live in the URL as page and size. Defaults (page 1, size 25) are omitted. Allowed sizes 5, 25, 50, 100. Search, tab or sort changes reset to page 1. Rows equal the page size; the frames draw at most 10 rows. The paginator hides when everything fits on one page; the summary stays. Mobile shows Previous, "Page N of M" and Next. Keyboard: Tab reaches page size, first, previous, each page, next, last; Enter or Space activates; the current page has aria-current="page"; ArrowDown opens the page-size list, Enter selects, Esc closes.
|
||||||
|
|
||||||
|
|||||||
@@ -42,8 +42,8 @@ Plain text, one sentence. Used in the table and in the per-endpoint error captio
|
|||||||
- 413 and 415 on `POST /v1/media/` keep their earlier plain captions; no real message is known.
|
- 413 and 415 on `POST /v1/media/` keep their earlier plain captions; no real message is known.
|
||||||
|
|
||||||
## Request bodies
|
## Request bodies
|
||||||
- `POST /v1/article/`: `title` (string, required, 3 to 200 characters), `body` (string, required, max 10000 today; the limit is being removed, see change-list.md item 3).
|
- `POST /v1/article/`: `title` (string, required, 3 to 200 characters), `body` (string, optional, no length limit).
|
||||||
- `PATCH /v1/article/{id}`: `body` (string, required, max 10000 today; same).
|
- `PATCH /v1/article/{id}`: `body` (string, optional, no length limit).
|
||||||
- `PATCH /v1/media/{id}` (rename): `filename` (string, required).
|
- `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/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").
|
- `POST /v1/media/`: multipart/form-data, 1 file field (shown as "multipart/form-data, 1 file field").
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
# Media
|
# Media
|
||||||
|
|
||||||
Route: `/media`, `/media (detail panel)`, `/media?filter=duplicates`. API: GET /v1/media/ · POST /v1/media/ · PATCH /v1/media/{id} · DELETE /v1/media/{id} · POST /v1/media/merge · GET /v1/media/{id}/usage · GET /v1/media?variants=with|without&sort=total_size · GET /v1/media/{id}/variants · POST /v1/media/{id}/variants/{name} · DELETE /v1/media/{id}/variants/{name} · owner and admin only.
|
Route: `/media`, `/media?page=7&size=50`, `/media (detail panel)`, `/media?filter=duplicates`. API: GET /v1/media/?page=&size=&q=&filter= (total in `X-Total-Count`) · POST /v1/media/ · PATCH /v1/media/{id} · DELETE /v1/media/{id} · POST /v1/media/merge · GET /v1/media/{id}/usage · GET /v1/media?variants=with|without&sort=total_size · GET /v1/media/{id}/variants · POST /v1/media/{id}/variants/{name} · DELETE /v1/media/{id}/variants/{name} · owner and admin only.
|
||||||
|
|
||||||
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").
|
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").
|
||||||
|
|
||||||
@@ -10,7 +10,7 @@ Visual reference: `RenewCMS Screens Back-office.dc.html`, groups "Media", "Media
|
|||||||
|
|
||||||
Every state below is drawn in light and dark (theme switch on the board), at 1440×900 and 390×844 (both frames sit side by side). Board: `RenewCMS Screens Back-office.dc.html`. Copy is exact; where a cell is empty the state reuses the fixed copy.
|
Every state below is drawn in light and dark (theme switch on the board), at 1440×900 and 390×844 (both frames sit side by side). Board: `RenewCMS Screens Back-office.dc.html`. Copy is exact; where a cell is empty the state reuses the fixed copy.
|
||||||
|
|
||||||
### Media (group "Media", 43 states)
|
### Media (group "Media", 52 states)
|
||||||
|
|
||||||
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.
|
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.
|
||||||
|
|
||||||
@@ -18,7 +18,7 @@ New route for verified users, in the sidebar between Articles and Users with the
|
|||||||
|
|
||||||
| # | State | Trigger | Copy |
|
| # | State | Trigger | Copy |
|
||||||
|---|---|---|---|
|
|---|---|---|---|
|
||||||
| 1 | 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. | |
|
| 1 | 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. Below the grid: "Showing 1–12 of 12" and the page-size select (same paginator as Articles). | |
|
||||||
| 2 | Grid, few images | Three images. Cards keep their size instead of stretching. Checkerboard shows behind the SVG. | |
|
| 2 | Grid, few images | Three images. Cards keep their size instead of stretching. Checkerboard shows behind the SVG. | |
|
||||||
| 3 | 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. | |
|
| 3 | 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. | |
|
||||||
| 4 | Loading | The first load, a retry, or a change of search or filter. Skeleton cards appear after 150 ms. | |
|
| 4 | Loading | The first load, a retry, or a change of search or filter. Skeleton cards appear after 150 ms. | |
|
||||||
@@ -61,6 +61,15 @@ New route for verified users, in the sidebar between Articles and Users with the
|
|||||||
| 41 | Merge: done | 200: the group leaves the list. When it was the last one, "No duplicates" shows. | "Copies merged" / "2 copies merged. 5 articles updated." |
|
| 41 | Merge: done | 200: the group leaves the list. When it was the last one, "No duplicates" shows. | "Copies merged" / "2 copies merged. 5 articles updated." |
|
||||||
| 42 | List failed to load | A 500 or network failure on the list request. The alert replaces the images; Try again repeats the request. | |
|
| 42 | List failed to load | A 500 or network failure on the list request. The alert replaces the images; Try again repeats the request. | |
|
||||||
| 43 | Offline | navigator.onLine is false. Loaded images stay browsable. Upload, Rename, Delete and Merge are disabled, and the banner says why. | |
|
| 43 | Offline | navigator.onLine is false. Loaded images stay browsable. Upload, Rename, Delete and Merge are disabled, and the banner says why. | |
|
||||||
|
| 44 | Pagination: first page | /media. Previous and First are disabled. Summary "Showing 1–25 of 312". The paginator sits under the grid or list and uses the Articles controls: 5, 25, 50 or 100 per page, default 25; page and size live in the URL as page and size (/media?page=7&size=50); search, tab, sort, view and size changes reset to page 1. API: GET /v1/media/?page=&size=&q=&filter= with the total in X-Total-Count. | |
|
||||||
|
| 45 | Pagination: middle page | /media?page=7. Current page uses --rc-sand and --rc-on-sand; ellipses mark skipped ranges. | |
|
||||||
|
| 46 | Pagination: last page | /media?page=13. Next and Last are disabled. Summary "Showing 301–312 of 312". | |
|
||||||
|
| 47 | Pagination: list view | Same paginator under the table. On mobile: Previous, "Page 2 of 13", Next, with the 44 px targets. | |
|
||||||
|
| 48 | Pagination: loading next page | Next was pressed. Skeleton cards keep the grid height, controls are disabled, summary reads "Loading page 7…". | |
|
||||||
|
| 49 | Pagination: error loading a page | 500 or network failure on page change. Previous images stay; Retry sits in the notice. | "Couldn't load page 7. Showing page 6." |
|
||||||
|
| 50 | Pagination: page out of range | /media?page=99 is replaced with ?page=13 and this notice is shown. | "That page doesn't exist. Showing the last page." |
|
||||||
|
| 51 | Pagination: page size menu | The select opens upward. 5, 25, 50 or 100; the chosen size is saved as size and the page resets to 1. | |
|
||||||
|
| 52 | Pagination: focus-visible | Keyboard focus on Next: 2 px --ui-primary outline, 2 px offset. Same ring on every paginator control. | |
|
||||||
|
|
||||||
### 3. Media library (group "Media library", 6 states)
|
### 3. Media library (group "Media library", 6 states)
|
||||||
|
|
||||||
|
|||||||
@@ -20,6 +20,6 @@ Recommendation: a modal. Title is the only field. The body is not asked for here
|
|||||||
|---|---|---|---|
|
|---|---|---|---|
|
||||||
| 1 | Default | "New article" from Home, Articles or the empty state. | |
|
| 1 | Default | "New article" from Home, Articles or the empty state. | |
|
||||||
| 2 | Validation | On submit or blur. Nothing is sent. | "Use at least 3 characters." |
|
| 2 | Validation | On submit or blur. Nothing is sent. | "Use at least 3 characters." |
|
||||||
| 3 | Submitting | Request in flight. Fields are disabled and the dialog can't be dismissed. | "Creating…" / "Choosing tiles for a small bathroom" / "Small rooms show every grout line, so we start with the floor." |
|
| 3 | Submitting | Request in flight. Fields are disabled and the dialog can't be dismissed. | "Creating…" / "Choosing tiles for a small bathroom" |
|
||||||
| 4 | Title rejected (400) | A server 400 that got past the browser checks. The raw error isn't shown. | "Something in the form isn't valid. Check the highlighted fields." / "Choosing tiles for a small bathroom" / "Small rooms show every grout line, so we start with the floor." / "Check this title and try again." |
|
| 4 | Title rejected (400) | A server 400 that got past the browser checks. The raw error isn't shown. | "Something in the form isn't valid. Check the highlighted fields." / "Choosing tiles for a small bathroom" / "Check this title and try again." |
|
||||||
| 5 | Error | 500 or network failure. | "Couldn't create the article. Your text is still here. Try again in a moment." / "Choosing tiles for a small bathroom" / "Small rooms show every grout line, so we start with the floor." |
|
| 5 | Error | 500 or network failure. | "Couldn't create the article. Your text is still here. Try again in a moment." / "Choosing tiles for a small bathroom" |
|
||||||
@@ -179,7 +179,7 @@ class Component extends DCLogic {
|
|||||||
const j = o => JSON.stringify(o, null, 2)
|
const j = o => JSON.stringify(o, null, 2)
|
||||||
const G = {
|
const G = {
|
||||||
articles: { title: 'Articles', desc: 'Read, write and publish articles. Titles can\'t be changed after creation.', eps: [
|
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-list', 'GET', '/v1/article/', 'List articles, one page at a time. Anonymous callers get online articles only, and the total counts only those. The total is in the X-Total-Count response header; the body stays a JSON array.', 'Public', 1, [[400, 'Invalid page or size.'], e401], [S('page', 'integer', 'No', '1 or higher. Default 1. A page past the end returns an empty array.'), S('size', 'integer', 'No', 'One of 5, 25, 50 or 100. Default 25.')], { qp: 1, 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-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', 'No', 'Optional. Any length.')], { body: { title: 'Choosing tiles for a small bathroom' }, r: j({ id: 13, status: 'draft' }) }),
|
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', 'No', 'Optional. Any length.')], { body: { title: 'Choosing tiles for a small bathroom' }, 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', 'Any length.')], { body: { body: 'Updated text.' }, r: j({ id: 12, 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', 'Any length.')], { body: { body: 'Updated text.' }, r: j({ id: 12, status: 'draft' }) }),
|
||||||
@@ -232,7 +232,7 @@ class Component extends DCLogic {
|
|||||||
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 })]
|
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,
|
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] } })),
|
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,
|
bodyTitle: e.qp ? 'Query parameters' : 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 } })) } }),
|
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 } })) } }),
|
||||||
snips: [{ k: 'fetch', label: 'fetch', code: fe }, { k: 'curl', label: 'curl', code: curl }, { k: 'response', label: 'Response', code: e.r }],
|
snips: [{ k: 'fetch', label: 'fetch', code: fe }, { k: 'curl', label: 'curl', code: curl }, { k: 'response', label: 'Response', code: e.r }],
|
||||||
errs: e.errs.map(([c, cap]) => ({ c, cap })) }
|
errs: e.errs.map(([c, cap]) => ({ c, cap })) }
|
||||||
|
|||||||
@@ -142,6 +142,36 @@ class Component extends DCLogic {
|
|||||||
|
|
||||||
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 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 Pager = () => {
|
||||||
|
const g = { page: 1, per: 25, total: imgs.length, ...(s.pg || {}) }
|
||||||
|
g.pages = g.pages || Math.max(1, Math.ceil(g.total / g.per))
|
||||||
|
const busy = !!g.loading, ring = k => g.focus === k ? 'outline:2px solid var(--ui-primary);outline-offset:2px;' : ''
|
||||||
|
const fmt = n => String(n).replace(/\B(?=(\d{3})+(?!\d))/g, ',')
|
||||||
|
const from = g.total ? (g.page - 1) * g.per + 1 : 0, to = Math.min(g.page * g.per, g.total)
|
||||||
|
const back = busy || g.page === 1 ? 0.4 : 1, fwd = busy || g.page === g.pages ? 0.4 : 1
|
||||||
|
const PB = (ic, op, rg, label) => S('width:' + bh + 'px;height:' + bh + 'px;display:flex;align-items:center;justify-content:center;border:1px solid var(--ui-border-accented);background:var(--ui-bg);color:var(--ui-text-highlighted);opacity:' + op + ';' + (rg || ''), I(ic))
|
||||||
|
const set = new Set([1, g.pages, g.page - 1, g.page, g.page + 1].filter(n => n >= 1 && n <= g.pages))
|
||||||
|
const arr = g.pages <= 7 ? Array.from({ length: g.pages }, (_, i) => i + 1) : [...set].sort((a, b) => a - b)
|
||||||
|
const nums = []
|
||||||
|
arr.forEach((n, i) => {
|
||||||
|
if (i && n - arr[i - 1] > 1) nums.push(S('min-width:' + bh + 'px;height:' + bh + 'px;display:flex;align-items:center;justify-content:center;color:var(--ui-text-muted)', '…'))
|
||||||
|
const cur = n === g.page
|
||||||
|
nums.push(S('min-width:' + bh + 'px;height:' + bh + 'px;padding:0 6px;display:flex;align-items:center;justify-content:center;border:1px solid ' + (cur ? 'var(--ui-primary)' : 'var(--ui-border-accented)') + ';background:' + (cur ? 'var(--rc-sand)' : 'var(--ui-bg)') + ';color:' + (cur ? 'var(--rc-on-sand)' : 'var(--ui-text-highlighted)') + ';font-weight:' + (cur ? 600 : 400), String(n)))
|
||||||
|
})
|
||||||
|
const Size = () => D('position:relative', S('height:' + bh + 'px;padding:0 8px 0 12px;display:flex;align-items:center;gap:8px;border:1px solid var(--ui-border-accented);background:var(--ui-bg);color:var(--ui-text-highlighted);' + ring('size'), g.per + ' per page', I('chevron-down', 14)),
|
||||||
|
g.sizeOpen && D('position:absolute;' + (m ? 'right' : 'left') + ':0;bottom:calc(100% + 4px);z-index:40;width:160px;background:var(--ui-bg);border:1px solid var(--ui-border);box-shadow:var(--rc-shadow-pop);padding:4px', ...[5, 25, 50, 100].map(n => D('height:' + bh + 'px;padding:0 8px;display:flex;align-items:center;background:' + (n === g.per ? 'var(--rc-sand)' : 'transparent') + ';color:' + (n === g.per ? 'var(--rc-on-sand)' : 'var(--ui-text-highlighted)') + ';font-weight:' + (n === g.per ? 600 : 400), n + ' per page'))))
|
||||||
|
const sum = S('color:var(--ui-text-muted)', busy ? 'Loading page ' + g.loading + '…' : 'Showing ' + from + '–' + to + ' of ' + fmt(g.total))
|
||||||
|
const out = []
|
||||||
|
if (g.err) out.push(Alert('error', 'circle-x', g.err, 'Check your connection and try again.', 'Retry'))
|
||||||
|
if (g.note) out.push(Alert('info', 'info', g.note))
|
||||||
|
if (m) {
|
||||||
|
out.push(D('display:flex;flex-direction:column;gap:12px;padding:4px 0 16px', D('display:flex;align-items:center;gap:12px;flex-wrap:wrap;justify-content:space-between', sum, Size()),
|
||||||
|
g.pages > 1 && D('display:flex;align-items:center;gap:8px', S('flex:1;height:44px;display:flex;align-items:center;justify-content:center;gap:6px;border:1px solid var(--ui-border-accented);background:var(--ui-bg);color:var(--ui-text-highlighted);font-weight:500;opacity:' + back + ';' + ring('prev'), I('chevron-left'), 'Previous'), S('padding:0 4px;color:var(--ui-text-highlighted);font-weight:500;white-space:nowrap', 'Page ' + g.page + ' of ' + g.pages), S('flex:1;height:44px;display:flex;align-items:center;justify-content:center;gap:6px;border:1px solid var(--ui-border-accented);background:var(--ui-bg);color:var(--ui-text-highlighted);font-weight:500;opacity:' + fwd + ';' + ring('next'), 'Next', I('chevron-right')))))
|
||||||
|
} else {
|
||||||
|
out.push(D('display:flex;align-items:center;gap:16px', D('flex:1;display:flex;align-items:center;gap:16px', sum, Size()), g.pages > 1 && D('display:flex;align-items:center;gap:4px;justify-content:flex-end', PB('chevrons-left', back), PB('chevron-left', back, ring('prev')), ...nums, PB('chevron-right', fwd, ring('next')), PB('chevrons-right', fwd))))
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
const pageBody = () => {
|
const pageBody = () => {
|
||||||
const parts = []
|
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.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 }
|
||||||
@@ -153,12 +183,13 @@ class Component extends DCLogic {
|
|||||||
: 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(), pb, 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(), pb, Toggle()))
|
||||||
parts.push(tb)
|
parts.push(tb)
|
||||||
if (UP) parts.push(UpPanel())
|
if (UP) parts.push(UpPanel())
|
||||||
if (s.loading) parts.push(Skel())
|
if (s.loading) { parts.push(Skel()); if (s.pg) parts.push(...Pager()) }
|
||||||
else if (s.error) { }
|
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 (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 (tab === 'dups') parts.push(s.dupEmpty ? Empty('copy', 'No duplicates', 'Every image in your library is different.', 'Back to all images', false) : Groups())
|
||||||
else {
|
else {
|
||||||
if (view === 'grid') parts.push(SelectAll(), Grid()); else parts.push(m ? Cards() : Table())
|
if (view === 'grid') parts.push(SelectAll(), Grid()); else parts.push(m ? Cards() : Table())
|
||||||
|
parts.push(...Pager())
|
||||||
}
|
}
|
||||||
return parts
|
return parts
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -205,7 +205,7 @@ class Component extends DCLogic {
|
|||||||
withM({ ...L({ modal: del(false, 'Couldn\'t delete the article, so it\'s still there. Try again in a moment.') }), name: 'Delete: failed', trigger: '500, a partial failure where the article is kept. The error shows inside the dialog.' }),
|
withM({ ...L({ modal: del(false, 'Couldn\'t delete the article, so it\'s still there. Try again in a moment.') }), name: 'Delete: failed', trigger: '500, a partial failure where the article is kept. The error shows inside the dialog.' }),
|
||||||
withM({ ...L({ list: { counts: [5, 4, 1], rows: rows().filter((r, i) => i !== 3) }, toasts: [T('success', 'circle-check', 'Article deleted', '"Winter checklist for timber windows" and its images are gone.')] }), name: 'Deleted', trigger: '204: the row is removed and focus moves to the next row. This is also where a delete from the editor ends up.' })
|
withM({ ...L({ list: { counts: [5, 4, 1], rows: rows().filter((r, i) => i !== 3) }, toasts: [T('success', 'circle-check', 'Article deleted', '"Winter checklist for timber windows" and its images are gone.')] }), name: 'Deleted', trigger: '204: the row is removed and focus moves to the next row. This is also where a delete from the editor ends up.' })
|
||||||
] },
|
] },
|
||||||
{ label: 'Articles: pagination', title: 'Articles: pagination', route: '/articles?page=2&size=50', api: 'GET /v1/article/?page=&size=&q=&status= (proposed: needs backend page, size, total in the response)', note: 'Page and page size live in the URL as page and size. Defaults (page 1, size 25) are omitted. Allowed sizes 5, 25, 50, 100. Search, tab or sort changes reset to page 1. Rows equal the page size; the frames draw at most 10 rows. The paginator hides when everything fits on one page; the summary stays. Mobile shows Previous, "Page N of M" and Next. Keyboard: Tab reaches page size, first, previous, each page, next, last; Enter or Space activates; the current page has aria-current="page"; ArrowDown opens the page-size list, Enter selects, Esc closes.', states: [
|
{ label: 'Articles: pagination', title: 'Articles: pagination', route: '/articles?page=2&size=50', api: 'GET /v1/article/?page=&size=&q=&status= (page, size; total in the X-Total-Count header; invalid values are normalised in the URL, never shown as an error)', note: 'Page and page size live in the URL as page and size. Defaults (page 1, size 25) are omitted. Allowed sizes 5, 25, 50, 100. Search, tab or sort changes reset to page 1. Rows equal the page size; the frames draw at most 10 rows. The paginator hides when everything fits on one page; the summary stays. Mobile shows Previous, "Page N of M" and Next. Keyboard: Tab reaches page size, first, previous, each page, next, last; Enter or Space activates; the current page has aria-current="page"; ArrowDown opens the page-size list, Enter selects, Esc closes.', states: [
|
||||||
withM({ ...PG({ page: 1 }), name: 'First page', trigger: '/articles. Previous and First are disabled. Summary "Showing 1–25 of 312".' }),
|
withM({ ...PG({ page: 1 }), name: 'First page', trigger: '/articles. Previous and First are disabled. Summary "Showing 1–25 of 312".' }),
|
||||||
withM({ ...PG({ page: 7 }), name: 'Middle page', trigger: '/articles?page=7. Current page uses --rc-sand and --rc-on-sand; ellipses mark skipped ranges.' }),
|
withM({ ...PG({ page: 7 }), name: 'Middle page', trigger: '/articles?page=7. Current page uses --rc-sand and --rc-on-sand; ellipses mark skipped ranges.' }),
|
||||||
withM({ ...PG({ page: 13 }), name: 'Last page', trigger: '/articles?page=13. Next and Last are disabled. Summary "Showing 301–312 of 312".' }),
|
withM({ ...PG({ page: 13 }), name: 'Last page', trigger: '/articles?page=13. Next and Last are disabled. Summary "Showing 301–312 of 312".' }),
|
||||||
@@ -269,7 +269,16 @@ class Component extends DCLogic {
|
|||||||
E({ notfound: true }, { name: 'Not found (404)', trigger: 'Unknown id, or the article was deleted elsewhere.' })
|
E({ notfound: true }, { name: 'Not found (404)', trigger: 'Unknown id, or the article was deleted elsewhere.' })
|
||||||
] },
|
] },
|
||||||
{ label: 'Media', title: 'Media', route: '/media', api: 'GET /v1/media/ · POST /v1/media/ · PATCH /v1/media/{id} · DELETE /v1/media/{id} · POST /v1/media/merge · GET /v1/media/{id}/usage', note: 'New route for verified users, in the sidebar between Articles and Users with the images icon. Images belong to the library, not to an article: one image can be used in many articles, and deleting an article never deletes images. Uploads from this page are not cropped or resized, and the file is stored as chosen. "Used in" is read from article bodies each time the list loads. Duplicates are images with identical content, whatever their filenames. Alt text is not stored on the image; it is set when inserting into an article. Search, filter, sort and view are stored in the query string. Keyboard: grid items are buttons in one tab stop each; Enter opens the detail panel, Space toggles selection, and Escape closes the panel or clears the selection. Selection changes are announced ("north-wall.jpg selected, 1 selected").', states: [
|
{ label: 'Media', title: 'Media', route: '/media', api: 'GET /v1/media/ · POST /v1/media/ · PATCH /v1/media/{id} · DELETE /v1/media/{id} · POST /v1/media/merge · GET /v1/media/{id}/usage', note: 'New route for verified users, in the sidebar between Articles and Users with the images icon. Images belong to the library, not to an article: one image can be used in many articles, and deleting an article never deletes images. Uploads from this page are not cropped or resized, and the file is stored as chosen. "Used in" is read from article bodies each time the list loads. Duplicates are images with identical content, whatever their filenames. Alt text is not stored on the image; it is set when inserting into an article. Search, filter, sort and view are stored in the query string. Keyboard: grid items are buttons in one tab stop each; Enter opens the detail panel, Space toggles selection, and Escape closes the panel or clears the selection. Selection changes are announced ("north-wall.jpg selected, 1 selected").', states: [
|
||||||
Mp({ name: 'Grid, many images', trigger: 'Default view. 12 images, newest first. Each item is a button labelled like "north-wall.jpg, 3.9 MB, used in 2 articles". Badges: "Unused" (warm), "Duplicate" (info), "Used in N" (outline). The Duplicates tab carries a count of groups only while duplicates exist.' }),
|
Mp({ 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. Below the grid: "Showing 1–12 of 12" and the page-size select (same paginator as Articles).' }),
|
||||||
|
Mp({ pg: { page: 1, total: 312 }, name: 'Pagination: first page', trigger: '/media. Previous and First are disabled. Summary "Showing 1–25 of 312". The paginator sits under the grid or list and uses the Articles controls: 5, 25, 50 or 100 per page, default 25; page and size live in the URL as page and size (/media?page=7&size=50); search, tab, sort, view and size changes reset to page 1. API: GET /v1/media/?page=&size=&q=&filter= with the total in X-Total-Count.' }),
|
||||||
|
Mp({ pg: { page: 7, total: 312 }, name: 'Pagination: middle page', trigger: '/media?page=7. Current page uses --rc-sand and --rc-on-sand; ellipses mark skipped ranges.' }),
|
||||||
|
Mp({ pg: { page: 13, total: 312 }, name: 'Pagination: last page', trigger: '/media?page=13. Next and Last are disabled. Summary "Showing 301–312 of 312".' }),
|
||||||
|
Mp({ view: 'list', pg: { page: 2, total: 312 }, name: 'Pagination: list view', trigger: 'Same paginator under the table. On mobile: Previous, "Page 2 of 13", Next, with the 44 px targets.' }),
|
||||||
|
Mp({ loading: true, pg: { page: 6, total: 312, loading: 7 }, name: 'Pagination: loading next page', trigger: 'Next was pressed. Skeleton cards keep the grid height, controls are disabled, summary reads "Loading page 7…".' }),
|
||||||
|
Mp({ pg: { page: 6, total: 312, err: 'Couldn\'t load page 7. Showing page 6.' }, name: 'Pagination: error loading a page', trigger: '500 or network failure on page change. Previous images stay; Retry sits in the notice.' }),
|
||||||
|
Mp({ pg: { page: 13, total: 312, note: 'That page doesn\'t exist. Showing the last page.' }, name: 'Pagination: page out of range', trigger: '/media?page=99 is replaced with ?page=13 and this notice is shown.' }),
|
||||||
|
Mp({ pg: { page: 1, total: 312, sizeOpen: true }, name: 'Pagination: page size menu', trigger: 'The select opens upward. 5, 25, 50 or 100; the chosen size is saved as size and the page resets to 1.' }),
|
||||||
|
Mp({ pg: { page: 7, total: 312, focus: 'next' }, name: 'Pagination: focus-visible', trigger: 'Keyboard focus on Next: 2 px --ui-primary outline, 2 px offset. Same ring on every paginator control.' }),
|
||||||
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({ 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({ 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({ loading: true, name: 'Loading', trigger: 'The first load, a retry, or a change of search or filter. Skeleton cards appear after 150 ms.' }),
|
||||||
|
|||||||
@@ -33,8 +33,8 @@ Glossary pass 2, changes made: activity log lines "Removed N expired invites" an
|
|||||||
## Public image 400 bodies
|
## Public image 400 bodies
|
||||||
`{ "status": 400, "error": "unknown_variant", "message": "Unknown variant", "detail": "hero" }` and `{ "status": 400, "error": "unsupported_parameter", "message": "Unsupported parameter", "detail": "width" }`. The original is not served as a fallback.
|
`{ "status": 400, "error": "unknown_variant", "message": "Unknown variant", "detail": "hero" }` and `{ "status": 400, "error": "unsupported_parameter", "message": "Unsupported parameter", "detail": "width" }`. The original is not served as a fallback.
|
||||||
|
|
||||||
## Articles pagination
|
## Articles and Media pagination
|
||||||
Loading next page keeps row height, controls disabled, summary "Loading page 7…". Error "Couldn't load page 7. Showing page 6." with Retry. Out of range "That page doesn't exist. Showing the last page." Page size menu offers 5, 25, 50, 100.
|
Same states and copy on Articles and Media (Media draws them under the grid or list). Loading next page keeps row height, controls disabled, summary "Loading page 7…". Error "Couldn't load page 7. Showing page 6." with Retry. Out of range "That page doesn't exist. Showing the last page." Page size menu offers 5, 25, 50, 100. Invalid `page` or `size` in the URL (size=30, page=abc, page=0) is replaced by the default without a notice; the API 400 never reaches the user.
|
||||||
|
|
||||||
## Editor
|
## Editor
|
||||||
Counter without limit ("1,204 words · 7,318 characters"; at 120,000 characters "19,845 words · 120,000 characters"), "Saving…", "Saved", "Couldn't save. Your text is kept. Retry". Link states and the toolbar overflow are drawn in the Editor group (11 states).
|
Counter without limit ("1,204 words · 7,318 characters"; at 120,000 characters "19,845 words · 120,000 characters"), "Saving…", "Saved", "Couldn't save. Your text is kept. Retry". Link states and the toolbar overflow are drawn in the Editor group (11 states).
|
||||||
|
|||||||
+4
-4
@@ -21,7 +21,7 @@ Requirements: Docker with Compose v2. [task](https://taskfile.dev) is optional f
|
|||||||
docker compose up -d
|
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`.
|
`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:v3.2.1-beta`.
|
||||||
|
|
||||||
To build from the local sources instead, see [Building from source](#building-from-source).
|
To build from the local sources instead, see [Building from source](#building-from-source).
|
||||||
|
|
||||||
@@ -50,7 +50,7 @@ docker compose -f docker-compose.yml -f docker-compose.build.yml up -d --build
|
|||||||
| Release | Tags pushed |
|
| Release | Tags pushed |
|
||||||
|---|---|
|
|---|---|
|
||||||
| `vX.Y.Z` (stable) | `vX.Y.Z`, `X.Y.Z`, `X.Y`, `latest` |
|
| `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`) |
|
| `vX.Y.Z-<pre>` (for example `v3.2.1-beta`, `v3.2.1-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.
|
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.
|
||||||
|
|
||||||
@@ -198,7 +198,7 @@ Publishing is a manual, maintainer-run task, like `task release`. There is no CI
|
|||||||
1. Tag the release and keep the work tree clean:
|
1. Tag the release and keep the work tree clean:
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
git tag v2.9.0-beta
|
git tag v3.2.1-beta
|
||||||
```
|
```
|
||||||
|
|
||||||
2. Log in once to the registry. The task never reads or stores credentials:
|
2. Log in once to the registry. The task never reads or stores credentials:
|
||||||
@@ -226,7 +226,7 @@ Publishing is a manual, maintainer-run task, like `task release`. There is no CI
|
|||||||
|
|
||||||
```sh
|
```sh
|
||||||
task docker:publish -- --dry-run
|
task docker:publish -- --dry-run
|
||||||
task docker:publish VERSION=v2.9.0-rc.1 -- --dry-run
|
task docker:publish VERSION=v3.2.1-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`.
|
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`.
|
||||||
|
|||||||
+20
-16
@@ -17,21 +17,25 @@ Rules: bullets are full sentences ending with a period; user-facing wording, no
|
|||||||
|
|
||||||
## Published releases
|
## 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.
|
Each body lives in `docs/releases/<tag>.md`. Publish with `tea releases create --tag <tag> --title "<tag> - <theme>" --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 |
|
| Tag | Theme |
|
||||||
| --- | --- |
|
| --- | --- |
|
||||||
| `2.0.0-beta` (legacy tag without the `v`, kept as is) | v2.0.0-beta - Vue 3 SPA and domain-driven backend |
|
| `2.0.0-beta` (legacy tag without the `v`, kept as is) | Vue 3 SPA and domain-driven backend |
|
||||||
| `v2.1.0-beta` | v2.1.0-beta - Image upload in the editor |
|
| `v2.1.0-beta` | Image upload in the editor |
|
||||||
| `v2.2.0-beta` | v2.2.0-beta - Image crop, image removal & reset screens |
|
| `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.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.4.0-beta` | Owner role, invite management & Settings page |
|
||||||
| `v2.5.0-beta` | v2.5.0-beta - Media library & image picker |
|
| `v2.5.0-beta` | Media library & image picker |
|
||||||
| `v2.6.0-beta` | v2.6.0-beta - Signed updates and browser restart |
|
| `v2.6.0-beta` | Signed updates and browser restart |
|
||||||
| `v2.6.2-beta` | v2.6.2-beta - English and French interface |
|
| `v2.6.2-beta` | English and French interface |
|
||||||
| `v2.7.0-beta` | v2.7.0-beta - Markdown and block article bodies |
|
| `v2.7.0-beta` | Markdown and block article bodies |
|
||||||
| `v2.8.0-beta` | v2.8.0-beta - API keys and API reference |
|
| `v2.8.0-beta` | API keys and API reference |
|
||||||
| `v2.8.1-beta` | v2.8.1-beta - Docker deployment |
|
| `v2.8.1-beta` | Docker deployment |
|
||||||
| `v2.8.2-beta` | v2.8.2-beta - Security headers and clearer log in errors |
|
| `v2.8.2-beta` | Security headers and clearer log in errors |
|
||||||
| `v2.8.3-beta` | v2.8.3-beta - Security policy fixes for the web app |
|
| `v2.8.3-beta` | Security policy fixes for the web app |
|
||||||
| `v3.1.0-beta` | v3.1.0-beta - Image variants |
|
| `v2.9.0-beta` | Media duplicate purge |
|
||||||
|
| `v3.0.0-beta` | Activity log, more databases and S3 storage |
|
||||||
|
| `v3.1.0-beta` | Image variants |
|
||||||
|
| `v3.2.0-beta` | Article lists, editor links and activity export |
|
||||||
|
| `v3.2.1-beta` | Paged media library and remembered page sizes |
|
||||||
@@ -0,0 +1,46 @@
|
|||||||
|
This release adds paginated, searchable article lists, links in the editor and an export of the activity log, and removes the article length limit. The article list API changes shape, so read the upgrading notes if you call it.
|
||||||
|
|
||||||
|
## New
|
||||||
|
|
||||||
|
**Articles**
|
||||||
|
|
||||||
|
- The article list is now paged, with a search box, an Online and Draft filter, sortable columns and a page size of 5, 25, 50 or 100. Counts for All, Online and Draft stay fixed while you search.
|
||||||
|
- Articles have no length limit any more, and a new article can be created without a body.
|
||||||
|
|
||||||
|
**Editor**
|
||||||
|
|
||||||
|
- Insert, edit and remove links directly in the editor.
|
||||||
|
|
||||||
|
**Activity log**
|
||||||
|
|
||||||
|
- The summary cards at the top are now filters: select one to narrow the list, select it again to clear it.
|
||||||
|
- A new Export menu downloads the filtered events as a CSV file.
|
||||||
|
- The date range also accepts "All time".
|
||||||
|
|
||||||
|
**Integration**
|
||||||
|
|
||||||
|
- The Integration page has a new Images section covering image variants, and its code snippets now share one format.
|
||||||
|
|
||||||
|
## Improvements and fixes
|
||||||
|
|
||||||
|
- Each page now sets its own browser tab title, in the form "Page · RenewCMS", instead of keeping the title of the first page loaded.
|
||||||
|
- Registering now waits for the session to be refreshed before showing the pending-approval screen, which fixes a redirect back to the sign in page.
|
||||||
|
- The media and variant screens, the navigation contrast and the shell colors follow the design spec more closely.
|
||||||
|
- The development workflow on Linux no longer deletes the visual check output.
|
||||||
|
|
||||||
|
## API
|
||||||
|
|
||||||
|
- Changed: `GET /v1/article/` always answers `{ items, total, page, size, counts }` instead of a bare array. It accepts `page`, `size` (`5`, `25`, `50`, `100`), `q`, `status` (`online` or `draft`) and `sort` (for example `title:asc`; default `updated_at:desc`). An invalid value answers `400`. Anonymous callers still only see online articles.
|
||||||
|
- Changed: `POST /v1/article/` and `PATCH /v1/article/{id}` no longer reject a body over 10,000 characters, and `POST` accepts an empty body.
|
||||||
|
- `GET /v1/activity` and `GET /v1/activity/export` accept `range=all`.
|
||||||
|
|
||||||
|
## Under the hood
|
||||||
|
|
||||||
|
- Add the paged article query to the article repository contract, with accent-insensitive title search, and promote `golang.org/x/text` to a direct dependency.
|
||||||
|
- Add specifications, design checks and Go and Vitest suites for the new screens.
|
||||||
|
- Document the article list in `docs/api/articles.md` and link the API docs from the README.
|
||||||
|
|
||||||
|
## Upgrading
|
||||||
|
|
||||||
|
- Replace the binary, or pull the new image. There is no schema change and no new environment variable.
|
||||||
|
- Any script or site that reads `GET /v1/article/` must now read the `items` property of the response. Without `page` and `size` you get the first 25 articles, so loop over `page` until you have `total` items.
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
This release pages the media library, remembers your page size on the article, activity and media lists, and previews image variants on a real sample photo. The media list API changes shape, so read the upgrading notes if you call it.
|
||||||
|
|
||||||
|
## New
|
||||||
|
|
||||||
|
**Media library**
|
||||||
|
|
||||||
|
- The media library is now paged, with a page size of 5, 25, 50 or 100. The image picker in the editor uses the same pages.
|
||||||
|
|
||||||
|
**Image variants**
|
||||||
|
|
||||||
|
- Creating a variant shows a preview rendered from a real sample image, so the size estimate and the before and after comparison match what visitors will get.
|
||||||
|
|
||||||
|
## Improvements and fixes
|
||||||
|
|
||||||
|
- The article, activity and media lists keep their page and page size in the address, so a reload or a shared link opens the same view.
|
||||||
|
- The Integration page is now fully translated into French.
|
||||||
|
|
||||||
|
## API
|
||||||
|
|
||||||
|
- Changed: `GET /v1/media/` answers `{ items, total, page, size, counts }` instead of `{ items, next_cursor, counts }`. It accepts `page` (default `1`) and `size` (`5`, `25`, `50` or `100`, default `25`). An invalid value answers `400`.
|
||||||
|
- Changed: `GET /v1/media/` no longer accepts `cursor` or `limit`.
|
||||||
|
|
||||||
|
## Under the hood
|
||||||
|
|
||||||
|
- Replace the cursor and limit of the media list query with a page and a size in the image domain and the list use case.
|
||||||
|
- Add specifications, design checks and Go and Vitest suites for the paged media screens.
|
||||||
|
|
||||||
|
## Upgrading
|
||||||
|
|
||||||
|
- Replace the binary, or pull the new image. There is no schema change and no new environment variable.
|
||||||
|
- Any script or site that reads `GET /v1/media/` must now read `total` and loop over `page` instead of following `next_cursor`.
|
||||||
@@ -271,10 +271,17 @@ Feature: The back-office keeps an append-only activity log that owners can read
|
|||||||
| range=today | events since 00:00 UTC today |
|
| range=today | events since 00:00 UTC today |
|
||||||
| range=7d | events of the last 7 days |
|
| range=7d | events of the last 7 days |
|
||||||
| range=30d | events of the last 30 days |
|
| range=30d | events of the last 30 days |
|
||||||
|
| range=all | every event, whatever its age |
|
||||||
| range=custom&from=2026-09-01&to=2026-09-30 | events from 1 to 30 September 2026 UTC |
|
| range=custom&from=2026-09-01&to=2026-09-30 | events from 1 to 30 September 2026 UTC |
|
||||||
| page=2&size=50 | the second page of 50 |
|
| page=2&size=50 | the second page of 50 |
|
||||||
| size=5 | the first page of 5 |
|
| size=5 | the first page of 5 |
|
||||||
|
|
||||||
|
Scenario: range=all covers every event
|
||||||
|
Given events 2 days old and 90 days old
|
||||||
|
When the owner sends GET /v1/activity?range=all
|
||||||
|
Then both events are listed
|
||||||
|
And the summary and the export with range=all cover both events too
|
||||||
|
|
||||||
Scenario: Omitting range means 7 days
|
Scenario: Omitting range means 7 days
|
||||||
Given events 2 days old and 10 days old
|
Given events 2 days old and 10 days old
|
||||||
When the owner sends GET /v1/activity
|
When the owner sends GET /v1/activity
|
||||||
|
|||||||
@@ -0,0 +1,228 @@
|
|||||||
|
Feature: Activity screen, filter cards as toggles and the Export menu
|
||||||
|
|
||||||
|
As an owner or admin
|
||||||
|
I want the Failed actions and Security events cards to toggle their filter, and Export to offer the current view or all activity as CSV
|
||||||
|
So that I can isolate problems in one click and keep a copy of the log
|
||||||
|
|
||||||
|
Background:
|
||||||
|
Given this slice amends features/activity_screen.feature (header Export CSV button, strip-card effects, Export scenarios, French export label, empty/error export rules) per docs/design/screens/activity.md groups "Activity: filter cards" and "Activity: export" and docs/design/states.md
|
||||||
|
And the screen, strip, chips, filter bar and list are otherwise as in features/activity_screen.feature
|
||||||
|
And a page filter is the set of q, actor, category, outcome, security, range, from, to
|
||||||
|
And the filters live in component state, so card, chip and Outcome segment read the same state: card Failed pressed = outcome "failed" is set = chip "Outcome: Failed" shown = Outcome segment on Failed; card Security pressed = security is true = chip "Type: Security events" shown, Outcome segment unchanged
|
||||||
|
And "Failed actions" and "Security events" are buttons with aria-pressed (true or false); "Total actions" and "Active people" are not toggles and carry no aria-pressed
|
||||||
|
And a pressed card uses --rc-sand background with --rc-on-sand text; an unpressed card uses the default look
|
||||||
|
And the card hint lines are: unpressed "Click to filter the list" (on hover), pressed "Filtering. Click to clear", pressed and hovered "Click to clear this filter" with an x icon
|
||||||
|
And hover on an unpressed card uses --ui-bg-elevated; keyboard focus-visible draws a 2 px --ui-primary outline with a 2 px offset; Enter and Space toggle
|
||||||
|
And the Outcome segment can still be changed by hand: choosing Failed presses the Failed card, choosing All or Succeeded unpresses it
|
||||||
|
And the Export control is shown only in the full view (owner or admin); the regular-user view and the Forbidden panel have none
|
||||||
|
And the Export control is one outline button, icon download, label "Export", trailing chevron; it is a dropdown menu on desktop and a bottom sheet below md; Enter or ArrowDown opens it, Escape closes it, and focus-visible is a 2 px --ui-primary outline with a 2 px offset
|
||||||
|
And the menu has two items:
|
||||||
|
| item | sub-line (enabled) | disabled reason |
|
||||||
|
| Export current view | CSV · {n} events matching your filters and sort, across all pages (n = list total) | Nothing to export. No events match these filters. |
|
||||||
|
| Export all activity… | CSV · every event, ignoring filters. Owners and admins only. | Only owners and admins can export all activity. |
|
||||||
|
And export is CSV only, synchronous, one streamed download: no progress percentage, no job, no "ready later"; JSON (format=json) is proposed in the design, is NOT implemented here, and no format control is offered
|
||||||
|
And "Export current view" sends GET /v1/activity/export with the active page filters (the list query without page and size) and no format parameter
|
||||||
|
And "Export all activity…" sends GET /v1/activity/export with no page filter at all and only the dialog's date range: All time sends range=all; Today, 7 days and 30 days send range=today|7d|30d; Custom sends range=custom&from=YYYY-MM-DD&to=YYYY-MM-DD
|
||||||
|
And the backend accepts range=all on the list, summary and export endpoints (features/activity-log-backend.feature); an omitted range still means 7d
|
||||||
|
And the download is built by the SPA from the response body (blob and anchor) with the file name activity-YYYY-MM-DD.csv for the current view and activity-all-YYYY-MM-DD.csv for all activity (local date)
|
||||||
|
And a response whose CSV has only the header row means nothing to export: nothing is downloaded
|
||||||
|
And 401 and the unverified 403 stay with useApi's global handling; the role-lowered 403 is handled here
|
||||||
|
And the dialog "Export all activity" is a modal (sm:max-w-md, a bottom sheet below md) with the title "Export all activity", a read-only "Format" row reading "CSV", a "Date range" select (default "All time") with the hint "Default is all time. Filters on the page are ignored.", and the footer Cancel on the left, "Export CSV" on the right
|
||||||
|
And every new English string has a French entry in messages.ts
|
||||||
|
|
||||||
|
Scenario Outline: Cards — the toggle cycle keeps card, chip, segment and request in sync
|
||||||
|
Given the Default state has loaded with no filter
|
||||||
|
When the user activates the "<card>" card
|
||||||
|
Then the card has aria-pressed="true", <chip> is shown with "Clear all", and <segment>
|
||||||
|
And GET /v1/activity is sent once with <query>, page=1 and size=25
|
||||||
|
And GET /v1/activity/summary is not requested again
|
||||||
|
When the user activates the "<card>" card again
|
||||||
|
Then aria-pressed is "false", the chip and "Clear all" are gone, the Outcome segment is on All
|
||||||
|
And GET /v1/activity is sent with range=7d, page=1 and size=25 only
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| card | chip | segment | query |
|
||||||
|
| Failed actions | "Outcome: Failed" | the Outcome segment is on Failed | outcome=failed |
|
||||||
|
| Security events | "Type: Security events" | the Outcome segment stays on All | security=true |
|
||||||
|
|
||||||
|
Scenario Outline: Cards — every way of removing the filter returns all three controls to default
|
||||||
|
Given the "<card>" card is pressed with <chip> shown
|
||||||
|
When the user <remove>
|
||||||
|
Then the card has aria-pressed="false" and default look, the chip is gone, the Outcome segment is on All
|
||||||
|
And "Clear all" is gone unless another chip remains
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| card | chip | remove |
|
||||||
|
| Failed actions | "Outcome: Failed" | activates the x of the chip |
|
||||||
|
| Failed actions | "Outcome: Failed" | activates "Clear all" |
|
||||||
|
| Failed actions | "Outcome: Failed" | chooses All in the Outcome segment |
|
||||||
|
| Failed actions | "Outcome: Failed" | chooses Succeeded in the Outcome segment |
|
||||||
|
| Security events | "Type: Security events" | activates the x of the chip |
|
||||||
|
| Security events | "Type: Security events" | activates "Clear all" |
|
||||||
|
|
||||||
|
Scenario: Cards — choosing Failed in the Outcome segment presses the card
|
||||||
|
Given the Default state has loaded
|
||||||
|
When the user chooses Failed in the Outcome segment
|
||||||
|
Then the Failed actions card has aria-pressed="true" and the chip "Outcome: Failed" is shown
|
||||||
|
|
||||||
|
Scenario: Cards — both cards can be pressed together
|
||||||
|
Given the "Failed actions" card is pressed
|
||||||
|
When the user activates the "Security events" card
|
||||||
|
Then both cards are pressed, the chips "Outcome: Failed" and "Type: Security events" are shown
|
||||||
|
And GET /v1/activity is sent with outcome=failed and security=true
|
||||||
|
|
||||||
|
Scenario: Cards — the card plus other filters; unpressing removes only its chip
|
||||||
|
Given Category "Authentication" and 30 days are applied and the "Failed actions" card is pressed
|
||||||
|
Then the chips read "Category: Authentication", "Outcome: Failed", "Dates: 30 days" and "Clear all"
|
||||||
|
When the user activates the "Failed actions" card
|
||||||
|
Then only "Outcome: Failed" is removed, the other two chips remain, and the request keeps category=auth and range=30d
|
||||||
|
|
||||||
|
Scenario: Cards — hint lines, hover and keyboard
|
||||||
|
Given the Default state has loaded
|
||||||
|
Then the Failed actions card hint reads "Click to filter the list" on hover and the card background is --ui-bg-elevated
|
||||||
|
When the Failed actions card is focused with the keyboard
|
||||||
|
Then a 2 px --ui-primary outline with a 2 px offset is drawn
|
||||||
|
When the user presses Space (or Enter)
|
||||||
|
Then the card is pressed with the hint "Filtering. Click to clear"
|
||||||
|
When the pointer is over the pressed card
|
||||||
|
Then the hint reads "Click to clear this filter" with an x icon
|
||||||
|
And "Clear all" and the chip x show hover and focus-visible styles per the board
|
||||||
|
|
||||||
|
Scenario: Cards — Total actions and Active people are not toggles
|
||||||
|
Given the "Failed actions" card is pressed
|
||||||
|
When the user activates "Total actions"
|
||||||
|
Then every filter is cleared and no card is pressed
|
||||||
|
When the user activates "Active people"
|
||||||
|
Then nothing changes and no request is sent
|
||||||
|
And neither card has aria-pressed
|
||||||
|
|
||||||
|
Scenario: Cards — the empty panel's "Clear filters" unpresses cards
|
||||||
|
Given the "Security events" card is pressed and the list is empty
|
||||||
|
When the user activates "Clear filters" in the empty panel
|
||||||
|
Then the card is unpressed and no chip is shown
|
||||||
|
|
||||||
|
Scenario: Cards — a mobile Filters sheet shares the same state
|
||||||
|
Given below md the "Failed actions" card is pressed
|
||||||
|
Then the Filters button badge counts the Outcome chip and the sheet's Outcome control is on Failed
|
||||||
|
When the user sets Outcome to All in the sheet
|
||||||
|
Then the card is unpressed
|
||||||
|
|
||||||
|
Scenario: Export menu — open, items and hover
|
||||||
|
Given the Default state has loaded as owner with total 1284
|
||||||
|
When the user activates "Export"
|
||||||
|
Then the menu lists "Export current view" ("CSV · 1,284 events matching your filters and sort, across all pages") and "Export all activity…", both enabled
|
||||||
|
And hovering "Export all activity…" highlights it
|
||||||
|
When the user presses Escape
|
||||||
|
Then the menu closes and focus returns to the Export button
|
||||||
|
|
||||||
|
Scenario: Export menu — filtered view states the count
|
||||||
|
Given the "Failed actions" card is pressed and the list total is 6
|
||||||
|
When the user opens the Export menu
|
||||||
|
Then "Export current view" reads "CSV · 6 events matching your filters and sort, across all pages"
|
||||||
|
|
||||||
|
Scenario: Export menu — nothing to export in the current view
|
||||||
|
Given Category "Media" and Outcome "Failed" match nothing (total 0)
|
||||||
|
When the user opens the Export menu
|
||||||
|
Then "Export current view" is disabled with "Nothing to export. No events match these filters." and "Export all activity…" is enabled
|
||||||
|
|
||||||
|
Scenario: Export menu — no activity at all and error state
|
||||||
|
Given the list is "No activity yet" (total 0, no chip) or in the Error state
|
||||||
|
Then the Export button is disabled
|
||||||
|
|
||||||
|
Scenario: Export current view — success
|
||||||
|
Given Category "Authentication" and 30 days are applied
|
||||||
|
When the user chooses "Export current view"
|
||||||
|
Then GET /v1/activity/export is sent once with category=auth and range=30d, no page, no size, no format
|
||||||
|
And when it resolves 200 with a text/csv body that has data rows, the file activity-YYYY-MM-DD.csv is downloaded
|
||||||
|
And a toast appears: title "Download started", body "activity-YYYY-MM-DD.csv is downloading."
|
||||||
|
And the menu is closed and no dialog was shown
|
||||||
|
|
||||||
|
Scenario Outline: Export current view — failures raise an error toast
|
||||||
|
When the user chooses "Export current view" and the request <failure>
|
||||||
|
Then an error toast titled "Couldn't prepare the download" appears with the body "<body>"
|
||||||
|
And nothing is downloaded and the Export button is enabled
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| failure | body |
|
||||||
|
| resolves with a 500 response | Something went wrong on our side. Nothing was changed. Try again in a moment. |
|
||||||
|
| never reaches the server | Something went wrong on our side. Nothing was changed. Try again in a moment. |
|
||||||
|
| resolves with a 400 response | That request wasn't valid. Check the fields and try again. |
|
||||||
|
|
||||||
|
Scenario: Export current view — the role was lowered while the page was open (403)
|
||||||
|
When the user chooses "Export current view" and the request resolves 403 with the owner/admin-required message
|
||||||
|
Then an error toast titled "You can't export all activity" appears and nothing is downloaded
|
||||||
|
And the Export menu then shows both items disabled with "Only owners and admins can export all activity."
|
||||||
|
|
||||||
|
Scenario: Export current view — nothing to export
|
||||||
|
When the user chooses "Export current view" and the response is 200 with only the CSV header row
|
||||||
|
Then nothing is downloaded and a toast titled "Nothing to export" appears
|
||||||
|
|
||||||
|
Scenario: Export all — the dialog opens configured
|
||||||
|
When the user chooses "Export all activity…"
|
||||||
|
Then the dialog "Export all activity" shows Format "CSV" (read-only, no JSON option), Date range "All time", Cancel on the left and "Export CSV" on the right
|
||||||
|
And no request has been sent
|
||||||
|
|
||||||
|
Scenario Outline: Export all — the date range maps to the query and ignores page filters
|
||||||
|
Given Category "Media", Outcome "Failed" and the "Failed actions" card are applied on the page
|
||||||
|
When the user picks Date range "<range>" in the dialog and activates "Export CSV"
|
||||||
|
Then GET /v1/activity/export is sent with <query> and no other parameter
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| range | query |
|
||||||
|
| All time | range=all |
|
||||||
|
| Today | range=today |
|
||||||
|
| 7 days | range=7d |
|
||||||
|
| 30 days | range=30d |
|
||||||
|
| Custom 1 Sep to 30 Sep 2026 | range=custom&from=2026-09-01&to=2026-09-30 |
|
||||||
|
|
||||||
|
Scenario: Export all — Custom needs a valid pair
|
||||||
|
When the user picks "Custom" and sets only one date, or from after to
|
||||||
|
Then "Export CSV" is disabled and no request is sent
|
||||||
|
|
||||||
|
Scenario: Export all — preparing, then download started
|
||||||
|
When the user activates "Export CSV" in the dialog
|
||||||
|
Then the dialog shows "Preparing download…" with an indeterminate bar and no percentage, "Keep this window open.", Cancel enabled and a disabled "Preparing…"
|
||||||
|
When the response resolves 200 with a CSV that has data rows
|
||||||
|
Then the file activity-all-YYYY-MM-DD.csv is downloaded and the dialog reads "Download started" and "activity-all-YYYY-MM-DD.csv is downloading. Check your browser's downloads if nothing appears." with only "Close"
|
||||||
|
When the user activates "Close"
|
||||||
|
Then the dialog closes and a toast appears: "Download started", "activity-all-YYYY-MM-DD.csv is downloading."
|
||||||
|
|
||||||
|
Scenario: Export all — Cancel while preparing
|
||||||
|
Given the export request is in flight
|
||||||
|
When the user activates "Cancel"
|
||||||
|
Then the request is aborted, nothing is downloaded, the dialog closes and no toast appears
|
||||||
|
|
||||||
|
Scenario Outline: Export all — failure shows Retry
|
||||||
|
When the request <failure>
|
||||||
|
Then the dialog reads "Couldn't prepare the download" and "Nothing was downloaded. Try again in a moment." with Cancel and "Retry"
|
||||||
|
When the user activates "Retry"
|
||||||
|
Then the same request is sent again and the dialog shows "Preparing download…"
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| failure |
|
||||||
|
| resolves with a 500 response |
|
||||||
|
| never reaches the server |
|
||||||
|
|
||||||
|
Scenario: Export all — the chosen range has no events
|
||||||
|
When the response is 200 with only the CSV header row
|
||||||
|
Then nothing is downloaded and the dialog reads "Nothing to export" and "There is no activity in this date range. Choose a wider range." with only "Close"
|
||||||
|
|
||||||
|
Scenario: Export all — not allowed (403)
|
||||||
|
When the response is 403
|
||||||
|
Then the dialog reads "You can't export all activity" and "Only owners and admins can export all activity. Ask an owner if you need a copy." with only "Close"
|
||||||
|
And nothing is downloaded
|
||||||
|
|
||||||
|
Scenario: Export — below md the menu and the dialog are bottom sheets
|
||||||
|
Given the Default state has loaded below md
|
||||||
|
When the user activates "Export"
|
||||||
|
Then a bottom sheet lists "Export current view" and "Export all activity…"
|
||||||
|
When the user chooses "Export all activity…"
|
||||||
|
Then the dialog is a bottom sheet with the same fields and footer (secondary left, primary right)
|
||||||
|
|
||||||
|
Scenario: Export — owners and admins only
|
||||||
|
Given the session role is "editor" (or absent)
|
||||||
|
Then no Export control is rendered and GET /v1/activity/export is never sent
|
||||||
|
|
||||||
|
Scenario: Export — French
|
||||||
|
Given the language is French
|
||||||
|
Then every string above (menu, dialog, toasts, hints, chips "Type : Événements de sécurité") has a French entry, and the former "Exporter en CSV" button label is replaced by the menu button
|
||||||
@@ -0,0 +1,63 @@
|
|||||||
|
# QA: Activity filter cards as toggles and the Export menu
|
||||||
|
|
||||||
|
## Implementation note for coder (informational)
|
||||||
|
|
||||||
|
SPA slice with one small backend change: accept `range=all` in the list, summary and export range validation (use case range handling and the handler `validate` tag). An omitted range stays 7d. The range table in features/activity-log-backend.feature is updated accordingly.
|
||||||
|
|
||||||
|
This slice amends features/activity_screen.feature and .qa.md: the header button is now "Export" with a menu, the Export success and failure scenarios are replaced, and the French label "Exporter en CSV" becomes "Exporter". Update the matching Vitest cases (strip-card effects, Export success and failure, empty/error export-disabled lines, French labels) in the same change.
|
||||||
|
|
||||||
|
`useApi().request` calls response.json(); add a blob read that keeps the global 401 handling and supports an AbortSignal. Downloads use an object URL and an anchor with a `download` file name built from the local date. Toasts use `useToast().add({ color, icon, title, description })`.
|
||||||
|
|
||||||
|
## Automated (Vitest + Vue Test Utils, `task test:web`)
|
||||||
|
|
||||||
|
Mock `useApi` per case matching on method, path and parsed query. Mount ActivityView in DashboardShell as in the existing QA (owner session; "editor" for the regular case). Run layout cases at desktop and below-md widths. Use fake timers for setTimeout/clearTimeout only. No test freezes or asserts the system date: file names are asserted with `^activity-\d{4}-\d{2}-\d{2}\.csv$` and `^activity-all-\d{4}-\d{2}-\d{2}\.csv$`. Fixtures: existing `activityItems`, `summaryDefault`, and a CSV text with a header and two rows (and a header-only CSV).
|
||||||
|
|
||||||
|
1. **Toggle cycle, Examples-driven (Failed, Security)** - click: aria-pressed true, chip text, Outcome segment, request query, no extra summary request; click again: aria-pressed false, chip and Clear all gone, segment All, query without the key.
|
||||||
|
2. **Every removal path** - chip x, Clear all, Outcome All, Outcome Succeeded (Failed card only): card, chip and segment all return to default (assert the three together after each).
|
||||||
|
3. **Segment drives the card** - choose Failed in the segment: Failed card pressed and chip present.
|
||||||
|
4. **Both cards pressed** - queries `outcome=failed&security=true`, two chips.
|
||||||
|
5. **Card plus other filters** - Category auth, 30d, Failed: unpress removes only the Outcome chip; request keeps category and range.
|
||||||
|
6. **Hint and style** - hint texts for unpressed, hover, pressed, pressed+hover (with x icon); pressed class uses the sand tokens (assert the token class, not a hex); unpressed hover class; focus-visible class; Enter and Space toggle.
|
||||||
|
7. **Non-toggle cards** - Total clears all, Active people sends no request, neither has aria-pressed.
|
||||||
|
8. **Clear filters from the empty panel** unpresses cards; mobile Filters sheet shares state and badge count.
|
||||||
|
9. **Export menu structure** - owner: button "Export" with the download icon and chevron; menu items and sub-lines with total 1284 and with Failed card total 6; Escape closes and returns focus; ArrowDown and Enter open; below md rendered as a bottom sheet.
|
||||||
|
10. **Disabled states** - total 0 with a chip: "Export current view" disabled with its reason, "Export all activity…" enabled; "No activity yet" and Error states: Export button disabled; after a 403 on export: both items disabled with the owner/admin reason.
|
||||||
|
11. **Role gating** - role "editor" or none: no Export control, no `/export` request; Forbidden panel: none.
|
||||||
|
12. **Export current view success** - request to `/v1/activity/export` with the list filters, no page or size, no format; blob read; one anchor click with download matching the file-name pattern; toast "Download started"; no dialog.
|
||||||
|
13. **Export current view failure, Examples-driven (500, 400, network)** - error toast "Couldn't prepare the download" with the mapped body; no download; button enabled.
|
||||||
|
14. **Export current view 403** - toast "You can't export all activity"; both items disabled afterwards.
|
||||||
|
15. **Export current view, header-only CSV** - no download, toast "Nothing to export".
|
||||||
|
16. **Export all dialog** - opens configured (Format "CSV" read-only, no JSON, Date range "All time", hint, Cancel left, "Export CSV" right); no request on open.
|
||||||
|
17. **Export all query, Examples-driven** - with page filters applied: All time -> `range=all` only; Today, 7d, 30d; Custom -> `range=custom&from=2026-09-01&to=2026-09-30`; Custom with one date or from>to keeps "Export CSV" disabled.
|
||||||
|
18. **Preparing** - request pending: indeterminate bar (no `aria-valuenow`), copy "Preparing download…", Cancel enabled, "Preparing…" disabled.
|
||||||
|
19. **Started** - resolve with data rows: download triggered once; dialog copy and only "Close"; Close shows the toast with the all-activity file name.
|
||||||
|
20. **Cancel while preparing** - AbortController aborted, no download, dialog closed, no toast.
|
||||||
|
21. **Failed + Retry** - 500 and network: copy, Cancel and Retry; Retry resends and re-enters Preparing.
|
||||||
|
22. **Nothing to export** - header-only CSV: no download, copy, only "Close".
|
||||||
|
23. **403 dialog** - copy and only "Close"; no download.
|
||||||
|
24. **Below md** - menu and dialog render as bottom sheets with the same content.
|
||||||
|
25. **French** - every new key exists in messages.ts (completeness test) and a spot-check of the menu, dialog and toast strings.
|
||||||
|
26. **No JSON** - no element with text "JSON" and no `format` query parameter in any export request.
|
||||||
|
|
||||||
|
Backend (Go, in test/, on the activity handler tests): `range=all` on list, summary and export returns 200 over all events (older than 30 days included); invalid values still 400; omitted range still means 7d; non-owner export still 403.
|
||||||
|
|
||||||
|
## Visual (task visual:check -- activity, desktop and mobile, light and dark)
|
||||||
|
|
||||||
|
Reference: board groups "Activity: filter cards" and "Activity: export" under `docs/design/source/`; exact values in `docs/design/source/ActivityFrame.dc.html`. Add states to the activity entry in `web/visual/states.ts` with the board's own sample data. Hard gate: every capture within 10 %. Mock only the calls each state needs; an unmocked call fails the run.
|
||||||
|
|
||||||
|
- [ ] Filter cards: Default, card hover, card focus-visible, Failed active, active hover, Security active, chip x hover, Clear all hover and focus-visible, card plus other filters. Mark `skip: 'clock-sensitive'` where the rows behind show relative times.
|
||||||
|
- [ ] Export: menu open, item hover, filtered view, nothing to export (Media / Failed, total 0), no permission, button focus-visible.
|
||||||
|
- [ ] Export dialog: configure (CSV only), preparing (request hangs), started, failed, nothing to export, not allowed (403). Mock `/export` with hang / 500 / 403 / header-only CSV as needed.
|
||||||
|
- [ ] Export "CSV or JSON (proposed)": NOT implemented; skip with reason "proposed, JSON not shipped".
|
||||||
|
- [ ] Export toasts: file name contains the current date; `skip: 'clock-sensitive'`.
|
||||||
|
- [ ] Mobile bottom sheets for the menu and the dialog at 390x844.
|
||||||
|
- [ ] Layout from the frame (not components.md): dialog sm:max-w-md; footer secondary left, primary right; Export button 32 px (44 px mobile); pressed card sand fill.
|
||||||
|
- [ ] Not covered by screenshots: keyboard and focus order (Tab to cards, Space/Enter toggle, focus returns to the Export button after the menu closes), focus trap in the dialog, Escape, hover and motion, the reduced-motion indeterminate bar.
|
||||||
|
|
||||||
|
## Manual verification
|
||||||
|
|
||||||
|
- **Real CSV download** against `task dev`: Export current view with and without filters, and Export all with each range; open the file: only the filtered rows for the current view, every row for all time; file names and the browser's download prompt.
|
||||||
|
- **Large export**: with thousands of events, confirm the download starts and the "Preparing download…" dialog behaves.
|
||||||
|
- **Role lowered while the page is open**: change the user's role in another session, then export; confirm the 403 handling.
|
||||||
|
- **Time zones**: file names use the local date; check near midnight.
|
||||||
|
- **French** and **screen readers**: aria-pressed announcements, menu and dialog semantics.
|
||||||
@@ -41,7 +41,7 @@ Feature: Activity screen, details slide-over and My activity
|
|||||||
And the header is the title "Activity" (regular user: "My activity") with the subtitle "Who
|
And the header is the title "Activity" (regular user: "My activity") with the subtitle "Who
|
||||||
did what, and when, across your site." (regular user: "Everything you've done on this
|
did what, and when, across your site." (regular user: "Everything you've done on this
|
||||||
site."), and, in the full view except Forbidden, an outline button with icon download and
|
site."), and, in the full view except Forbidden, an outline button with icon download and
|
||||||
the label "Export CSV" at the right, aligned to the bottom of the title block
|
the label "Export" and a trailing chevron at the right, opening the menu described in activity_filter_cards_and_export.feature, aligned to the bottom of the title block
|
||||||
And sentences are composed in the SPA from the event's action code, its outcome, its params
|
And sentences are composed in the SPA from the event's action code, its outcome, its params
|
||||||
and its target name through the existing i18n (English keys, French in messages.ts), never
|
and its target name through the existing i18n (English keys, French in messages.ts), never
|
||||||
stored as text; the target name is user content, is inserted untranslated as a semibold
|
stored as text; the target name is user content, is inserted untranslated as a semibold
|
||||||
@@ -226,7 +226,7 @@ Feature: Activity screen, details slide-over and My activity
|
|||||||
load activity" is an error alert with icon circle-x, the text and an outline "Try again"
|
load activity" is an error alert with icon circle-x, the text and an outline "Try again"
|
||||||
button, and "You can't view this activity" (no trailing period) uses icon lock and the
|
button, and "You can't view this activity" (no trailing period) uses icon lock and the
|
||||||
action "Back to home"
|
action "Back to home"
|
||||||
And "Export CSV" is disabled in "No activity yet" and while the list is in the Error state,
|
And "Export" is disabled in "No activity yet" and while the list is in the Error state,
|
||||||
and enabled otherwise
|
and enabled otherwise
|
||||||
And ActivityDetailsPanel is a USlideover: 480 px wide from the right on desktop, an 88 %-high
|
And ActivityDetailsPanel is a USlideover: 480 px wide from the right on desktop, an 88 %-high
|
||||||
bottom sheet with a 36×4 px handle below md; its header reads "Activity details" with a
|
bottom sheet with a 36×4 px handle below md; its header reads "Activity details" with a
|
||||||
@@ -277,7 +277,7 @@ Feature: Activity screen, details slide-over and My activity
|
|||||||
failed 6, security 11 and seven-day series, and the session role is "owner"
|
failed 6, security 11 and seven-day series, and the session role is "owner"
|
||||||
When the user navigates to /activity
|
When the user navigates to /activity
|
||||||
Then the header shows "Activity", "Who did what, and when, across your site." and an enabled
|
Then the header shows "Activity", "Who did what, and when, across your site." and an enabled
|
||||||
"Export CSV"
|
"Export"
|
||||||
And the strip reads "1,284" "12% vs previous 7 days" with trending-up; "9" "7 people, 2 API
|
And the strip reads "1,284" "12% vs previous 7 days" with trending-up; "9" "7 people, 2 API
|
||||||
keys"; "6" "0.5% of all actions"; "11" "11 flagged"
|
keys"; "6" "0.5% of all actions"; "11" "11 flagged"
|
||||||
And the filter bar shows "Search activity", "All people", "All categories", All selected in
|
And the filter bar shows "Search activity", "All people", "All categories", All selected in
|
||||||
@@ -340,7 +340,7 @@ Feature: Activity screen, details slide-over and My activity
|
|||||||
Scenario: Loading — skeletons after 150 ms while both requests are in flight
|
Scenario: Loading — skeletons after 150 ms while both requests are in flight
|
||||||
Given GET /v1/activity and GET /v1/activity/summary have not resolved
|
Given GET /v1/activity and GET /v1/activity/summary have not resolved
|
||||||
When the user navigates to /activity
|
When the user navigates to /activity
|
||||||
Then the header, the filter bar and an enabled "Export CSV" are drawn at once
|
Then the header, the filter bar and an enabled "Export" are drawn at once
|
||||||
And nothing is drawn in place of the strip and the table for the first 150 ms
|
And nothing is drawn in place of the strip and the table for the first 150 ms
|
||||||
And after 150 ms 4 skeleton cards replace the strip and 9 skeleton rows (5 cards below md)
|
And after 150 ms 4 skeleton cards replace the strip and 9 skeleton rows (5 cards below md)
|
||||||
replace the table, the pager is hidden and the table container is aria-busy="true"
|
replace the table, the pager is hidden and the table container is aria-busy="true"
|
||||||
@@ -377,7 +377,7 @@ Feature: Activity screen, details slide-over and My activity
|
|||||||
"0" "Nothing to flag"
|
"0" "Nothing to flag"
|
||||||
And an empty panel with icon history shows "No activity yet" and "Actions on articles,
|
And an empty panel with icon history shows "No activity yet" and "Actions on articles,
|
||||||
media, users and API keys will appear here."
|
media, users and API keys will appear here."
|
||||||
And "Export CSV" is disabled and no table header or pager is shown
|
And "Export" is disabled and no table header or pager is shown
|
||||||
|
|
||||||
Scenario: Empty, filters match nothing — the panel offers Clear filters
|
Scenario: Empty, filters match nothing — the panel offers Clear filters
|
||||||
Given the Default state has loaded
|
Given the Default state has loaded
|
||||||
@@ -386,7 +386,7 @@ Feature: Activity screen, details slide-over and My activity
|
|||||||
Then the chips read "Search: sitemap", "Category: Media", "Outcome: Failed" and "Clear all"
|
Then the chips read "Search: sitemap", "Category: Media", "Outcome: Failed" and "Clear all"
|
||||||
And an empty panel with icon search-x shows "No activity matches these filters" and "Try a
|
And an empty panel with icon search-x shows "No activity matches these filters" and "Try a
|
||||||
different search or a wider date range." with the action "Clear filters"
|
different search or a wider date range." with the action "Clear filters"
|
||||||
And "Export CSV" stays enabled and the strip is unchanged
|
And "Export" stays enabled and the strip is unchanged
|
||||||
When the user activates "Clear filters"
|
When the user activates "Clear filters"
|
||||||
Then every filter is reset, GET /v1/activity is sent with range=7d, page=1, size=25 only and
|
Then every filter is reset, GET /v1/activity is sent with range=7d, page=1, size=25 only and
|
||||||
the rows come back
|
the rows come back
|
||||||
@@ -397,7 +397,7 @@ Feature: Activity screen, details slide-over and My activity
|
|||||||
Then the strip and the filter bar are shown
|
Then the strip and the filter bar are shown
|
||||||
And an error alert shows "Couldn't load activity" and "Check your connection and try again."
|
And an error alert shows "Couldn't load activity" and "Check your connection and try again."
|
||||||
with the action "Try again"
|
with the action "Try again"
|
||||||
And "Export CSV" is disabled and no table or pager is shown
|
And "Export" is disabled and no table or pager is shown
|
||||||
When the user activates "Try again"
|
When the user activates "Try again"
|
||||||
Then the Loading state shows for the list and GET /v1/activity is sent again with the same
|
Then the Loading state shows for the list and GET /v1/activity is sent again with the same
|
||||||
query
|
query
|
||||||
@@ -426,7 +426,7 @@ Feature: Activity screen, details slide-over and My activity
|
|||||||
Scenario: Forbidden (403) — the page itself is refused
|
Scenario: Forbidden (403) — the page itself is refused
|
||||||
Given GET /v1/activity resolves 403 and GET /v1/auth/me resolves 200 with a verified user
|
Given GET /v1/activity resolves 403 and GET /v1/auth/me resolves 200 with a verified user
|
||||||
When the user navigates to /activity
|
When the user navigates to /activity
|
||||||
Then the header shows "Activity" and no "Export CSV"
|
Then the header shows "Activity" and no "Export"
|
||||||
And no strip, filter bar, chips, table or pager is shown
|
And no strip, filter bar, chips, table or pager is shown
|
||||||
And an empty panel with icon lock shows "You can't view this activity" and "Your role
|
And an empty panel with icon lock shows "You can't view this activity" and "Your role
|
||||||
doesn't include this page. Ask an owner or admin if you need access." with the action "Back
|
doesn't include this page. Ask an owner or admin if you need access." with the action "Back
|
||||||
@@ -529,29 +529,6 @@ Feature: Activity screen, details slide-over and My activity
|
|||||||
When the user activates "Show 6 results"
|
When the user activates "Show 6 results"
|
||||||
Then the sheet closes and the list stays filtered
|
Then the sheet closes and the list stays filtered
|
||||||
|
|
||||||
Scenario: Export — the file is prepared, then downloads
|
|
||||||
Given the Default state has loaded with the filters Category "Authentication" and 30 days
|
|
||||||
When the user activates "Export CSV"
|
|
||||||
Then GET /v1/activity/export is sent with category=auth and range=30d and without page or size
|
|
||||||
And while it is in flight the button reads "Preparing file…" and is disabled
|
|
||||||
When it resolves 200 with a text/csv body
|
|
||||||
Then the file is downloaded as "activity.csv" and a toast appears: color success, icon
|
|
||||||
i-lucide-circle-check, title "Export started. Your file will download shortly."
|
|
||||||
And the button returns to "Export CSV", enabled
|
|
||||||
|
|
||||||
Scenario Outline: Export — a failure raises an error toast and re-enables the button
|
|
||||||
Given the Default state has loaded
|
|
||||||
When the user activates "Export CSV" and GET /v1/activity/export <failure>
|
|
||||||
Then a toast appears: color error, icon i-lucide-circle-x, title "Couldn't export activity.
|
|
||||||
Try again."
|
|
||||||
And nothing is downloaded and the button returns to "Export CSV", enabled
|
|
||||||
|
|
||||||
Examples:
|
|
||||||
| failure |
|
|
||||||
| resolves with a 500 response |
|
|
||||||
| resolves with a 403 response |
|
|
||||||
| never reaches the server |
|
|
||||||
|
|
||||||
Scenario: Details — a row opens the slide-over and focus returns on close
|
Scenario: Details — a row opens the slide-over and focus returns on close
|
||||||
Given the Default state has loaded
|
Given the Default state has loaded
|
||||||
When the user activates the second row (click, or Enter with the row focused)
|
When the user activates the second row (click, or Enter with the row focused)
|
||||||
@@ -661,7 +638,7 @@ Feature: Activity screen, details slide-over and My activity
|
|||||||
When the user navigates to /activity
|
When the user navigates to /activity
|
||||||
Then the title reads "My activity", the subtitle "Everything you've done on this site." and
|
Then the title reads "My activity", the subtitle "Everything you've done on this site." and
|
||||||
the breadcrumb "My activity"
|
the breadcrumb "My activity"
|
||||||
And no summary strip, no Person filter and no "Export CSV" are rendered
|
And no summary strip, no Person filter and no "Export" are rendered
|
||||||
And the table has the columns When, Action, Target, Outcome and no Actor column
|
And the table has the columns When, Action, Target, Outcome and no Actor column
|
||||||
And the cards show no actor line below md
|
And the cards show no actor line below md
|
||||||
And GET /v1/activity is sent with range=7d, page=1, size=25 and no actor parameter, and
|
And GET /v1/activity is sent with range=7d, page=1, size=25 and no actor parameter, and
|
||||||
@@ -683,7 +660,7 @@ Feature: Activity screen, details slide-over and My activity
|
|||||||
Scenario: The French interface composes sentences and chrome in French
|
Scenario: The French interface composes sentences and chrome in French
|
||||||
Given the language is French and the Default state has loaded as owner
|
Given the language is French and the Default state has loaded as owner
|
||||||
Then the title reads "Activité", the strip labels, filter placeholders, badges, pager and
|
Then the title reads "Activité", the strip labels, filter placeholders, badges, pager and
|
||||||
"Exporter en CSV" are in French, the sentences use the French templates and day
|
"Exporter" are in French, the sentences use the French templates and day
|
||||||
separators read "Aujourd'hui", "Hier" or "3 oct. 2026"
|
separators read "Aujourd'hui", "Hier" or "3 oct. 2026"
|
||||||
And the Security sub-line reads "11 signalés"
|
And the Security sub-line reads "11 signalés"
|
||||||
And every new English string of this screen has a French entry in messages.ts
|
And every new English string of this screen has a French entry in messages.ts
|
||||||
|
|||||||
@@ -52,7 +52,7 @@ zeros) and `summaryNone` (all zeros). The list response is `{ items, total, page
|
|||||||
1. **Navigation** — sidebar and drawer list Home, Articles, Media, Users, Activity, Integration,
|
1. **Navigation** — sidebar and drawer list Home, Articles, Media, Users, Activity, Integration,
|
||||||
Settings in order; "Activity" has the `i-lucide-history` icon, links to /activity, has
|
Settings in order; "Activity" has the `i-lucide-history` icon, links to /activity, has
|
||||||
aria-current="page" on /activity and none elsewhere; breadcrumb and mobile title "Activity".
|
aria-current="page" on /activity and none elsewhere; breadcrumb and mobile title "Activity".
|
||||||
2. **Default (owner)** — assert header texts, enabled "Export CSV", the four strip cards (labels,
|
2. **Default (owner)** — assert header texts, enabled "Export", the four strip cards (labels,
|
||||||
"1,284", "9", "6", "11", sub-lines "12% vs previous 7 days" with the trending-up icon, "7
|
"1,284", "9", "6", "11", sub-lines "12% vs previous 7 days" with the trending-up icon, "7
|
||||||
people, 2 API keys", "0.5% of all actions" with icon `circle-x`, "11 flagged" with icon
|
people, 2 API keys", "0.5% of all actions" with icon `circle-x`, "11 flagged" with icon
|
||||||
`shield-alert`), the filter bar (placeholder, "All people", "All categories", Outcome All
|
`shield-alert`), the filter bar (placeholder, "All people", "All categories", Outcome All
|
||||||
@@ -85,7 +85,7 @@ zeros) and `summaryNone` (all zeros). The list response is `{ items, total, page
|
|||||||
antérieure" and "Aucun changement"; ranges Today, 30 days and Custom give "vs previous day",
|
antérieure" and "Aucun changement"; ranges Today, 30 days and Custom give "vs previous day",
|
||||||
"vs previous 30 days" and "vs previous period".
|
"vs previous 30 days" and "vs previous period".
|
||||||
10. **Empty, no activity yet** — `summaryNone`, items []; assert "No data yet" on two cards, the
|
10. **Empty, no activity yet** — `summaryNone`, items []; assert "No data yet" on two cards, the
|
||||||
calm lines on the other two, the empty panel copy and icon, a disabled "Export CSV", no table
|
calm lines on the other two, the empty panel copy and icon, a disabled "Export", no table
|
||||||
header and no pager.
|
header and no pager.
|
||||||
11. **Empty, filters match nothing** — type "sitemap", choose Category "Media" and Outcome
|
11. **Empty, filters match nothing** — type "sitemap", choose Category "Media" and Outcome
|
||||||
"Failed", resolve items []; assert chips, empty panel copy, "Clear filters", enabled export;
|
"Failed", resolve items []; assert chips, empty panel copy, "Clear filters", enabled export;
|
||||||
@@ -122,14 +122,8 @@ zeros) and `summaryNone` (all zeros). The list response is `{ items, total, page
|
|||||||
22. **Mobile list and sheet** — below md assert cards (actor line, sentence, badges, "Target
|
22. **Mobile list and sheet** — below md assert cards (actor line, sentence, badges, "Target
|
||||||
deleted"), "Filters" with the badge count, the sheet content and footer ("Show 6 results", "Show
|
deleted"), "Filters" with the badge count, the sheet content and footer ("Show 6 results", "Show
|
||||||
1 result"), two date fields for Custom, and that "Show … results" closes it.
|
1 result"), two date fields for Custom, and that "Show … results" closes it.
|
||||||
23. **Export success** — click "Export CSV" with filters applied; assert one request to
|
23. **Export** — superseded by activity_filter_cards_and_export.qa.md (menu, dialog, toasts).
|
||||||
`/v1/activity/export` with the list filters and no `page` or `size`, "Preparing file…" and
|
24. **Export failure** — superseded by activity_filter_cards_and_export.qa.md.
|
||||||
disabled while pending, an object URL created and an anchor clicked with
|
|
||||||
`download="activity.csv"`, the success toast (color success, icon `i-lucide-circle-check`,
|
|
||||||
title "Export started. Your file will download shortly."), and the button back to "Export CSV".
|
|
||||||
24. **Export failure, Examples-driven** — 500, 403 and `NetworkError`; assert the error toast
|
|
||||||
(color error, icon `i-lucide-circle-x`, title "Couldn't export activity. Try again."), no
|
|
||||||
download, button re-enabled.
|
|
||||||
25. **Details open and close** — click, then Enter on a focused row; assert the title, the selected
|
25. **Details open and close** — click, then Enter on a focused row; assert the title, the selected
|
||||||
row class, the footer "Event 2 of 1,284"; close with Escape, the close button and the scrim and
|
row class, the footer "Event 2 of 1,284"; close with Escape, the close button and the scrim and
|
||||||
assert focus on the row.
|
assert focus on the row.
|
||||||
@@ -156,7 +150,7 @@ zeros) and `summaryNone` (all zeros). The list response is `{ items, total, page
|
|||||||
request to `/summary` or `/export` and no `actor` parameter; pager "Showing 1–25 of 41"; empty
|
request to `/summary` or `/export` and no `actor` parameter; pager "Showing 1–25 of 41"; empty
|
||||||
state copy; details "Event 1 of 41" with previous disabled.
|
state copy; details "Event 1 of 41" with previous disabled.
|
||||||
31. **French** — `setLocale('fr')`; assert the chrome strings (Activity "Activité", My activity
|
31. **French** — `setLocale('fr')`; assert the chrome strings (Activity "Activité", My activity
|
||||||
"Mon activité", Export CSV "Exporter en CSV", Preparing file… "Préparation du fichier…",
|
"Mon activité", Export CSV "Exporter", Preparing file… "Préparation du fichier…",
|
||||||
Total actions "Actions au total", Active people "Personnes actives", Failed actions "Actions
|
Total actions "Actions au total", Active people "Personnes actives", Failed actions "Actions
|
||||||
en échec", Security events "Événements de sécurité", Succeeded "Réussie", Failed "Échec", Not
|
en échec", Security events "Événements de sécurité", Succeeded "Réussie", Failed "Échec", Not
|
||||||
signed in "Non connecté", Activity details "Détails de l'activité", Previous event and Next
|
signed in "Non connecté", Activity details "Détails de l'activité", Previous event and Next
|
||||||
@@ -199,14 +193,14 @@ the sub-line "11 flagged". Total is 1284 with page size 25 for the owner and 41
|
|||||||
|
|
||||||
- [ ] Loading: both requests with `hang: true`; the setup waits 150 ms or more so the skeleton
|
- [ ] Loading: both requests with `hang: true`; the setup waits 150 ms or more so the skeleton
|
||||||
strip and rows are drawn before the capture.
|
strip and rows are drawn before the capture.
|
||||||
- [ ] Empty, no activity yet: list `items: [], total: 0`, summary `summaryNone`; "Export CSV"
|
- [ ] Empty, no activity yet: list `items: [], total: 0`, summary `summaryNone`; "Export"
|
||||||
disabled.
|
disabled.
|
||||||
- [ ] Empty, filters match nothing: the board applies Search "sitemap", Category "Media", Outcome
|
- [ ] Empty, filters match nothing: the board applies Search "sitemap", Category "Media", Outcome
|
||||||
"Failed" (steps type and select them, or the mock answers with the filtered query), list
|
"Failed" (steps type and select them, or the mock answers with the filtered query), list
|
||||||
`items: [], total: 0`, summary Default.
|
`items: [], total: 0`, summary Default.
|
||||||
- [ ] Error with retry: list 500, summary Default; the alert, disabled export, strip drawn.
|
- [ ] Error with retry: list 500, summary Default; the alert, disabled export, strip drawn.
|
||||||
- [ ] Forbidden (403): list 403, summary 403; session with a non-admin role as the board does
|
- [ ] Forbidden (403): list 403, summary 403; session with a non-admin role as the board does
|
||||||
(`role: 'user'`), so no "Export CSV".
|
(`role: 'user'`), so no "Export".
|
||||||
- [ ] My activity, Empty: `activityEditorSession`, list `items: [], total: 0`.
|
- [ ] My activity, Empty: `activityEditorSession`, list `items: [], total: 0`.
|
||||||
- [ ] skip: clock-sensitive. Default, large dataset: `skip: 'clock-sensitive'` (day separators and
|
- [ ] skip: clock-sensitive. Default, large dataset: `skip: 'clock-sensitive'` (day separators and
|
||||||
"2 min ago" depend on the real clock). Prints SKIP, never investigated or date-frozen.
|
"2 min ago" depend on the real clock). Prints SKIP, never investigated or date-frozen.
|
||||||
@@ -218,7 +212,7 @@ the sub-line "11 flagged". Total is 1284 with page size 25 for the owner and 41
|
|||||||
the rows behind the scrim show relative times and the panel shows the browser's local
|
the rows behind the scrim show relative times and the panel shows the browser's local
|
||||||
time. Their Vitest coverage is cases 3, 5, 25 to 30.
|
time. Their Vitest coverage is cases 3, 5, 25 to 30.
|
||||||
- [ ] Layout, from `ActivityFrame.dc.html`, not `components.md`: header row is the title block
|
- [ ] Layout, from `ActivityFrame.dc.html`, not `components.md`: header row is the title block
|
||||||
(20 px/28 px title) on the left and the 32 px (44 px mobile) "Export CSV" button on the right,
|
(20 px/28 px title) on the left and the 32 px (44 px mobile) "Export" button on the right,
|
||||||
aligned to the bottom; the strip is 4 columns with a 12 px gap on desktop and a clipped row
|
aligned to the bottom; the strip is 4 columns with a 12 px gap on desktop and a clipped row
|
||||||
of 156 px cards with an 8 px gap on mobile; the table header is 36 px, day rows 32 px, rows at
|
of 156 px cards with an 8 px gap on mobile; the table header is 36 px, day rows 32 px, rows at
|
||||||
least 52 px; the slide-over is 480 px wide on desktop, the bottom sheet 88 % high.
|
least 52 px; the slide-over is 480 px wide on desktop, the bottom sheet 88 % high.
|
||||||
@@ -238,7 +232,7 @@ the sub-line "11 flagged". Total is 1284 with page size 25 for the owner and 41
|
|||||||
the right sentences, the shield marker on the failed login, the Succeeded and Failed badges, the
|
the right sentences, the shield marker on the failed login, the Succeeded and Failed badges, the
|
||||||
summary numbers and the sparkline bars; apply each filter and each card; page through with size
|
summary numbers and the sparkline bars; apply each filter and each card; page through with size
|
||||||
25, 50 and 100; open the details across a page boundary.
|
25, 50 and 100; open the details across a page boundary.
|
||||||
- **Real CSV** — click "Export CSV" with and without filters and open `activity.csv`: columns
|
- **Real CSV** — click "Export" with and without filters and open `activity.csv`: columns
|
||||||
`when,actor,action,target,outcome,source,ip`, the filtered rows only, no page or size applied,
|
`when,actor,action,target,outcome,source,ip`, the filtered rows only, no page or size applied,
|
||||||
neutralised cells that start with `=`, `+`, `-` or `@`; confirm the browser download prompt and
|
neutralised cells that start with `=`, `+`, `-` or `@`; confirm the browser download prompt and
|
||||||
the two toasts.
|
the two toasts.
|
||||||
|
|||||||
@@ -155,7 +155,7 @@ Feature: API keys screen
|
|||||||
"\"Nightly media import\" is ready. Copy the key and store it somewhere safe."
|
"\"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
|
And a warning alert (UAlert, color warning, triangle-alert icon) reads "You won't be able to
|
||||||
see this key again."
|
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 full key from the response is shown in a CodeSnippet with the single tab "API key" and a "Copy" button (icon copy, accessible name "Copy code"), focused when the modal opens
|
||||||
And the note "Closing this window discards the key from the screen. Copy it first." is shown
|
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"
|
And the only button is a primary "Done"
|
||||||
|
|
||||||
@@ -181,8 +181,7 @@ Feature: API keys screen
|
|||||||
Given the key reveal is open
|
Given the key reveal is open
|
||||||
When the user activates "Copy"
|
When the user activates "Copy"
|
||||||
Then the full key is written to the clipboard
|
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
|
And the button shows icon check and text "Copied" in the success color, announced politely
|
||||||
technology
|
|
||||||
When 2 seconds elapse
|
When 2 seconds elapse
|
||||||
Then the button reverts to icon copy and text "Copy"
|
Then the button reverts to icon copy and text "Copy"
|
||||||
|
|
||||||
|
|||||||
@@ -68,8 +68,8 @@ layout cases at desktop and below-md (mock `matchMedia`).
|
|||||||
errors clear when fixed.
|
errors clear when fixed.
|
||||||
9. **Create key: name too long** - 75 characters; counter, error class and text, no request.
|
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
|
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
|
key; the reveal: title, text, warning alert, key equal to the mocked `key` inside a CodeSnippet with
|
||||||
"Done".
|
the single tab "API key", "Copy" (named "Copy code") focused on open, note, only "Done".
|
||||||
11. **Create key: expiry** - date D + 30 days; assert expires_at is 23:59:59 local on that day
|
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
|
with the local offset. Examples today (sent), yesterday (blocked), tomorrow (sent); build the
|
||||||
dates from `new Date()` in the test.
|
dates from `new Date()` in the test.
|
||||||
@@ -137,7 +137,7 @@ States:
|
|||||||
- [ ] Create key
|
- [ ] Create key
|
||||||
- [ ] Create key: validation
|
- [ ] Create key: validation
|
||||||
- [ ] Create key: name too long
|
- [ ] Create key: name too long
|
||||||
- [ ] One-time reveal
|
- [ ] One-time reveal (re-run after the CodeSnippet migration, within 10 %)
|
||||||
- [ ] One-time reveal: copied (timer-driven, so it is checked)
|
- [ ] One-time reveal: copied (timer-driven, so it is checked)
|
||||||
- [ ] Revoke: confirm
|
- [ ] Revoke: confirm
|
||||||
- [ ] Revoked (list with the revoked row and the toast)
|
- [ ] Revoked (list with the revoked row and the toast)
|
||||||
|
|||||||
@@ -0,0 +1,124 @@
|
|||||||
|
Feature: Article bodies have no length limit and the body is optional
|
||||||
|
|
||||||
|
As a verified RenewCMS owner
|
||||||
|
I want to create an article with only a title and write articles of any length
|
||||||
|
So that starting a draft is one field and long articles are never blocked
|
||||||
|
|
||||||
|
Background:
|
||||||
|
Given POST /v1/article/ and PATCH /v1/article/{id} sit inside the jwt-protected group
|
||||||
|
And the request structs PostArticle and UpdateArticleBody validate through validator.Validate.Struct
|
||||||
|
And PostArticle.Title keeps validate "required,min=3,max=200"
|
||||||
|
And PostArticle.Body and UpdateArticleBody.Body carry no validate tag: no max, no required
|
||||||
|
And a body is stored and returned as given; an absent "body" key is treated as ""
|
||||||
|
And success bodies are the article JSON (id, title, body, body_format, is_online, created_at, updated_at)
|
||||||
|
And a new article is created offline (is_online false)
|
||||||
|
|
||||||
|
Scenario Outline: Create with only a title succeeds in every body format
|
||||||
|
Given a valid jwt cookie for a verified user
|
||||||
|
When the client sends POST /v1/article/<query> with JSON <payload>
|
||||||
|
Then the status is 201
|
||||||
|
And the response JSON has title "Choosing tiles for a small bathroom", is_online false, body_format "<format>" and body <rendered>
|
||||||
|
And the fake article repository holds one article with Body ""
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| query | payload | format | rendered |
|
||||||
|
| | {"title": "Choosing tiles for a small bathroom"} | markdown | "" |
|
||||||
|
| ?format=html | {"title": "Choosing tiles for a small bathroom"} | html | "" |
|
||||||
|
| ?format=json | {"title": "Choosing tiles for a small bathroom"} | json | [] |
|
||||||
|
| | {"title": "Choosing tiles for a small bathroom", "body": ""} | markdown | "" |
|
||||||
|
|
||||||
|
Scenario: A body of 120,000 characters is accepted on create
|
||||||
|
Given a valid jwt cookie for a verified user
|
||||||
|
When the client sends POST /v1/article/ with a title of 3 characters or more and a body of 120000 characters
|
||||||
|
Then the status is 201
|
||||||
|
And the repository holds the full 120000-character body, unmodified
|
||||||
|
|
||||||
|
Scenario Outline: Update the body with no length limit
|
||||||
|
Given an article with id 12 exists
|
||||||
|
And a valid jwt cookie for a verified user
|
||||||
|
When the client sends PATCH /v1/article/12 with a body of <length> characters
|
||||||
|
Then the status is 200
|
||||||
|
And the repository body for article 12 has <length> characters
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| length |
|
||||||
|
| 10001 |
|
||||||
|
| 120000 |
|
||||||
|
|
||||||
|
Scenario: Update the body to empty
|
||||||
|
Given an article with id 12 exists with a non-empty body
|
||||||
|
When the client sends PATCH /v1/article/12 with JSON {"body": ""}
|
||||||
|
Then the status is 200 and the repository body is ""
|
||||||
|
And GET /v1/article/12?format=json returns body []
|
||||||
|
|
||||||
|
Scenario Outline: Title rules are unchanged
|
||||||
|
Given a valid jwt cookie for a verified user
|
||||||
|
When the client sends POST /v1/article/ with JSON <payload>
|
||||||
|
Then the status is 400, the response is plain text from http.Error, and no article is created
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| payload |
|
||||||
|
| {"body": "Hello"} |
|
||||||
|
| {"title": "Ti", "body": "Hello"} |
|
||||||
|
| {"title": "<201 characters>"} |
|
||||||
|
|
||||||
|
Scenario: Existing guards on PATCH are unchanged
|
||||||
|
When PATCH /v1/article/abc is sent
|
||||||
|
Then the status is 400 with the uint32 id error text
|
||||||
|
When PATCH /v1/article/999 is sent and no such article exists
|
||||||
|
Then the status is 404 with the article-not-found text
|
||||||
|
When PATCH /v1/article/12 is sent with malformed JSON
|
||||||
|
Then the status is 400 with apperr.BodyErrorMessage
|
||||||
|
|
||||||
|
Scenario: The SPA no longer limits or counts the body
|
||||||
|
Given the Vue SPA
|
||||||
|
Then the constant BODY_MAX_LENGTH no longer exists
|
||||||
|
And the CharacterCounter component stays (ProfileView and CreateApiKeyModal still use it) but EditorView and NewArticleModal no longer import it
|
||||||
|
And the editor has no "Near the limit" or "Too long" state
|
||||||
|
|
||||||
|
Scenario: Editor status bar shows a neutral count
|
||||||
|
Given the editor is open on /article/12/edit with a loaded article whose body has 1204 words and 7318 characters
|
||||||
|
Then the EditorStatusBar reads "1,204 words · 7,318 characters"
|
||||||
|
And the count updates as the body changes
|
||||||
|
And a new empty article reads "0 words · 0 characters"
|
||||||
|
And the count carries no warning, error colour or icon at any length
|
||||||
|
|
||||||
|
Scenario: Editor states at 120,000 characters
|
||||||
|
Given the editor holds an article body of 120000 characters (19,845 words)
|
||||||
|
Then the count reads "19,845 words · 120,000 characters", neutral
|
||||||
|
When the body is edited
|
||||||
|
Then the state is Unsaved changes, and Save and Publish ("Save and publish") are enabled
|
||||||
|
When the user saves and PATCH /v1/article/12 is pending
|
||||||
|
Then the status shows the spinner with "Saving 120,000 characters. This can take a few seconds.", Save is disabled and the page stays editable
|
||||||
|
When PATCH resolves 200
|
||||||
|
Then the status reads Saved with the time and the count is unchanged
|
||||||
|
When PATCH instead resolves 500, 413 or a network failure
|
||||||
|
Then the editor shows "Couldn't save. Your text is kept. Retry." and the body is unchanged
|
||||||
|
And Retry resends the same content
|
||||||
|
|
||||||
|
Scenario: NewArticleModal is title-only
|
||||||
|
Given NewArticleModal is open
|
||||||
|
Then it shows the Title field with its "0 / 200" counter and "3 to 200 characters." help, "Cancel" and "Create draft"
|
||||||
|
And there is no First paragraph field
|
||||||
|
When the user submits a valid title
|
||||||
|
Then POST /v1/article/ is sent with JSON {"title": "<title>"} (no body key)
|
||||||
|
|
||||||
|
Scenario Outline: NewArticleModal states
|
||||||
|
Given NewArticleModal is open with Title "<title>"
|
||||||
|
When <trigger>
|
||||||
|
Then <outcome>
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| title | trigger | outcome |
|
||||||
|
| | it opens | Default (empty): Title focused, counter "0 / 200" |
|
||||||
|
| Ti | the field blurs or Create draft is pressed | Validation: "Use at least 3 characters.", counter in error style, no request |
|
||||||
|
| Choosing tiles for a small bathroom | Create draft is pressed | Submitting: "Creating…", Title and buttons disabled, not dismissible |
|
||||||
|
| Choosing tiles for a small bathroom | POST resolves 201 (id 42) | modal closes, navigates to /article/42/edit, toast "Draft created" id "article-created-42" |
|
||||||
|
| Choosing tiles for a small bathroom | POST resolves 400 | Title rejected: "Check this title and try again." and alert "Something in the form isn't valid. Check the highlighted fields." |
|
||||||
|
| Choosing tiles for a small bathroom | POST resolves 500 or never reaches server | Error: alert "Couldn't create the article. Your text is still here. Try again in a moment." |
|
||||||
|
|
||||||
|
Scenario: Integration API reference no longer says max 10000
|
||||||
|
Given the Integration screen's request-body tables for POST /v1/article/ and PATCH /v1/article/{id}
|
||||||
|
Then POST lists: title string required 3-200; body string optional, no length limit
|
||||||
|
And PATCH lists: body string optional, no length limit
|
||||||
|
And no text on the screen contains "max 10000"
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
# QA: unlimited, optional article body
|
||||||
|
|
||||||
|
## Part A. HTTP (Go, test/article_body_unlimited_http_test.go)
|
||||||
|
|
||||||
|
Setup: in-memory fake article repository plus the real markdown converter as BodyRenderer (so the "json" format of an empty body is genuinely exercised). Build CreateArticle, GetArticle, UpdateArticle use cases and the article handler via NewHandler(...). Mount on a fresh chi.NewRouter() that mirrors api/router.go: POST /v1/article/ and PATCH /v1/article/{id} inside jwtauth.Verifier + Authenticator with a test jwtauth.New("HS256", ...) token. Call validator.InitValidator(). Use httptest. No live server, no real SQLite, no real SMTP.
|
||||||
|
|
||||||
|
1. POST title-only, one request per format (default markdown, html, json): assert 201, body_format, the body value in the JSON response (the Examples table), and that the fake repo has Body "". The json case must produce valid JSON (`[]`) and not fail encoding.
|
||||||
|
2. POST with "body": "" explicitly: same as 1.
|
||||||
|
3. POST with strings.Repeat("a", 120000): 201 and the repo body length is 120000.
|
||||||
|
4. PATCH with 10001 and 120000 characters: 200 and the stored length matches.
|
||||||
|
5. PATCH with "body": "": 200, then GET ?format=json returns body [].
|
||||||
|
6. POST title missing, "Ti", and 201 characters: 400, plain text, repo count unchanged.
|
||||||
|
7. PATCH guards: bad id gives 400, unknown id gives 404, malformed JSON gives 400.
|
||||||
|
8. Update existing tests: in test/edit_article_body_http_test.go remove the case "body over 10000 characters" (line 172) from the 400 table, and any missing-body rejection case (flip it to accepted if present).
|
||||||
|
9. Grep that the Integration source no longer contains "max 10000" (see Part C).
|
||||||
|
|
||||||
|
## Part B. SPA
|
||||||
|
|
||||||
|
Automated (Vitest, `task test:web`). Until the SPA runner exists, report NOT RUN rather than pass.
|
||||||
|
|
||||||
|
- EditorView.spec.ts: delete the "Near the limit" and "Too long" describes (around lines 392 and 405). Add: the neutral count "1,204 words · 7,318 characters" with mocked GET (fixture of 1,204 words / 7,318 characters); "0 words · 0 characters" for an empty article; at 120,000 characters (19,845 words): neutral count, Save and Publish enabled, then Saving ("Saving 120,000 characters. This can take a few seconds."), Saved (count unchanged), and Save failed (PATCH 500, 413 and network error, body kept, Retry resending the same payload).
|
||||||
|
- CharacterCounter.vue and web/src/components/__tests__/CharacterCounter.spec.ts stay (ProfileView and CreateApiKeyModal use them).
|
||||||
|
- NewArticleModal spec: Default (empty), Validation ("Ti"), Submitting, 201 handoff, Title rejected (400), Server error (500 and network). Assert the POST payload is exactly {"title": "..."} and that no First paragraph field exists.
|
||||||
|
- Static check: grep web/src for BODY_MAX_LENGTH, and for CharacterCounter imports in EditorView and NewArticleModal, returns nothing.
|
||||||
|
|
||||||
|
Visual (`task visual:check -- editor`, `task visual:check -- new-article`). Hard gate: every capture within 10 %, desktop and mobile, light and dark.
|
||||||
|
|
||||||
|
- editor: states Saved, Unsaved changes, Saving, Save failed, and Very long article (6-9). Reuse the board's sample data ("1,204 words · 7,318 characters", "19,845 words · 120,000 characters", "Saving 120,000 characters. This can take a few seconds."). States showing time-dependent content (the "Saved at" time, "Updated Today, 11:02") are `skip: clock-sensitive`.
|
||||||
|
- new-article: Default, Validation, Submitting, Title rejected, Error. Mocks reuse "Choosing tiles for a small bathroom". The user will update the design .md files only; the board .dc.html frames may still draw a body line in Submitting / Title rejected / Error, so a visual diff there is a known follow-up to raise, not a reason to keep the field.
|
||||||
|
- Remove the "Near the limit" and "Too long" entries from web/visual/states.ts (around lines 4712 and 4720) if they belong to the editor group.
|
||||||
|
|
||||||
|
Manual: keyboard and focus order in the modal (Title focused on open, Esc blocked while submitting); hover and motion; typing responsiveness in a real browser at 120,000 characters.
|
||||||
|
|
||||||
|
## Part C. Docs consistency
|
||||||
|
|
||||||
|
- The Integration screen reference text shows no "max 10000" (view /integration).
|
||||||
@@ -0,0 +1,115 @@
|
|||||||
|
Feature: Articles list remembers the chosen page size
|
||||||
|
|
||||||
|
As a verified RenewCMS user
|
||||||
|
I want the page size I choose on the Articles list to be remembered
|
||||||
|
So that I do not have to pick it again each time I come back or refresh
|
||||||
|
|
||||||
|
Background:
|
||||||
|
Given this slice amends features/articles_pagination_screen.feature; the URL keeps ?size= as in that spec and no visual or API change is made (docs/design/ is untouched)
|
||||||
|
And the size options stay "5 per page", "25 per page", "50 per page", "100 per page" and the default stays 25
|
||||||
|
And the chosen size is stored in localStorage under the key renewcms-page-size-articles as the bare number (for example 5), one key per paginated list; only the Articles list uses it today
|
||||||
|
And only choosing a size in the page-size select writes the stored value; loading a URL never writes it
|
||||||
|
And an explicit valid ?size= in the URL is authoritative for that load and does not change the stored value
|
||||||
|
And an invalid ?size= in the URL falls back to 25, never to the stored value, and is replaced in the URL (features/articles_pagination_screen.feature scenario 10b)
|
||||||
|
And a stored value that is not 5, 25, 50 or 100 is treated as absent
|
||||||
|
And localStorage that is unavailable or throws on read or write never raises an error or breaks the page: reads act as absent and writes are ignored
|
||||||
|
And logout does not clear the stored size
|
||||||
|
And a size change still resets page to 1 and drops page from the URL
|
||||||
|
And the requests are GET /v1/article/?format=html&page=P&size=S&q=Q&status=T as in features/articles_pagination_api.feature
|
||||||
|
|
||||||
|
Scenario Outline: Choosing a size stores it
|
||||||
|
Given nothing is stored and the user is on /article
|
||||||
|
When the user chooses "<label>" in the page-size select
|
||||||
|
Then localStorage renewcms-page-size-articles is "<stored>"
|
||||||
|
And on success the URL is <url>
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| label | stored | url |
|
||||||
|
| 5 per page | 5 | /article?size=5 |
|
||||||
|
| 25 per page | 25 | /article |
|
||||||
|
| 50 per page | 50 | /article?size=50 |
|
||||||
|
| 100 per page | 100 | /article?size=100 |
|
||||||
|
|
||||||
|
Scenario: The stored size is restored when the list is opened without a size
|
||||||
|
Given localStorage renewcms-page-size-articles is "5"
|
||||||
|
When the user navigates to /article
|
||||||
|
Then GET ...&page=1&size=5 is sent
|
||||||
|
And the page-size select reads "5 per page"
|
||||||
|
And on success the URL is replaced (no history entry) by /article?size=5
|
||||||
|
|
||||||
|
Scenario: The size survives leaving the list and coming back
|
||||||
|
Given the user chose "5 per page" on /article
|
||||||
|
When the user navigates to /, then back to /article
|
||||||
|
Then GET ...&size=5 is sent and the select reads "5 per page"
|
||||||
|
|
||||||
|
Scenario: The size survives a full page refresh
|
||||||
|
Given the user chose "5 per page" on /article
|
||||||
|
When the page is reloaded on /article?size=5, or on /article with the URL typed in without a size
|
||||||
|
Then GET ...&size=5 is sent and the select reads "5 per page"
|
||||||
|
|
||||||
|
Scenario: The stored size is kept across paging, search, tabs and sort
|
||||||
|
Given localStorage renewcms-page-size-articles is "50" and the user is on /article?size=50
|
||||||
|
When the user activates Next, switches to the "Drafts" tab, sorts by Title or searches "plaster"
|
||||||
|
Then every request carries size=50 and the stored value stays "50"
|
||||||
|
|
||||||
|
Scenario: Changing the size again replaces the stored one
|
||||||
|
Given localStorage renewcms-page-size-articles is "5"
|
||||||
|
When the user chooses "100 per page"
|
||||||
|
Then localStorage renewcms-page-size-articles is "100"
|
||||||
|
And the next visit to /article without a size sends size=100
|
||||||
|
|
||||||
|
Scenario: Returning to 25 is remembered too
|
||||||
|
Given localStorage renewcms-page-size-articles is "5"
|
||||||
|
When the user chooses "25 per page"
|
||||||
|
Then localStorage renewcms-page-size-articles is "25"
|
||||||
|
And the next visit to /article sends size=25 and the URL stays /article
|
||||||
|
|
||||||
|
Scenario: An explicit size in the URL wins and is not stored
|
||||||
|
Given localStorage renewcms-page-size-articles is "5"
|
||||||
|
When the user navigates to /article?size=100
|
||||||
|
Then GET ...&size=100 is sent and the select reads "100 per page"
|
||||||
|
And localStorage renewcms-page-size-articles is still "5"
|
||||||
|
And a later visit to /article sends size=5
|
||||||
|
|
||||||
|
Scenario: An explicit page with no size uses the stored size
|
||||||
|
Given localStorage renewcms-page-size-articles is "5"
|
||||||
|
When the user navigates to /article?page=3
|
||||||
|
Then GET ...&page=3&size=5 is sent and on success the URL is replaced by /article?page=3&size=5
|
||||||
|
|
||||||
|
Scenario Outline: An invalid stored value falls back to 25
|
||||||
|
Given localStorage renewcms-page-size-articles is "<stored>"
|
||||||
|
When the user navigates to /article
|
||||||
|
Then GET ...&page=1&size=25 is sent, the select reads "25 per page" and the URL is /article
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| stored |
|
||||||
|
| 10 |
|
||||||
|
| abc |
|
||||||
|
| 0 |
|
||||||
|
| -5 |
|
||||||
|
| 25.5 |
|
||||||
|
| |
|
||||||
|
|
||||||
|
Scenario: An invalid size in the URL ignores the stored one
|
||||||
|
Given localStorage renewcms-page-size-articles is "5"
|
||||||
|
When the user navigates to /article?size=10
|
||||||
|
Then GET ... is sent with size=25 and the URL is replaced by /article
|
||||||
|
And localStorage renewcms-page-size-articles is still "5"
|
||||||
|
|
||||||
|
Scenario Outline: Unavailable storage never breaks the list
|
||||||
|
Given localStorage <failure>
|
||||||
|
When the user navigates to /article
|
||||||
|
Then GET ...&page=1&size=25 is sent, the list renders and no error is shown
|
||||||
|
When the user chooses "50 per page"
|
||||||
|
Then GET ...&page=1&size=50 is sent and the URL is /article?size=50
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| failure |
|
||||||
|
| throws on getItem |
|
||||||
|
| throws on setItem (quota) |
|
||||||
|
| is undefined |
|
||||||
|
|
||||||
|
Scenario: Logging out keeps the stored size
|
||||||
|
Given localStorage renewcms-page-size-articles is "5"
|
||||||
|
When the user logs out and logs in again and opens /article
|
||||||
|
Then GET ...&size=5 is sent
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
# QA: Articles page-size memory (SPA)
|
||||||
|
|
||||||
|
No Go or HTTP test applies: nothing outside web/ changes.
|
||||||
|
|
||||||
|
## Automated (Vitest, task test:web)
|
||||||
|
|
||||||
|
Extend or sit beside web/src/views/__tests__/ArticlesPagination.spec.ts and reuse articleEnvelope.ts for the mocked GET /v1/article/ envelope (total 312, size from the query). localStorage.clear() in beforeEach; fresh router per test. Assert on the mocked request query string, the select label, the router URL and localStorage.
|
||||||
|
|
||||||
|
1. Choosing 5 / 25 / 50 / 100 writes "5" / "25" / "50" / "100" under renewcms-page-size-articles; URLs /article?size=5, /article, ?size=50, ?size=100.
|
||||||
|
2. Stored "5", open /article: request carries size=5 and page=1, select reads "5 per page", URL replaced (router.replace, no history entry added) with ?size=5.
|
||||||
|
3. Choose 5, navigate to another route and back (mount again): size=5 requested.
|
||||||
|
4. Choose 5, remount the app on /article and on /article?size=5 (simulated refresh): size=5 requested.
|
||||||
|
5. Stored "50", on ?size=50: Next, Drafts tab, sort Title, search "plaster" (fake timers for the 120 ms debounce, not the system date): every request has size=50, stored value unchanged.
|
||||||
|
6. Stored "5", choose 100: stored "100"; remount sends size=100.
|
||||||
|
7. Stored "5", choose 25: stored "25"; remount sends size=25, URL /article.
|
||||||
|
8. Stored "5", open /article?size=100: size=100 requested, stored still "5"; remount on /article sends size=5.
|
||||||
|
9. Stored "5", open /article?page=3: request page=3&size=5, URL replaced by ?page=3&size=5.
|
||||||
|
10. Invalid stored values 10, abc, 0, -5, 25.5, "": size=25 requested, select "25 per page", URL /article.
|
||||||
|
11. Stored "5", open /article?size=10: size=25 requested, URL /article, stored still "5".
|
||||||
|
12. Storage failures (Storage.prototype.getItem throwing; setItem throwing; window.localStorage undefined): no exception, list renders, size=25 on load, choosing 50 requests size=50 and URL ?size=50.
|
||||||
|
13. Logout (session store reset) leaves the stored value; the next /article sends size=5.
|
||||||
|
14. Unit tests for any read/write helper added next to web/src/lib/pagination.ts: valid values accepted, invalid rejected, errors swallowed.
|
||||||
|
|
||||||
|
## Visual (task visual:check -- articles)
|
||||||
|
|
||||||
|
No visual change is intended. Run the full articles group as a regression and require every capture within 10 %. Setups use the board's own sample data and must not depend on a stored size. Clear localStorage before each capture so a leftover value cannot change the default 25 frame. No state is clock-sensitive for this slice.
|
||||||
|
|
||||||
|
## Manual
|
||||||
|
|
||||||
|
- In a real browser, choose 5 per page, navigate away and back, then hard-refresh: it stays at 5.
|
||||||
|
- Private-window or storage-blocked browser: the list still works at 25 with no error.
|
||||||
|
- Keyboard: the page-size select behaves as before (ArrowDown, Enter, Esc, focus ring), and focus returns to the select after choosing.
|
||||||
|
- Open a copied /article?size=100 link in a profile that has 5 stored: the link shows 100 and the next plain visit shows 5.
|
||||||
@@ -0,0 +1,191 @@
|
|||||||
|
Feature: Paginated article listing
|
||||||
|
|
||||||
|
As an API consumer or the RenewCMS back-office
|
||||||
|
I want GET /v1/article/ to always answer one page of articles with the total and the tab counts
|
||||||
|
So that large sites list articles quickly and the SPA can search, filter and page on the server
|
||||||
|
|
||||||
|
Background:
|
||||||
|
Given GET /v1/article/ is mounted under jwtauth.Verifier only (features/public_article_listing.feature)
|
||||||
|
And a caller is "verified" when the jwt cookie carries a user_id claim whose user has is_verified true, and "public" otherwise (missing, malformed, expired or unverified)
|
||||||
|
And a public caller only ever sees articles with is_online true; a verified caller sees every article
|
||||||
|
And BREAKING CHANGE: the body is no longer a bare JSON array; every successful request, with or without query parameters, answers {"items": [...], "total": N, "page": P, "size": S, "counts": {"all": A, "online": O, "draft": D}} in snake_case
|
||||||
|
And each item is the existing article object (id, title, body, body_format, is_online, created_at, updated_at) and items is [] rather than null
|
||||||
|
And paging follows the Activity convention: page is an integer >= 1 (default 1), size is one of 5, 25, 50, 100 (default 25)
|
||||||
|
And q (optional, max 200 characters; case-insensitive, accent-insensitive, matches anywhere in the title) and status (optional, online or draft) filter the items
|
||||||
|
And total is the number of visible articles matching q and status, before paging; page and size echo the values applied
|
||||||
|
And counts ignores q and status, so the tab counts do not move while the user searches; it respects visibility: for a public caller all equals online and draft is 0
|
||||||
|
And status=draft requested by a public caller matches nothing: items [], total 0
|
||||||
|
And sort (optional) is one of title:asc, title:desc, status:asc, status:desc, created_at:asc, created_at:desc, updated_at:asc, updated_at:desc; the default is updated_at:desc; status orders by is_online (asc puts drafts first); every ordering ends with id descending as the tie-break, so pages are stable and never overlap
|
||||||
|
And sort is mapped to a column and direction through a fixed whitelist in the repository, so request text never reaches the SQL; the same ordering applies on the search path (q) before slicing
|
||||||
|
And a page beyond the last answers 200 with items [] and the real total
|
||||||
|
And an invalid page, size, status, sort or an over-long q answers 400 with the plain-text body "The request cannot be processed due to a mismatch in the format of the body." (apperr.BodyErrorMessage), like GET /v1/activity, validated with validate tags through validator.Validate.Struct
|
||||||
|
And format is validated first: an invalid format still answers 400 "The format must be one of: markdown, html, json."
|
||||||
|
And ListArticlesUseCase reaches the data only through article.Repository; the handler never touches a repository; the repository query uses portable SQL (COUNT, LIMIT/OFFSET, ORDER BY, LIKE)
|
||||||
|
And article.Filters keeps Page 0 and Size 0 meaning "unpaged, every article" for internal callers (purge plan, media listing), which are unchanged
|
||||||
|
|
||||||
|
Scenario: A bare request answers the envelope with the defaults
|
||||||
|
Given the repository holds 30 online articles
|
||||||
|
When a public client sends GET /v1/article/
|
||||||
|
Then the status is 200
|
||||||
|
And the body is an object with page 1, size 25, total 30, 25 items and counts {"all": 30, "online": 30, "draft": 0}
|
||||||
|
|
||||||
|
Scenario Outline: Defaults when only one parameter is given
|
||||||
|
Given the repository holds 60 online articles
|
||||||
|
When a public client sends GET /v1/article/?<query>
|
||||||
|
Then the body has page <page>, size <size>, total 60 and <count> items
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| query | page | size | count |
|
||||||
|
| page=2 | 2 | 25 | 25 |
|
||||||
|
| page=3 | 3 | 25 | 10 |
|
||||||
|
| size=5 | 1 | 5 | 5 |
|
||||||
|
| size=50 | 1 | 50 | 50 |
|
||||||
|
|
||||||
|
Scenario: Items are ordered by last update, newest first, then id descending
|
||||||
|
Given online articles id 1 updated 2026-09-01, id 2 updated 2026-09-03, id 3 updated 2026-09-03
|
||||||
|
When a public client sends GET /v1/article/?size=5
|
||||||
|
Then the item ids are 3, 2, 1
|
||||||
|
|
||||||
|
Scenario Outline: Sort orders the whole list, not just the page
|
||||||
|
Given a verified session and articles
|
||||||
|
| id | title | created_at | updated_at | is_online |
|
||||||
|
| 1 | Banana | 2026-01-01 | 2026-09-03 | true |
|
||||||
|
| 2 | apple | 2026-01-03 | 2026-09-01 | false |
|
||||||
|
| 3 | Cherry | 2026-01-02 | 2026-09-02 | true |
|
||||||
|
When the client sends GET /v1/article/?sort=<sort>
|
||||||
|
Then the item ids are <ids>
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| sort | ids |
|
||||||
|
| updated_at:desc | 1,3,2 |
|
||||||
|
| updated_at:asc | 2,3,1 |
|
||||||
|
| created_at:desc | 2,3,1 |
|
||||||
|
| created_at:asc | 1,3,2 |
|
||||||
|
| title:asc | 2,1,3 |
|
||||||
|
| title:desc | 3,1,2 |
|
||||||
|
| status:asc | 2,3,1 |
|
||||||
|
| status:desc | 3,1,2 |
|
||||||
|
|
||||||
|
Scenario: No sort parameter keeps the default order
|
||||||
|
Given the same articles
|
||||||
|
When the client sends GET /v1/article/
|
||||||
|
Then the item ids are 1,3,2
|
||||||
|
|
||||||
|
Scenario: Equal sort keys fall back to id descending
|
||||||
|
Given three articles with the same title "Same" and ids 1, 2, 3
|
||||||
|
When the client sends GET /v1/article/?sort=title:asc
|
||||||
|
Then the item ids are 3,2,1
|
||||||
|
|
||||||
|
Scenario: Sort is applied before paging
|
||||||
|
Given 12 online articles whose titles sort alphabetically as ids 1..12
|
||||||
|
When a client requests ?sort=title:desc&size=5 for pages 1, 2 and 3
|
||||||
|
Then the pages hold ids 12..8, 7..3 and 2..1 with no repeat
|
||||||
|
|
||||||
|
Scenario: Sort combines with search and status
|
||||||
|
Given a verified session and draft articles "Tile A", "Tile C", "Tile B" and an online one "Tile D"
|
||||||
|
When the client sends GET /v1/article/?q=tile&status=draft&sort=title:asc
|
||||||
|
Then the item titles are "Tile A", "Tile B", "Tile C", total is 3 and counts is unchanged by q, status and sort
|
||||||
|
|
||||||
|
Scenario: Pages partition the list with no overlap
|
||||||
|
Given 12 online articles
|
||||||
|
When a client requests ?page=1&size=5, ?page=2&size=5 and ?page=3&size=5
|
||||||
|
Then the three pages hold 5, 5 and 2 items, total is 12 on each, and no id repeats
|
||||||
|
|
||||||
|
Scenario: A public caller's total and counts cover online articles only
|
||||||
|
Given 5 online and 3 offline articles
|
||||||
|
When a public client sends GET /v1/article/?size=5
|
||||||
|
Then total is 5, counts is {"all": 5, "online": 5, "draft": 0} and no item has is_online false
|
||||||
|
|
||||||
|
Scenario: A verified caller sees offline articles in the page, the total and the counts
|
||||||
|
Given 5 online and 3 offline articles and a valid jwt cookie of a verified user
|
||||||
|
When the client sends GET /v1/article/?size=5
|
||||||
|
Then total is 8, counts is {"all": 8, "online": 5, "draft": 3} and 3 items have is_online false
|
||||||
|
|
||||||
|
Scenario: An unverified or invalid session is treated as public
|
||||||
|
Given 5 online and 3 offline articles
|
||||||
|
And the jwt cookie is malformed, or belongs to an unverified user
|
||||||
|
When the client sends GET /v1/article/?size=5
|
||||||
|
Then total is 5 and no offline article is returned
|
||||||
|
|
||||||
|
Scenario: A page beyond the last is empty with the real total
|
||||||
|
Given 12 online articles
|
||||||
|
When a client sends GET /v1/article/?page=99&size=5
|
||||||
|
Then the status is 200, items is [], total is 12, page is 99, size is 5 and counts.all is 12
|
||||||
|
|
||||||
|
Scenario: No articles at all
|
||||||
|
Given the repository is empty
|
||||||
|
When a client sends GET /v1/article/
|
||||||
|
Then the status is 200, items is [], total is 0 and counts is {"all": 0, "online": 0, "draft": 0}
|
||||||
|
|
||||||
|
Scenario Outline: Status filter
|
||||||
|
Given 4 online and 2 offline articles and a valid jwt cookie of a verified user
|
||||||
|
When the client sends GET /v1/article/?status=<status>
|
||||||
|
Then total is <total>, counts is {"all": 6, "online": 4, "draft": 2} and every item matches the status
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| status | total |
|
||||||
|
| online | 4 |
|
||||||
|
| draft | 2 |
|
||||||
|
|
||||||
|
Scenario: A public caller asking for drafts gets nothing
|
||||||
|
Given 4 online and 2 offline articles
|
||||||
|
When a public client sends GET /v1/article/?status=draft
|
||||||
|
Then items is [], total is 0 and counts is {"all": 4, "online": 4, "draft": 0}
|
||||||
|
|
||||||
|
Scenario: Search narrows the page and the total but not the counts
|
||||||
|
Given online articles "Choosing lime plaster for old stone walls" and "How we price a bathroom renovation"
|
||||||
|
When a client sends GET /v1/article/?q=PLÂSTER
|
||||||
|
Then total is 1, the only item is the lime plaster article and counts.all is 2
|
||||||
|
|
||||||
|
Scenario: Search and status combine with paging
|
||||||
|
Given a verified session and 7 draft articles whose title contains "tile" and 3 online ones
|
||||||
|
When the client sends GET /v1/article/?q=tile&status=draft&size=5&page=2
|
||||||
|
Then total is 7, the page holds 2 items and counts.draft is 7
|
||||||
|
|
||||||
|
Scenario: Search that matches nothing
|
||||||
|
When a client sends GET /v1/article/?q=zzzz
|
||||||
|
Then items is [], total is 0 and counts is unchanged
|
||||||
|
|
||||||
|
Scenario Outline: Invalid parameters answer 400 like Activity
|
||||||
|
When a client sends GET /v1/article/?<query>
|
||||||
|
Then the status is 400
|
||||||
|
And the body is "The request cannot be processed due to a mismatch in the format of the body."
|
||||||
|
And the repository was not called
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| query |
|
||||||
|
| page=0 |
|
||||||
|
| page=-1 |
|
||||||
|
| page=abc |
|
||||||
|
| page= |
|
||||||
|
| page=1.5 |
|
||||||
|
| size=0 |
|
||||||
|
| size=10 |
|
||||||
|
| size=200 |
|
||||||
|
| size=abc |
|
||||||
|
| status=archived |
|
||||||
|
| status= |
|
||||||
|
| q=<201 characters>|
|
||||||
|
| page=0&size=5 |
|
||||||
|
| page=1&size=1000 |
|
||||||
|
| sort=title |
|
||||||
|
| sort=title:up |
|
||||||
|
| sort=body:asc |
|
||||||
|
| sort= |
|
||||||
|
| sort=updated_at |
|
||||||
|
| sort=title:asc;DROP TABLE |
|
||||||
|
| sort=TITLE:ASC |
|
||||||
|
|
||||||
|
Scenario: Invalid format is reported first
|
||||||
|
When a client sends GET /v1/article/?page=0&format=pdf
|
||||||
|
Then the status is 400 and the body is "The format must be one of: markdown, html, json."
|
||||||
|
|
||||||
|
Scenario: format and paging combine
|
||||||
|
Given 3 online articles
|
||||||
|
When a client sends GET /v1/article/?size=5&format=html
|
||||||
|
Then every item carries body_format "html" and total is 3
|
||||||
|
|
||||||
|
Scenario: Repository failure answers 500
|
||||||
|
Given the repository fails on its next call
|
||||||
|
When a client sends GET /v1/article/
|
||||||
|
Then the status is 500 and the body is "Failed to retrieve articles"
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
# QA: Paginated article listing (API)
|
||||||
|
|
||||||
|
## HTTP-level (Go, `test/`, `task test`)
|
||||||
|
|
||||||
|
Build `article.NewHandler(...)` over the real `ListArticlesUseCase` and a fake `article.Repository` (extend `mockArticleRepo` in `test/article_test.go`, keeping type names unique across files). The fake implements the interface contract: paging (Page/Size 0 = unpaged), q/status filtering, ordering updated_at DESC then id DESC, total, and the visibility counts. Mount on a fresh `chi.NewRouter()` mirroring `NewArticleRouter` in `api/router.go` (GET / under `jwtauth.Verifier` only, test `jwtauth.New("HS256", ...)`). Call `validator.InitValidator()`. Use a user fake for the verified, unverified and missing cases, as in `test/public_article_listing_test.go`. No live server, no SQLite file.
|
||||||
|
|
||||||
|
Helper: decode the body into {items []map, total, page, size int, counts {all, online, draft}} and also assert the raw JSON contains `"items":[` (never null).
|
||||||
|
|
||||||
|
1. Bare request: 30 online articles, GET /v1/article/ -> object (not array), page 1, size 25, total 30, 25 items, counts 30/30/0.
|
||||||
|
2. Defaults table (page=2, page=3, size=5, size=50) on 60 articles.
|
||||||
|
3. Order: ids 3,2,1 for the equal-timestamp case with no sort parameter (default updated_at:desc). Sort table: the 8 whitelisted values on the mixed-case fixture (apple/Banana/Cherry), asserting the item ids. The fake repo implements the same contract: key, direction, then id desc.
|
||||||
|
3a. Equal titles with sort=title:asc -> ids 3,2,1.
|
||||||
|
3b. Sort before paging: 12 articles, ?sort=title:desc&size=5, three pages, no overlap.
|
||||||
|
3c. Sort + q + status combination: ordered titles, total 3, counts unchanged.
|
||||||
|
3d. Use-case test: ListArticlesUseCase passes the typed sort through to Filters and defaults to updated_at desc when absent. Only whitelisted values reaching Order in the repository is a code-review item; the handler test covers the 400 side.
|
||||||
|
4. Partition: 12 articles, pages 1-3 of size 5 -> 5,5,2 and 12 distinct ids.
|
||||||
|
5. Public: 5 online + 3 offline -> total 5, counts 5/5/0, no offline item.
|
||||||
|
6. Verified: same data -> total 8, counts 8/5/3, three offline items.
|
||||||
|
7. Malformed cookie and unverified user -> same as public.
|
||||||
|
8. Out of range: ?page=99&size=5 -> 200, raw `"items":[]`, total 12, counts.all 12.
|
||||||
|
9. Empty repository -> items [], total 0, counts 0/0/0.
|
||||||
|
10. Status table (verified): online -> total 4, draft -> total 2, counts always 6/4/2.
|
||||||
|
11. Public status=draft -> items [], total 0, counts 4/4/0.
|
||||||
|
12. q=PLÂSTER (accent and case insensitive) -> total 1, counts.all 2. q=zzzz -> empty, counts unchanged.
|
||||||
|
13. q+status+page combination: total 7, 2 items on page 2, counts.draft 7.
|
||||||
|
14. Invalid table (all rows incl. `page=`, `page=1.5`, `status=archived`, `status=`, 201-char q, and the 7 sort rows: `sort=title`, `sort=title:up`, `sort=body:asc`, `sort=`, `sort=updated_at`, `sort=title:asc;DROP TABLE`, `sort=TITLE:ASC`): each -> 400 with the exact BodyErrorMessage text, and the fake's FindByFilters/count counters stay 0.
|
||||||
|
15. ?page=0&format=pdf -> 400 with the format message.
|
||||||
|
16. ?size=5&format=html -> every item body_format "html".
|
||||||
|
17. Fake repo failure (existing `failNext("FindByFilters")`) -> 500 "Failed to retrieve articles".
|
||||||
|
18. Use-case tests: the paged list method returns items, total and counts, propagates a repo error (errors.Is on a sentinel), and the unpaged `Filters{}` call used by `purgePlan.go` and `ListMedia.go` still returns every article (existing tests keep passing).
|
||||||
|
19. Existing tests that decode `GET /v1/article/` as an array (`test/public_article_listing_test.go`, `test/article_test.go`, `test/use_case_baseline_test.go`, features/articles_list.qa.md item 1) are amended to the envelope. List them in the diff.
|
||||||
|
|
||||||
|
## Docs (verified by reading the diff)
|
||||||
|
|
||||||
|
- `docs/api/articles.md`: new "Pagination, search, sort and counts" section (parameters including `sort` values, default and id tie-break, envelope, ordering, errors) and a "Breaking change" note, like the existing format note: GET /v1/article/ no longer returns a bare array; read `items`.
|
||||||
|
- `web/src/data/apiCatalogue.ts` `art-list`: add `page`, `size`, `q`, `status`, `sort` query entries, the 400 error, and a paged JSON example; the Integration specs that assert this catalogue are amended.
|
||||||
|
- `docs/design/screens/integration.md` is read-only for agents: flag that its text "GET /v1/article/" example needs the user's update.
|
||||||
|
- A release note under `docs/releases/` is the maintainer's call: flag it.
|
||||||
|
|
||||||
|
## Manual verification
|
||||||
|
|
||||||
|
- Real SQLite file via `task dev`: seed 60 articles, check ?page=2&size=25, ordering, q accent-insensitivity, total and counts. MySQL and PostgreSQL parity of the COUNT / LIMIT-OFFSET / LIKE queries is manual (no live DB in tests).
|
||||||
|
- Sort by `title` on a live SQLite file, and on MySQL/PostgreSQL if available: title collation differs (binary, case-insensitive, locale), so mixed-case and accented ordering may differ between databases. Accepted; note any difference.
|
||||||
|
- An anonymous curl against a running server returns the envelope.
|
||||||
@@ -0,0 +1,187 @@
|
|||||||
|
Feature: Articles list pagination
|
||||||
|
|
||||||
|
As a verified RenewCMS user with many articles
|
||||||
|
I want the Articles list split into pages with a page-size menu, server-side search and tabs, and shareable URLs
|
||||||
|
So that I can browse a large list quickly and come back to the same page
|
||||||
|
|
||||||
|
Background:
|
||||||
|
Given /article is the verified Articles route (features/articles_list.feature), per docs/design/routes.md, docs/design/screens/articles.md group "Articles: pagination" and the Paginator in docs/design/components.md
|
||||||
|
And the route stays /article (the design's /articles is not adopted)
|
||||||
|
And the page requests GET /v1/article/?format=html&page=P&size=S&q=Q&status=T and reads {items, total, page, size, counts} (features/articles_pagination_api.feature); the tab counts "All", "Online", "Drafts" come from counts and do not change while searching
|
||||||
|
And page, size, q, status (tab) and sort live in the URL: ?page=&size=&q=&status=&sort=; the defaults (page 1, size 25, no q, tab All, sort updated_at:desc) are omitted from the URL and from the request only where the API default applies
|
||||||
|
And the sortable columns are Title (title), Status (status), Created (created_at) and Updated (updated_at); a header activation sends sort=<field>:<direction>, the active column shows an arrow icon for its direction, and sorting is done by the server over the whole list, never inside the loaded page
|
||||||
|
And an invalid sort in the URL falls back to updated_at:desc and is replaced in the URL
|
||||||
|
And the table caption reads "Articles, sorted by last updated, newest first" for the default sort and "Articles, sorted by {column}, {ascending|descending}" otherwise, with a French entry in messages.ts
|
||||||
|
And the mobile card list has no sort control; the sort parameter is still honoured from the URL there
|
||||||
|
And an invalid or missing size falls back to 25 and an invalid page (not an integer >= 1) falls back to 1, both replaced in the URL
|
||||||
|
And a change to search, tab, sort or size resets page to 1 (and drops it from the URL); search keeps its 120 ms debounce
|
||||||
|
And the URL changes when a response succeeds, not when the request is sent
|
||||||
|
And the summary reads "Showing {from}–{to} of {total}" with locale-formatted numbers, from total (the filtered count)
|
||||||
|
And the Paginator has First, Previous, page numbers with ellipses marking skipped ranges, Next, Last, and the page-size select "5 per page", "25 per page", "50 per page", "100 per page"
|
||||||
|
And the current page uses --rc-sand fill, --rc-on-sand text and a --ui-primary border and has aria-current="page"; disabled controls are at 40 % opacity; buttons are 32 px (44 px on mobile)
|
||||||
|
And on mobile the paginator is Previous, "Page N of M" and Next
|
||||||
|
And the paginator is hidden when total fits on one page; the summary and the page-size select stay
|
||||||
|
And keyboard: Tab reaches the page-size select, first, previous, each page, next, last; Enter or Space activates; ArrowDown opens the page-size list, Enter selects, Esc closes; every control shows a 2 px --ui-primary focus outline with a 2 px offset
|
||||||
|
And this slice amends features/articles_list.feature: search, tabs and sort are no longer computed client-side over the full list; the list, the counts and the empty states come from the server response
|
||||||
|
And HomeView, ArticleView and useArticles.listArticles migrate to the envelope: they read items (and counts or total where they count) and send explicit paging; no caller reads a bare array any more
|
||||||
|
And the fixture below is total 312, size 25 (13 pages) unless stated; the frames draw at most 10 rows
|
||||||
|
|
||||||
|
Scenario: 1 First page
|
||||||
|
Given GET /v1/article/?format=html&page=1&size=25 resolves 200 with 25 items and total 312
|
||||||
|
When the user navigates to /article
|
||||||
|
Then the summary reads "Showing 1–25 of 312"
|
||||||
|
And First and Previous are disabled, page 1 is current, Next and Last are enabled
|
||||||
|
And the URL has no page or size
|
||||||
|
|
||||||
|
Scenario: 2 Middle page
|
||||||
|
Given GET ...&page=7&size=25 resolves 200 with 25 items and total 312
|
||||||
|
When the user navigates to /article?page=7
|
||||||
|
Then the summary reads "Showing 151–175 of 312"
|
||||||
|
And page 7 is current with --rc-sand / --rc-on-sand and aria-current="page"
|
||||||
|
And ellipses mark the skipped ranges and every control is enabled
|
||||||
|
|
||||||
|
Scenario: 3 Last page
|
||||||
|
Given GET ...&page=13&size=25 resolves 200 with 12 items and total 312
|
||||||
|
When the user navigates to /article?page=13
|
||||||
|
Then the summary reads "Showing 301–312 of 312"
|
||||||
|
And Next and Last are disabled
|
||||||
|
|
||||||
|
Scenario: 4 Single page
|
||||||
|
Given GET /v1/article/ resolves 200 with 6 items, total 6 and counts {all 6, online 4, draft 2}
|
||||||
|
When the user navigates to /article
|
||||||
|
Then the summary reads "Showing 1–6 of 6" and the page-size select stays
|
||||||
|
And the paginator (First ... Last) is not rendered
|
||||||
|
And the tabs read "All 6" "Online 4" "Drafts 2"
|
||||||
|
|
||||||
|
Scenario: 5 Loading next page
|
||||||
|
Given the first page has loaded and GET ...&page=2 has not resolved
|
||||||
|
When the user activates Next
|
||||||
|
Then skeleton rows keep the table height and the list is aria-busy="true"
|
||||||
|
And every paginator control is disabled and the summary reads "Loading page 2…"
|
||||||
|
When the request resolves 200
|
||||||
|
Then the rows and summary of page 2 appear and the URL becomes /article?page=2
|
||||||
|
|
||||||
|
Scenario Outline: 6 Error loading a page keeps the previous rows
|
||||||
|
Given page 6 is shown
|
||||||
|
When the user activates Next and GET ...&page=7 <failure>
|
||||||
|
Then the page-6 rows stay, the URL stays /article?page=6 and the controls are re-enabled
|
||||||
|
And a notice reads "Couldn't load page 7. Showing page 6." with a "Retry" action
|
||||||
|
When the user activates "Retry"
|
||||||
|
Then GET ...&page=7 is sent again and, on 200, page 7 replaces the rows, the URL becomes ?page=7 and the notice goes
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| failure |
|
||||||
|
| resolves with a 500 response |
|
||||||
|
| never reaches the server |
|
||||||
|
|
||||||
|
Scenario: 7 Page out of range redirects to the last page with a notice
|
||||||
|
Given GET ...&page=99 resolves 200 with items [] and total 312
|
||||||
|
When the user navigates to /article?page=99
|
||||||
|
Then the URL is replaced (no history entry) by /article?page=13 and GET ...&page=13 is sent
|
||||||
|
And the notice reads "That page doesn't exist. Showing the last page."
|
||||||
|
And the last-page state (3) is shown
|
||||||
|
|
||||||
|
Scenario: 7b Out of range with total 0 shows the empty state, no redirect
|
||||||
|
Given GET ...&page=5 resolves 200 with items [] and total 0
|
||||||
|
When the user navigates to /article?page=5
|
||||||
|
Then the "No articles yet" empty state shows and the URL is /article
|
||||||
|
|
||||||
|
Scenario: 8 Search resets to page 1
|
||||||
|
Given the user is on /article?page=7
|
||||||
|
When the user types "plaster" in the search field and the debounce elapses
|
||||||
|
Then GET ...&q=plaster&page=1 is sent
|
||||||
|
And on success the URL is /article?q=plaster (page omitted)
|
||||||
|
And the tab counts are unchanged
|
||||||
|
And the same reset happens for a tab change, a sort change and a page-size change
|
||||||
|
|
||||||
|
Scenario: 9 Empty after search
|
||||||
|
Given GET ...&q=tiles resolves 200 with items [], total 0 and counts {all 6, online 4, draft 2}
|
||||||
|
When the user searches "tiles"
|
||||||
|
Then the paginator and the summary are hidden
|
||||||
|
And the no-results state shows "No articles match "tiles"", "Check the spelling, or search for a shorter part of the title." and "Clear search"
|
||||||
|
And the tabs still read "All 6" "Online 4" "Drafts 2"
|
||||||
|
|
||||||
|
Scenario Outline: 10 Page size menu
|
||||||
|
Given the user is on /article?page=3
|
||||||
|
When the user opens the page-size select (it opens upward) and chooses "<label>"
|
||||||
|
Then GET ...&page=1&size=<size> is sent and, on success, the URL is <url>
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| label | size | url |
|
||||||
|
| 5 per page | 5 | /article?size=5 |
|
||||||
|
| 25 per page | 25 | /article |
|
||||||
|
| 50 per page | 50 | /article?size=50 |
|
||||||
|
| 100 per page | 100 | /article?size=100 |
|
||||||
|
|
||||||
|
Scenario: 10b Invalid URL values fall back
|
||||||
|
When the user navigates to /article?size=10&page=abc
|
||||||
|
Then GET ... is sent with page=1 and size=25 and the URL is replaced by /article
|
||||||
|
|
||||||
|
Scenario: 11 Focus-visible
|
||||||
|
When the user tabs to Next
|
||||||
|
Then Next shows a 2 px --ui-primary outline with a 2 px offset
|
||||||
|
And the same ring shows on every paginator control and on the page-size select
|
||||||
|
|
||||||
|
Scenario: Keyboard, the page-size list
|
||||||
|
When the user focuses the page-size select and presses ArrowDown
|
||||||
|
Then the list opens; Enter selects the highlighted size; Esc closes it and returns focus to the select
|
||||||
|
|
||||||
|
Scenario: Tabs filter on the server
|
||||||
|
Given the Default list has loaded and the user is on /article?page=3
|
||||||
|
When the user selects the "Drafts" tab
|
||||||
|
Then GET ...&status=draft&page=1 is sent and, on success, the URL is /article?status=draft
|
||||||
|
And the tab counts are unchanged
|
||||||
|
|
||||||
|
Scenario Outline: Sort header, server-side, resets to page 1
|
||||||
|
Given the user is on /article?page=7
|
||||||
|
When the user activates the "<column>" header (first click)
|
||||||
|
Then GET ...&sort=<sort>&page=1 is sent
|
||||||
|
And on success the URL is /article?sort=<sort> (page omitted)
|
||||||
|
And the header shows the arrow icon for its direction and the tab counts are unchanged
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| column | sort |
|
||||||
|
| Title | title:asc |
|
||||||
|
| Status | status:asc |
|
||||||
|
| Created | created_at:asc |
|
||||||
|
| Updated | updated_at:asc |
|
||||||
|
|
||||||
|
Scenario: Activating the sorted header again toggles the direction
|
||||||
|
Given the list is sorted by Title ascending
|
||||||
|
When the user activates the "Title" header
|
||||||
|
Then GET ...&sort=title:desc&page=1 is sent and, on success, the URL is /article?sort=title:desc
|
||||||
|
|
||||||
|
Scenario: Returning to the default sort drops sort from the URL
|
||||||
|
Given the URL is /article?sort=title:asc
|
||||||
|
When the user activates the "Updated" header until it is updated_at:desc
|
||||||
|
Then the request sends sort=updated_at:desc and, on success, the URL has no sort
|
||||||
|
|
||||||
|
Scenario: Sort is kept across paging, page size, search and tabs
|
||||||
|
Given the URL is /article?sort=title:asc
|
||||||
|
When the user activates Next, or changes the size, or searches "plaster"
|
||||||
|
Then every request carries sort=title:asc and the URL keeps sort=title:asc (search, tab and size also reset the page)
|
||||||
|
|
||||||
|
Scenario: A sorted URL loads sorted
|
||||||
|
When the user navigates to /article?sort=created_at:desc&page=2
|
||||||
|
Then GET ... carries sort=created_at:desc&page=2 and the Created header shows the arrow-down icon
|
||||||
|
|
||||||
|
Scenario: Invalid sort in the URL falls back
|
||||||
|
When the user navigates to /article?sort=body:asc
|
||||||
|
Then GET ... carries no sort (the default applies), the Updated header shows the arrow-down icon and the URL is replaced by /article
|
||||||
|
|
||||||
|
Scenario: The caption follows the sort
|
||||||
|
Given the list is sorted by Title ascending
|
||||||
|
Then the table's visually hidden caption reads "Articles, sorted by title, ascending"
|
||||||
|
|
||||||
|
Scenario: Mobile, Previous, "Page N of M", Next
|
||||||
|
Given the viewport is below md and page 2 of 13 is shown
|
||||||
|
Then the paginator reads Previous, "Page 2 of 13", Next with 44 px controls and no page numbers
|
||||||
|
|
||||||
|
Scenario: Deleting the last row of the last page
|
||||||
|
Given the user is on the last page with a single row and deletes it (204)
|
||||||
|
Then the list reloads the previous page and the URL is replaced by it
|
||||||
|
And the tab counts are recomputed from the new response
|
||||||
|
|
||||||
|
Scenario: Home and the article view read the envelope
|
||||||
|
When HomeView or ArticleView load their articles
|
||||||
|
Then they call GET /v1/article/ with explicit paging and read items, never a bare array
|
||||||
@@ -0,0 +1,42 @@
|
|||||||
|
# QA: Articles list pagination (SPA)
|
||||||
|
|
||||||
|
## Automated (Vitest + Vue Test Utils, `task test:web`)
|
||||||
|
|
||||||
|
Mock `useApi` for `GET /v1/article/?format=html&...` (the route key includes the query) per case. Mount ArticlesPage inside DashboardShell with a verified session and a test router at /article, as in features/articles_list.qa.md. The fixture is 312 articles at 25 per page, built by a helper, with counts {all, online, draft}. No system date freezing.
|
||||||
|
|
||||||
|
1. First page: no page/size in the URL, "Showing 1–25 of 312", First/Previous disabled, page 1 aria-current.
|
||||||
|
2. Middle page: ?page=7 -> "Showing 151–175 of 312", aria-current on 7, ellipsis present.
|
||||||
|
3. Last page: ?page=13 -> "Showing 301–312 of 312", Next/Last disabled.
|
||||||
|
4. Single page: total 6 -> no paginator nav, summary "Showing 1–6 of 6", select present, tabs "All 6" "Online 4" "Drafts 2".
|
||||||
|
5. Loading next page: unresolved page-2 promise -> skeleton rows, aria-busy, controls disabled, "Loading page 2…"; resolve -> rows, URL ?page=2 (URL unchanged before the response).
|
||||||
|
6. Error (500 and network rejection): rows and URL (?page=6) kept, notice "Couldn't load page 7. Showing page 6.", Retry resends page 7, success clears the notice and sets ?page=7.
|
||||||
|
7. Out of range: ?page=99 returns {items:[], total:312} -> router.replace to ?page=13 (assert no extra history entry), second request page=13, notice text. 7b: total 0 -> empty state, no redirect.
|
||||||
|
8. Search resets: from ?page=7 type "plaster" (fake timers past 120 ms) -> request q=plaster&page=1, URL /article?q=plaster after the response, tab counts unchanged. Same assertion for tab, sort (request sort=title:asc&page=1) and size.
|
||||||
|
8a. Sort headers: for Title, Status, Created, Updated, a first click sends sort=<field>:asc&page=1, the URL becomes /article?sort=<field>:asc only after the response, the arrow icon shows and counts are unchanged.
|
||||||
|
8b. A second click toggles to desc; returning to updated_at:desc drops sort from the URL.
|
||||||
|
8c. Sort kept across Next, size change and search.
|
||||||
|
8d. A sorted URL on load (?sort=created_at:desc&page=2) sends it and shows the Created arrow-down; an invalid ?sort=body:asc sends no sort and the URL is replaced by /article.
|
||||||
|
8e. No client-side re-sorting: with the mock returning rows in a fixed order, the table shows exactly that order whatever the sorting state.
|
||||||
|
8f. Caption: default "Articles, sorted by last updated, newest first"; sorted by Title ascending "Articles, sorted by title, ascending"; French strings present.
|
||||||
|
8g. Mobile card list renders no sort control.
|
||||||
|
9. Empty after search: paginator and summary absent, copy and "Clear search", tab counts unchanged.
|
||||||
|
10. Page-size menu: 5/25/50/100 -> request and URL; ArrowDown opens, Enter selects, Esc closes and restores focus. 10b: ?size=10&page=abc -> request page=1&size=25, URL replaced.
|
||||||
|
11. Focus-visible: the focus-ring tokens on every control (the pixel outline is a visual check).
|
||||||
|
12. Tabs on the server: Drafts -> status=draft&page=1, counts unchanged.
|
||||||
|
13. Mobile: below md, Previous / "Page 2 of 13" / Next, no numbers.
|
||||||
|
14. Delete last row of last page: reloads the previous page, counts refreshed.
|
||||||
|
15. HomeView, ArticleView and useArticles: with the envelope mocked, they render from `items`; no code path reads a bare array (a mocked bare array makes the test fail).
|
||||||
|
16. Existing specs amended: features/articles_list.qa.md items 1-18 (search and tab counts server-driven, `GET /v1/article/` mocked as the envelope), `web/src/i18n/spa.spec.ts` (mock around line 417), the ArticleTable specs that rely on client-side TanStack sorting, and the Home, ArticleView and Integration specs. List them in the diff.
|
||||||
|
|
||||||
|
## Visual (`task visual:check -- articles`)
|
||||||
|
|
||||||
|
Add a setup per state in `web/visual/states.ts`, reusing the board's own sample data from group "Articles: pagination" in `docs/design/source/RenewCMS Screens Back-office.dc.html` (total 312, size 25, titles from the frame script), at 1440x900 and 390x844, light and dark; every capture within 10 %. States: First page, Middle page, Last page, Single page, Loading next page, Error loading a page, Page out of range, Search resets to page 1, Empty after search, Page size menu, Focus-visible. A state whose frame shows relative dates ("2 hours ago") is `skip: 'clock-sensitive'`; confirm per frame when coding. Take layout (summary vs paginator vs select, select opening upward) from the frame markup, not from components.md prose. The Articles group's existing states are re-run, since the list now comes from the envelope.
|
||||||
|
|
||||||
|
## Manual
|
||||||
|
|
||||||
|
- Keyboard order and focus return (Tab path, Enter/Space, ArrowDown/Enter/Esc), hover and motion (the skeleton pulse stops under reduced motion).
|
||||||
|
- Keyboard activation (Enter/Space) of the sort headers and the screen-reader announcement of the sort direction (aria-sort).
|
||||||
|
- The sorted-header arrow is part of the existing Articles board states; if a frame lacks it, raise it with the user rather than inventing a state.
|
||||||
|
- Real round trip with `task dev`: page, size, q, status, total and counts from a live SQLite file; a reload keeps the URL state; browser Back after a size change.
|
||||||
|
- Out-of-range redirect against a real shrinking list (delete rows in another tab).
|
||||||
|
- Home and Article views against the real API after the envelope change.
|
||||||
@@ -0,0 +1,109 @@
|
|||||||
|
Feature: Browser tab title names the current page
|
||||||
|
|
||||||
|
Background:
|
||||||
|
Given the SPA is mounted with its router
|
||||||
|
And the tab title format is "<page> · RenewCMS" for a page that has a name
|
||||||
|
And the tab title is just "RenewCMS" when the current page has no name at all
|
||||||
|
And page names are translated to the interface language
|
||||||
|
And the title is set in one place for the whole SPA, not by each screen
|
||||||
|
And no /v1 call is made only to set the title
|
||||||
|
|
||||||
|
Scenario Outline: Back-office pages show their name
|
||||||
|
Given a signed-in verified user
|
||||||
|
When the user navigates to <path>
|
||||||
|
Then the tab title is "<title>"
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| path | title |
|
||||||
|
| /home | Home · RenewCMS |
|
||||||
|
| /article | Articles · RenewCMS |
|
||||||
|
| /article/new | Articles · RenewCMS |
|
||||||
|
| /media | Media · RenewCMS |
|
||||||
|
| /users | Users · RenewCMS |
|
||||||
|
| /activity | Activity · RenewCMS |
|
||||||
|
| /profile | Profile · RenewCMS |
|
||||||
|
| /integration | Integration · RenewCMS |
|
||||||
|
| /integration/api-keys | Integration · RenewCMS |
|
||||||
|
| /settings | Settings · RenewCMS |
|
||||||
|
| /settings/media/variants | Settings · RenewCMS |
|
||||||
|
| /settings/media/cache | Settings · RenewCMS |
|
||||||
|
|
||||||
|
Scenario Outline: Auth pages show the card heading they display
|
||||||
|
Given a signed-out visitor
|
||||||
|
When the visitor navigates to <path>
|
||||||
|
Then the tab title is "<title>"
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| path | title |
|
||||||
|
| /login | Log in · RenewCMS |
|
||||||
|
| /register | Create the owner account · RenewCMS |
|
||||||
|
| /register/pending | Check your email · RenewCMS |
|
||||||
|
| /register/reset/request | Reset your password · RenewCMS |
|
||||||
|
| /register/reset/validate?c=CODE&email=EMAIL | Choose a new password · RenewCMS |
|
||||||
|
| /invite/accept?c=CODE | Accept your invite · RenewCMS |
|
||||||
|
| /register/validate?c=CODE without a session | Log in to finish verifying · RenewCMS |
|
||||||
|
|
||||||
|
Scenario: An auth card with no heading uses the product name
|
||||||
|
Given the verify screen is verifying a code and its card shows no heading
|
||||||
|
Then the tab title is "RenewCMS"
|
||||||
|
|
||||||
|
Scenario: Auth card heading changes inside one route
|
||||||
|
Given an auth screen whose card heading changes between states
|
||||||
|
When the card heading changes
|
||||||
|
Then the tab title follows the new card heading
|
||||||
|
|
||||||
|
Scenario: Title updates when the page changes
|
||||||
|
Given a signed-in verified user on /home with the tab title "Home · RenewCMS"
|
||||||
|
When the user navigates to /media
|
||||||
|
Then the tab title is "Media · RenewCMS"
|
||||||
|
When the user navigates back to /home
|
||||||
|
Then the tab title is "Home · RenewCMS"
|
||||||
|
|
||||||
|
Scenario: Leaving the login screen does not leave "Log in" stuck
|
||||||
|
Given a signed-out visitor on /login with the tab title "Log in · RenewCMS"
|
||||||
|
When the visitor logs in successfully and is redirected to /home
|
||||||
|
Then the tab title is "Home · RenewCMS"
|
||||||
|
|
||||||
|
Scenario: Logging out does not keep the back-office title
|
||||||
|
Given a signed-in verified user on /settings
|
||||||
|
When the user logs out and is sent to /login
|
||||||
|
Then the tab title is "Log in · RenewCMS"
|
||||||
|
|
||||||
|
Scenario: Editor tab shows the article's own title once loaded
|
||||||
|
Given a signed-in verified user
|
||||||
|
When the user opens /article/42/edit and the article is still loading
|
||||||
|
Then the tab title is "Editor · RenewCMS"
|
||||||
|
When the article "Hello world" has loaded
|
||||||
|
Then the tab title is "Hello world · RenewCMS"
|
||||||
|
|
||||||
|
Scenario: Editor tab follows the saved article title
|
||||||
|
Given the user is editing the article "Hello world" at /article/42/edit
|
||||||
|
When the article title is saved as "Hello again"
|
||||||
|
Then the tab title is "Hello again · RenewCMS"
|
||||||
|
|
||||||
|
Scenario Outline: Editor tab falls back to "Editor"
|
||||||
|
Given a signed-in verified user
|
||||||
|
When the user opens /article/42/edit and <situation>
|
||||||
|
Then the tab title is "Editor · RenewCMS"
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| situation |
|
||||||
|
| the article fails to load |
|
||||||
|
| the article has an empty title |
|
||||||
|
|
||||||
|
Scenario: Leaving the editor drops the article title
|
||||||
|
Given the user is on /article/42/edit with the tab title "Hello world · RenewCMS"
|
||||||
|
When the user navigates to /article
|
||||||
|
Then the tab title is "Articles · RenewCMS"
|
||||||
|
|
||||||
|
Scenario: Not-found page
|
||||||
|
Given any user
|
||||||
|
When the user navigates to an unknown path
|
||||||
|
Then the tab title is "404 · RenewCMS"
|
||||||
|
|
||||||
|
Scenario: Title follows the interface language
|
||||||
|
Given the interface language is Français
|
||||||
|
When the user navigates to /media
|
||||||
|
Then the tab title is the French "Media" name followed by " · RenewCMS"
|
||||||
|
When the user switches the interface language to English
|
||||||
|
Then the tab title is "Media · RenewCMS" without a navigation
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
# QA: document title (SPA, Vitest only)
|
||||||
|
|
||||||
|
## Automated (Vitest + Vue Test Utils, real route table, memory history, mocked /v1)
|
||||||
|
Each test resets `document.title` to "" in `beforeEach`.
|
||||||
|
|
||||||
|
1. Back-office rows: with `/v1` user mocked as signed in and verified, push each path from the first Examples table, await `router.isReady()`, assert `document.title`.
|
||||||
|
2. Auth rows: with the session mocked as signed out (401), push each path of the auth Examples table and assert the title equals the card heading plus " · RenewCMS". For the verify noSession row, mock a verify attempt with no session.
|
||||||
|
3. Verify with a code and no heading: assert `document.title === 'RenewCMS'`.
|
||||||
|
4. Auth heading change: drive an auth screen through two states with different headings (e.g. reset request default to the incomplete/expired variant) and assert the title follows.
|
||||||
|
5. Navigation sequence: /home, /media, /home, asserting after each push.
|
||||||
|
6. Login redirect: from /login simulate a successful login so the guard redirects to /home; assert "Home · RenewCMS".
|
||||||
|
7. Logout: from /settings trigger logout; assert "Log in · RenewCMS".
|
||||||
|
8. Editor: mock GET article 42 with a pending promise, assert "Editor · RenewCMS"; resolve with title "Hello world", assert "Hello world · RenewCMS". Save with title "Hello again" and assert the update. Repeat with a failing GET and with an empty title, expecting "Editor · RenewCMS". Navigate to /article and assert "Articles · RenewCMS".
|
||||||
|
9. Not found: push an unknown path, assert "404 · RenewCMS".
|
||||||
|
10. Locale: set `fr`, push /media, assert the French name plus " · RenewCMS"; switch to `en` and assert "Media · RenewCMS" without a navigation.
|
||||||
|
11. Update `web/src/components/__tests__/AuthShell.spec.ts` if its title expectations no longer hold once the title is set in one place.
|
||||||
|
|
||||||
|
## Visual
|
||||||
|
None. The tab title is not drawn on any board (skip: not-visual).
|
||||||
|
|
||||||
|
## Manual
|
||||||
|
- In a real browser, log in from /login and confirm the tab reads "Home · RenewCMS", then use the sidebar and the browser Back and Forward buttons and confirm the tab follows.
|
||||||
|
- Open an article in the editor, edit its title, and confirm the tab and the history entry follow.
|
||||||
@@ -19,9 +19,9 @@ Feature: An authenticated user can edit an article's body
|
|||||||
DELETE /v1/article/{id}, PATCH /v1/article/{id}/publish and
|
DELETE /v1/article/{id}, PATCH /v1/article/{id}/publish and
|
||||||
PATCH /v1/article/{id}/unpublish in api/router.go, so it also requires a valid
|
PATCH /v1/article/{id}/unpublish in api/router.go, so it also requires a valid
|
||||||
jwt cookie
|
jwt cookie
|
||||||
And the request body is JSON {"body": "..."}, validated with
|
And the request body is JSON {"body": "..."}; the Body field carries no validate tag
|
||||||
validate:"required,max=10000" on the Body field, the same tag PostArticle.Body
|
(no max, not required), as PostArticle.Body, per
|
||||||
already carries
|
features/article_body_unlimited.feature
|
||||||
And a successful edit answers 200 with the JSON body of the updated article.Article,
|
And a successful edit answers 200 with the JSON body of the updated article.Article,
|
||||||
the same shape GetArticle, PostArticle, PublishArticle and UnpublishArticle
|
the same shape GetArticle, PostArticle, PublishArticle and UnpublishArticle
|
||||||
already return; the article's title, is_online flag and images are unchanged
|
already return; the article's title, is_online flag and images are unchanged
|
||||||
@@ -30,9 +30,8 @@ Feature: An authenticated user can edit an article's body
|
|||||||
PublishArticle and UnpublishArticle
|
PublishArticle and UnpublishArticle
|
||||||
And a body that is not valid JSON answers 400 with body apperr.BodyErrorMessage,
|
And a body that is not valid JSON answers 400 with body apperr.BodyErrorMessage,
|
||||||
the same as PostArticle
|
the same as PostArticle
|
||||||
And a body that fails its own required/max=10000 validation answers 400 with the
|
And no body value fails validation: an empty or absent body and a body of any length
|
||||||
raw validator error text, the same as PostArticle already does for its own
|
are accepted
|
||||||
fields; no new apperr message is introduced for this
|
|
||||||
And an id absent from the article repository answers 404 with body
|
And an id absent from the article repository answers 404 with body
|
||||||
apperr.ArticleNotFoundErrorMessage, backed by
|
apperr.ArticleNotFoundErrorMessage, backed by
|
||||||
errors.Is(err, article.ErrArticleNotFound), the same as DeleteArticle,
|
errors.Is(err, article.ErrArticleNotFound), the same as DeleteArticle,
|
||||||
@@ -84,11 +83,12 @@ Feature: An authenticated user can edit an article's body
|
|||||||
Then the response status is 400
|
Then the response status is 400
|
||||||
And the response body is the text apperr.BodyErrorMessage
|
And the response body is the text apperr.BodyErrorMessage
|
||||||
|
|
||||||
Scenario Outline: A body value that fails validation answers 400
|
Scenario Outline: A body of any length, including empty, is accepted
|
||||||
Given a valid jwt cookie for a user with id 1
|
Given a valid jwt cookie for a user with id 1
|
||||||
And the article repository contains an article with id 1
|
And the article repository contains an article with id 1
|
||||||
When the client sends PATCH /v1/article/1 with that cookie and body <payload>
|
When the client sends PATCH /v1/article/1 with that cookie and body <payload>
|
||||||
Then the response status is 400
|
Then the response status is 200
|
||||||
|
And the stored body equals the sent body
|
||||||
|
|
||||||
Examples:
|
Examples:
|
||||||
| payload |
|
| payload |
|
||||||
|
|||||||
@@ -41,11 +41,10 @@ Package: `test` (black-box, extending `article_test.go`).
|
|||||||
string `not-json`), repo seeded with article id 1 -> status `400`, body matching
|
string `not-json`), repo seeded with article id 1 -> status `400`, body matching
|
||||||
`apperr.BodyErrorMessage + "\n"`.
|
`apperr.BodyErrorMessage + "\n"`.
|
||||||
13. `PATCH /v1/article/1` with the valid cookie and JSON body `{"body": ""}`, repo
|
13. `PATCH /v1/article/1` with the valid cookie and JSON body `{"body": ""}`, repo
|
||||||
seeded with article id 1 -> status `400`; assert `repo.articles[1].Body` is
|
seeded with article id 1 -> status `200`; assert `repo.articles[1].Body` is `""`.
|
||||||
unchanged (nothing stored).
|
|
||||||
14. `PATCH /v1/article/1` with the valid cookie and JSON body `{"body": "<10001-char
|
14. `PATCH /v1/article/1` with the valid cookie and JSON body `{"body": "<10001-char
|
||||||
string>"}`, repo seeded with article id 1 -> status `400`; assert
|
string>"}`, repo seeded with article id 1 -> status `200`; assert
|
||||||
`repo.articles[1].Body` is unchanged.
|
`repo.articles[1].Body` equals the sent string.
|
||||||
15. `PATCH /v1/article/1` with **no** cookie, repo seeded with article id 1 -> status
|
15. `PATCH /v1/article/1` with **no** cookie, repo seeded with article id 1 -> status
|
||||||
`401`.
|
`401`.
|
||||||
|
|
||||||
|
|||||||
@@ -23,11 +23,11 @@ Feature: Editor screen — load, edit and save an article's body
|
|||||||
the article is a draft; clicking PublishControl itself is out of scope for this slice and
|
the article is a draft; clicking PublishControl itself is out of scope for this slice and
|
||||||
is specified in a follow-on slice (editor_publish_and_delete)
|
is specified in a follow-on slice (editor_publish_and_delete)
|
||||||
And Save is enabled only when useArticleDraft's state is "dirty", the request is not already
|
And Save is enabled only when useArticleDraft's state is "dirty", the request is not already
|
||||||
in flight, the app is not offline, and the body's HTML length is at most 10000 characters;
|
in flight, and the app is not offline, whatever the body's length; it is disabled in every
|
||||||
it is disabled in every other case
|
other case
|
||||||
And Save (a click, or Ctrl/⌘ S) sends PATCH /v1/article/{id} with JSON {"body": "..."},
|
And Save (a click, or Ctrl/⌘ S) sends PATCH /v1/article/{id} with JSON {"body": "..."},
|
||||||
the same contract features/edit_article_body.feature already gives the API: 200 with the
|
the same contract features/edit_article_body.feature already gives the API: 200 with the
|
||||||
updated article.Article, 400 for a body over 10000 characters, 404 for an id absent from
|
updated article.Article (any body length, including empty), 404 for an id absent from
|
||||||
the repository, 401 with no valid session
|
the repository, 401 with no valid session
|
||||||
And a successful save (200) sets useArticleDraft's state to "saved" and records the save
|
And a successful save (200) sets useArticleDraft's state to "saved" and records the save
|
||||||
time; SaveStatus shows "Saved at {HH:MM}" for the first hour and "Saved {n} min ago" after
|
time; SaveStatus shows "Saved at {HH:MM}" for the first hour and "Saved {n} min ago" after
|
||||||
@@ -43,11 +43,11 @@ Feature: Editor screen — load, edit and save an article's body
|
|||||||
(features/api_client_global_error_handling.feature): before the redirect, useArticleDraft
|
(features/api_client_global_error_handling.feature): before the redirect, useArticleDraft
|
||||||
mirrors the current dirty body to sessionStorage keyed by the article's id, so it survives
|
mirrors the current dirty body to sessionStorage keyed by the article's id, so it survives
|
||||||
the redirect to /login?redirect=/article/{id}/edit&reason=expired
|
the redirect to /login?redirect=/article/{id}/edit&reason=expired
|
||||||
And CharacterCounter shows "{len} / 10 000" below the editor, using the body's HTML string
|
And EditorStatusBar shows a neutral "{words} words · {characters} characters" count with
|
||||||
length (formatting and images count); at 9000 characters or more (90%, "Near the limit")
|
en-US thousands separators (e.g. "1,204 words · 7,318 characters", "0 words · 0 characters"
|
||||||
it adds a warning icon and stays enabled; above 10000 ("Too long") it adds an icon and the
|
for an empty body); characters is the body's HTML string length, words are the
|
||||||
text "{over} characters over. Shorten the text or remove an image. Formatting counts too.",
|
whitespace-separated tokens of its text content; the count has no limit, warning or error
|
||||||
and disables both Save and PublishControl until the length is 10000 or fewer again
|
styling, per features/article_body_unlimited.feature
|
||||||
And a Preview switch, when on, replaces the editable ArticleEditor and its toolbar with a
|
And a Preview switch, when on, replaces the editable ArticleEditor and its toolbar with a
|
||||||
read-only rendering of the title and body in the content type scale; switching it off
|
read-only rendering of the title and body in the content type scale; switching it off
|
||||||
restores the editable surface with the same content, unchanged
|
restores the editable surface with the same content, unchanged
|
||||||
@@ -93,7 +93,7 @@ Feature: Editor screen — load, edit and save an article's body
|
|||||||
And SaveStatus reads "Saved at 11:02"
|
And SaveStatus reads "Saved at 11:02"
|
||||||
And the Save button is disabled
|
And the Save button is disabled
|
||||||
And PublishControl reads "<publish_label>"
|
And PublishControl reads "<publish_label>"
|
||||||
And the character counter reads "4 318 / 10 000"
|
And the count reads "{words} words · 4,318 characters"
|
||||||
|
|
||||||
Examples:
|
Examples:
|
||||||
| is_online | badge | publish_label |
|
| is_online | badge | publish_label |
|
||||||
@@ -161,22 +161,12 @@ Feature: Editor screen — load, edit and save an article's body
|
|||||||
Then a toast reads "That article no longer exists."
|
Then a toast reads "That article no longer exists."
|
||||||
And SaveStatus does not read "Save failed"
|
And SaveStatus does not read "Save failed"
|
||||||
|
|
||||||
Scenario: Near the limit — the counter warns at 9000 characters without blocking Save
|
Scenario: A very long body keeps a neutral count and leaves Save and Publish enabled
|
||||||
Given the user is on /article/12/edit with unsaved changes making the body's HTML length
|
Given the user is on /article/12/edit with unsaved changes making the body's HTML length
|
||||||
9240 characters
|
120000 characters
|
||||||
Then the character counter reads "9 240 / 10 000" with a warning icon
|
Then the count reads "19,845 words · 120,000 characters" with no warning styling
|
||||||
And the Save button remains enabled
|
And the Save button is enabled
|
||||||
|
And PublishControl is enabled
|
||||||
Scenario: Too long — over 10000 characters disables Save and Publish until shortened
|
|
||||||
Given the user is on /article/12/edit with unsaved changes making the body's HTML length
|
|
||||||
10214 characters
|
|
||||||
Then the character counter reads "10 214 / 10 000" with the text "214 characters over.
|
|
||||||
Shorten the text or remove an image. Formatting counts too."
|
|
||||||
And the Save button is disabled
|
|
||||||
And PublishControl is disabled
|
|
||||||
When the user shortens the body to 10000 characters or fewer
|
|
||||||
Then the character counter no longer shows the over-limit text
|
|
||||||
And the Save button is enabled again
|
|
||||||
|
|
||||||
Scenario: Preview shows the rendered title and body without the editing surface
|
Scenario: Preview shows the rendered title and body without the editing surface
|
||||||
Given the user is on /article/12/edit, article titled "How we price a bathroom renovation"
|
Given the user is on /article/12/edit, article titled "How we price a bathroom renovation"
|
||||||
|
|||||||
@@ -35,7 +35,7 @@ Fixture article (reused across cases unless a scenario overrides a field): id 12
|
|||||||
2. **Saved state, draft and online** — Examples-driven on `is_online`: mock `GET
|
2. **Saved state, draft and online** — Examples-driven on `is_online`: mock `GET
|
||||||
/v1/article/12` resolving 200 with the fixture at each `is_online` value; assert the
|
/v1/article/12` resolving 200 with the fixture at each `is_online` value; assert the
|
||||||
breadcrumb, ArticleStatusBadge ("Draft"/"Online"), SaveStatus "Saved at 11:02", Save
|
breadcrumb, ArticleStatusBadge ("Draft"/"Online"), SaveStatus "Saved at 11:02", Save
|
||||||
disabled, PublishControl ("Publish"/"Unpublish"), and character counter "4 318 / 10 000".
|
disabled, PublishControl ("Publish"/"Unpublish"), and the neutral count ending "4,318 characters".
|
||||||
3. **Unsaved changes** — from the Saved state, type into the body; assert SaveStatus "Unsaved
|
3. **Unsaved changes** — from the Saved state, type into the body; assert SaveStatus "Unsaved
|
||||||
changes", Save enabled, PublishControl now "Save and publish".
|
changes", Save enabled, PublishControl now "Save and publish".
|
||||||
4. **Saving via click and via Ctrl/⌘ S** — from Unsaved changes, (a) click Save, (b) press
|
4. **Saving via click and via Ctrl/⌘ S** — from Unsaved changes, (a) click Save, (b) press
|
||||||
@@ -53,12 +53,10 @@ Fixture article (reused across cases unless a scenario overrides a field): id 12
|
|||||||
9. **404 on save shows a toast, not the error SaveStatus** — from Unsaved changes, save; resolve
|
9. **404 on save shows a toast, not the error SaveStatus** — from Unsaved changes, save; resolve
|
||||||
`PATCH` 404; assert a toast "That article no longer exists." appears and SaveStatus never
|
`PATCH` 404; assert a toast "That article no longer exists." appears and SaveStatus never
|
||||||
reads "Save failed".
|
reads "Save failed".
|
||||||
10. **Near the limit** — set the body's HTML length to 9240 (via a fixture string of that
|
10. **Very long body** — set the body's HTML length to 120000 (via a fixture string of that
|
||||||
length); assert counter "9 240 / 10 000" with a warning icon and Save still enabled.
|
length); assert the count "19,845 words · 120,000 characters" with no warning styling, Save
|
||||||
11. **Too long** — set the body's HTML length to 10214; assert counter "10 214 / 10 000" with
|
and PublishControl enabled.
|
||||||
"214 characters over. Shorten the text or remove an image. Formatting counts too.", Save
|
11. **No limit states** — assert no "Near the limit" or "Too long" text is ever rendered.
|
||||||
disabled, PublishControl disabled; shorten to 10000; assert both re-enable and the over-limit
|
|
||||||
text disappears.
|
|
||||||
12. **Preview toggle** — from a loaded article with body content, switch Preview on; assert the
|
12. **Preview toggle** — from a loaded article with body content, switch Preview on; assert the
|
||||||
toolbar and editable surface are gone and a read-only rendering of title+body appears;
|
toolbar and editable surface are gone and a read-only rendering of title+body appears;
|
||||||
switch off; assert the editable surface returns with the same content.
|
switch off; assert the editable surface returns with the same content.
|
||||||
@@ -97,12 +95,11 @@ reusing the sample data below and a fixed `now` of "2026-09-26T11:02:00Z" (updat
|
|||||||
|
|
||||||
- [ ] Loading: skeletons for title, content and details, shaped like the real layout.
|
- [ ] Loading: skeletons for title, content and details, shaped like the real layout.
|
||||||
- [ ] Saved: breadcrumb, "Draft" badge, "Saved at 11:02", disabled Save, "Publish", counter
|
- [ ] Saved: breadcrumb, "Draft" badge, "Saved at 11:02", disabled Save, "Publish", counter
|
||||||
"4 318 / 10 000", details panel (Created/Updated/ID/Images/Public API URL).
|
"N words · 4,318 characters", details panel (Created/Updated/ID/Images/Public API URL).
|
||||||
- [ ] Unsaved changes: "Unsaved changes" SaveStatus, enabled Save, "Save and publish".
|
- [ ] Unsaved changes: "Unsaved changes" SaveStatus, enabled Save, "Save and publish".
|
||||||
- [ ] Saving: "Saving…" SaveStatus, disabled Save.
|
- [ ] Saving: "Saving…" SaveStatus, disabled Save.
|
||||||
- [ ] Save failed: "Save failed" with Retry, per the SaveStatus error spec.
|
- [ ] Save failed: "Save failed" with Retry, per the SaveStatus error spec.
|
||||||
- [ ] Near the limit: counter "9 240 / 10 000" with the warning icon/style.
|
- [ ] Very long article: count "19,845 words · 120,000 characters", neutral, Save/Publish enabled.
|
||||||
- [ ] Too long: counter "10 214 / 10 000" with the over-limit text and disabled Save/Publish.
|
|
||||||
- [ ] Preview: read-only rendered title and body in the content scale, toolbar hidden.
|
- [ ] Preview: read-only rendered title and body in the content scale, toolbar hidden.
|
||||||
- [ ] Offline: SaveStatus shows the wifi-off icon and reads "Waiting for connection", disabled
|
- [ ] Offline: SaveStatus shows the wifi-off icon and reads "Waiting for connection", disabled
|
||||||
Save/Publish, OfflineBanner visible.
|
Save/Publish, OfflineBanner visible.
|
||||||
|
|||||||
@@ -4,8 +4,8 @@
|
|||||||
|
|
||||||
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.
|
Mock `XMLHttpRequest` (a fake with `open`, `setRequestHeader`, `send`, `abort`, firing `upload.progress`, `load`, `error`) for `POST /v1/media/`. Mock useApi's `request` for `GET /v1/media/` (list and `?hash=`), reusing the mock from `api_client_global_error_handling.qa.md`. Stub `hashFile` where a hash is needed, and add one test with `crypto.subtle` deleted. Mount EditorPage inside DashboardShell at `/article/12/edit` with the `editor_core.qa.md` fixture article, GET already resolved 200. Assert URLs by parsing the query, not by string equality.
|
||||||
|
|
||||||
1. **Toolbar button, empty library** - `GET /v1/media/?limit=24` resolves `{items: [], next_cursor: null, counts: {all: 0, unused: 0, duplicates: 0}}`; click "Image"; assert the dialog "Add an image", both tabs, the Upload tab selected, the drop zone copy, footer "Cancel" only, no XHR.
|
1. **Toolbar button, empty library** - `GET /v1/media/?page=1&size=25` resolves `{items: [], total: 0, page: 1, size: 25, counts: {all: 0, unused: 0, duplicates: 0}}`; click "Image"; assert the dialog "Add an image", both tabs, the Upload tab selected, the drop zone copy, footer "Cancel" only, no XHR.
|
||||||
2. **Drop opens Upload with the file** - dispatch `drop` with `before.png` (image/png, 3.9 MB); assert the Upload tab, a `?hash=` request, no `?limit=24` list request, then the crop step after an empty lookup, and no XHR.
|
2. **Drop opens Upload with the file** - dispatch `drop` with `before.png` (image/png, 3.9 MB); assert the Upload tab, a `?hash=...&page=1&size=100` request, no `?page=1&size=25` list request, then the crop step after an empty lookup, and no XHR.
|
||||||
3. **Dragging over shows "Drop to upload"**.
|
3. **Dragging over shows "Drop to upload"**.
|
||||||
4. **Rejected, Examples-driven** - `plan.pdf`, `disguised.png`, `north-wall.tif`; assert no `?hash=` request and no XHR, plus the exact title, text, confirm and cancel.
|
4. **Rejected, Examples-driven** - `plan.pdf`, `disguised.png`, `north-wall.tif`; assert no `?hash=` request and no XHR, plus the exact title, text, confirm and cancel.
|
||||||
5. **"Choose another file" returns to idle**, with the tabs back.
|
5. **"Choose another file" returns to idle**, with the tabs back.
|
||||||
|
|||||||
@@ -0,0 +1,226 @@
|
|||||||
|
Feature: Inserting, editing and removing a link in the article body
|
||||||
|
|
||||||
|
As a verified RenewCMS owner writing an article
|
||||||
|
I want to turn text into a link from the toolbar or with Ctrl/Cmd+K, and to edit or remove it later
|
||||||
|
So that readers can follow references, and no link I add can run script
|
||||||
|
|
||||||
|
Background:
|
||||||
|
Given this slice is SPA only; no Go code, route or API contract changes
|
||||||
|
And the screen is /article/:id/edit (EditorPage in DashboardShell), per docs/design/screens/editor.md
|
||||||
|
rows 11 to 27, docs/design/components.md "Editor: link" and the Editor group of the board
|
||||||
|
"RenewCMS Screens Back-office.dc.html"; docs/design/README.md says "11 states" but all 17 rows are in scope
|
||||||
|
And a link change is a body edit only: it moves useArticleDraft to "dirty" ("Unsaved changes", Save enabled,
|
||||||
|
PublishControl "Save and publish" on a draft) and sends no request; the existing PATCH /v1/article/{id}
|
||||||
|
with {"body": "<html>"} saves it, unchanged
|
||||||
|
And the body stays Tiptap HTML, a link being <a href="...">; ArticleEditor keeps its props, events and
|
||||||
|
exposed focus, insertImage, imageSrc and removeImage
|
||||||
|
And the toolbar has a link button (icon i-lucide-link) after the list buttons, before "Clear formatting"
|
||||||
|
and "Image"; 28 px on desktop, 40 px on mobile; text colour --ui-text-toned
|
||||||
|
And Ctrl+K (Cmd+K on macOS) with the editor focused opens the same dialog as the button and prevents the
|
||||||
|
browser's own shortcut
|
||||||
|
And LinkModal is a dialog at desktop width and a bottom sheet at mobile width (viewport); fields "Link text"
|
||||||
|
and "URL", toggle "Open in new tab" (off by default) with the helper text "Links open in the same tab unless
|
||||||
|
you turn on a new tab."; title "Insert link" or "Edit link"; Cancel left, "Insert link" or "Save link" right;
|
||||||
|
in edit mode a text button "Remove link"
|
||||||
|
And a valid URL, after trimming, is http(s)://host..., mailto:address, a path with exactly one leading "/",
|
||||||
|
or #anchor; everything else fails with "Enter a valid URL. Use http(s), mailto, a path or #anchor."
|
||||||
|
(so javascript:, data:, vbscript:, file:, ftp:, tel:, //host, page.html and ../x are all invalid, in any
|
||||||
|
letter case, with leading whitespace, control characters or entity escapes)
|
||||||
|
And "Link text" must not be blank, else "Enter the link text."
|
||||||
|
And validation runs on submit, and on blur for the URL; an invalid submit inserts nothing, keeps the dialog
|
||||||
|
open and focuses the first invalid field
|
||||||
|
And "Open in new tab" writes target="_blank" rel="noopener noreferrer" on the anchor; off writes neither
|
||||||
|
And the link popover and its sheet follow the input type, not the width: a popover for a fine pointer, a bottom
|
||||||
|
sheet for pointer: coarse
|
||||||
|
And the popover is 288 px wide under the link: the URL in mono, then "Edit", "Open", "Remove" (error colour);
|
||||||
|
the sheet shows the link text, the URL and 48 px rows "Edit link", "Open link", "Remove link"
|
||||||
|
And Remove takes no confirmation and is undone by the editor's undo; Open opens a new tab with
|
||||||
|
rel="noopener noreferrer"
|
||||||
|
And selection edge cases follow the editor's default mark behaviour; no custom rules
|
||||||
|
And automatic URL linking is untouched by this slice
|
||||||
|
And target and rel exist only in ?format=html; the json and markdown reads carry only the href (accepted)
|
||||||
|
And every new English string has a French entry in messages.ts
|
||||||
|
|
||||||
|
Scenario Outline: The link button across its states
|
||||||
|
Given the user is on /article/12/edit in the Saved state, <situation>
|
||||||
|
Then the link button shows <expected>
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| situation | expected |
|
||||||
|
| the cursor is in plain text | aria-pressed "false", --ui-text-toned |
|
||||||
|
| the pointer rests on it for 400 ms (Windows or Linux) | the tooltip "Insert link (Ctrl+K)" |
|
||||||
|
| the pointer rests on it for 400 ms (macOS) | the tooltip "Insert link (⌘K)" |
|
||||||
|
| the input is touch | no tooltip |
|
||||||
|
| it takes keyboard focus | a 2 px --ui-primary outline, 1 px offset; Enter or Space opens the dialog |
|
||||||
|
| the cursor is inside a link | aria-pressed "true", --rc-sand fill, --rc-on-sand icon; pressing it opens the edit dialog |
|
||||||
|
| part or all of a link's text is selected | the same active look |
|
||||||
|
| an image is selected | 40% opacity, aria-disabled "true", no tooltip; pressing it and Ctrl/Cmd+K open nothing |
|
||||||
|
| Preview is on, or ArticleEditor has disabled true | Ctrl/Cmd+K opens nothing |
|
||||||
|
|
||||||
|
Scenario Outline: Creating a link
|
||||||
|
Given the user is on /article/12/edit with the body "<p>We also check the timber windows before any tiling starts.</p>"
|
||||||
|
And <start>
|
||||||
|
When the user presses Ctrl+K, or activates the link button
|
||||||
|
Then LinkModal opens titled "Insert link" with "Link text" <text-field>, the toggle off, and "Cancel" and "Insert link"
|
||||||
|
And <focus-target> has focus
|
||||||
|
When the user sets "Link text" to "<text>", "URL" to "/articles/winter-checklist" and activates "Insert link"
|
||||||
|
Then the dialog closes and the body holds <a href="/articles/winter-checklist"><text></a> at that place
|
||||||
|
And focus is back in the editor, SaveStatus reads "Unsaved changes", and no request has been sent
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| start | text-field | focus-target | text |
|
||||||
|
| "timber windows" is selected | prefilled "timber windows" | "URL" | timber windows |
|
||||||
|
| "timber windows" is selected | prefilled, then edited | "URL" | timber sash windows |
|
||||||
|
| nothing is selected | empty, placeholder "What the reader sees" | "Link text" | winter checklist |
|
||||||
|
|
||||||
|
Scenario Outline: Editing and removing an existing link
|
||||||
|
Given the body has the link "timber windows" to "/articles/winter-checklist" opening in a new tab
|
||||||
|
When the user <opens-edit>
|
||||||
|
Then LinkModal opens titled "Edit link" with the text, the URL (focused) and the toggle on prefilled, and "Remove link", "Cancel", "Save link"
|
||||||
|
When the user <action>
|
||||||
|
Then <result>
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| opens-edit | action | result |
|
||||||
|
| presses Edit in the link popover | sets the URL to "https://example.org/windows" and activates "Save link" | the same anchor has that href and still opens in a new tab; SaveStatus "Unsaved changes" |
|
||||||
|
| presses Ctrl+K with the cursor in the link | activates "Save link" with nothing changed | the dialog closes, the body is identical and a Saved draft stays Saved |
|
||||||
|
| presses Ctrl+K with the cursor in the link | activates "Remove link" | the text stays without the link, no confirmation, "Unsaved changes"; undo brings the link back with its target |
|
||||||
|
|
||||||
|
Scenario Outline: Validation in the dialog
|
||||||
|
Given the dialog is open
|
||||||
|
When the user sets "Link text" to "<text>", "URL" to "<url>" and activates "Insert link"
|
||||||
|
Then <outcome>
|
||||||
|
And nothing is inserted, the dialog stays open and the draft's dirty state is unchanged
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| text | url | outcome |
|
||||||
|
| timber windows | www.example | "URL" shows "Enter a valid URL. Use http(s), mailto, a path or #anchor." |
|
||||||
|
| timber windows | example.com | the same URL error |
|
||||||
|
| timber windows | javascript:alert(1) | the same URL error |
|
||||||
|
| timber windows | JaVaScRiPt:alert(1) | the same URL error |
|
||||||
|
| timber windows | javascript:alert(1) | the same URL error |
|
||||||
|
| timber windows | javascript:alert(1) | the same URL error |
|
||||||
|
| timber windows | data:text/html;base64,PHA+ | the same URL error |
|
||||||
|
| timber windows | vbscript:msgbox(1) | the same URL error |
|
||||||
|
| timber windows | file:///etc/passwd | the same URL error |
|
||||||
|
| timber windows | ftp://example.org/a | the same URL error |
|
||||||
|
| timber windows | tel:+33123456789 | the same URL error |
|
||||||
|
| timber windows | //evil.example | the same URL error |
|
||||||
|
| timber windows | page.html | the same URL error |
|
||||||
|
| timber windows | ../x | the same URL error |
|
||||||
|
| timber windows | http:// | the same URL error |
|
||||||
|
| timber windows | https://exa mple.org | the same URL error |
|
||||||
|
| | #measuring | "Link text" shows "Enter the link text." and has focus |
|
||||||
|
| (spaces) | #measuring | the same text error |
|
||||||
|
| | www.example | both errors show and focus goes to "Link text" |
|
||||||
|
|
||||||
|
Scenario Outline: Accepted URL forms
|
||||||
|
Given the dialog is open with "Link text" "x"
|
||||||
|
When the user enters "<url>" and activates "Insert link"
|
||||||
|
Then the link is inserted with href "<href>"
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| url | href |
|
||||||
|
| https://example.org/a?b=1#c | https://example.org/a?b=1#c |
|
||||||
|
| HTTP://Example.org | HTTP://Example.org |
|
||||||
|
| mailto:hello@example.org | mailto:hello@example.org |
|
||||||
|
| /articles/winter-checklist | /articles/winter-checklist |
|
||||||
|
| #measuring | #measuring |
|
||||||
|
| (padded) " /page " | /page |
|
||||||
|
|
||||||
|
Scenario: The URL validates on blur
|
||||||
|
Given the dialog is open and the user typed "www.example" in "URL"
|
||||||
|
When focus leaves "URL"
|
||||||
|
Then the URL error shows and nothing is inserted
|
||||||
|
|
||||||
|
Scenario: Link: long URL
|
||||||
|
Given the edit dialog is open on "planning guidance" with the 90-character URL
|
||||||
|
"https://www.example.org/planning/guidance/listed-buildings/windows-and-doors/…/2026-update.pdf"
|
||||||
|
Then "URL" stays on one line, does not widen the dialog, scrolls to reveal the whole value, and its title attribute holds the full URL
|
||||||
|
And "Save link" keeps its place and stays reachable at desktop and mobile width
|
||||||
|
|
||||||
|
Scenario Outline: Leaving the dialog without saving
|
||||||
|
Given the dialog is open with changed fields
|
||||||
|
When the user <leaves>
|
||||||
|
Then it closes, the body and the draft's dirty state are unchanged, and focus returns to the editor with the earlier selection
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| leaves |
|
||||||
|
| activates "Cancel" |
|
||||||
|
| presses Esc |
|
||||||
|
| clicks or taps outside it |
|
||||||
|
|
||||||
|
Scenario Outline: Dialog or sheet by viewport, popover or sheet by input
|
||||||
|
Given a link "timber windows" to "/articles/winter-checklist" in the body
|
||||||
|
When <action>
|
||||||
|
Then <result>
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| action | result |
|
||||||
|
| the user opens the link dialog at 1440 px wide | a dialog |
|
||||||
|
| the user opens the link dialog at 390 px wide | a bottom sheet with the same fields, errors and footer |
|
||||||
|
| a fine pointer clicks the link, or Enter on the focused link | a 288 px popover under the link with the URL, "Edit", "Open", "Remove"; the link button is active; Esc closes it and keeps the cursor in the link |
|
||||||
|
| a coarse pointer taps the link | a bottom sheet with "timber windows", the URL and 48 px rows "Edit link", "Open link", "Remove link"; Esc or a tap outside closes it |
|
||||||
|
| the user activates "Open" or "Open link" | the URL opens in a new tab with rel "noopener noreferrer" |
|
||||||
|
| the user activates "Remove" or "Remove link" | the link is removed with no confirmation, "Unsaved changes", and undo restores it |
|
||||||
|
|
||||||
|
Scenario Outline: Rendered link states in both themes
|
||||||
|
Given the body has the link "timber windows" and the theme is <theme>
|
||||||
|
Then the link <state>
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| state | theme |
|
||||||
|
| is --ui-text-highlighted with a 1 px underline at a 3 px offset | light |
|
||||||
|
| is --ui-text-highlighted with a 1 px underline at a 3 px offset | dark |
|
||||||
|
| shows a 2 px underline on pointer hover | light |
|
||||||
|
| shows a 2 px underline on pointer hover | dark |
|
||||||
|
| shows a 2 px --ui-primary outline at 2 px offset when reached by Tab or arrows | light |
|
||||||
|
| shows a 2 px --ui-primary outline at 2 px offset when reached by Tab or arrows | dark |
|
||||||
|
| has an --rc-sand fill and --rc-on-sand text when the selection crosses it | light |
|
||||||
|
| has an --rc-sand fill and --rc-on-sand text when the selection crosses it | dark |
|
||||||
|
|
||||||
|
Scenario: Toolbar overflow at 390 px
|
||||||
|
Given the viewport is 390 px wide
|
||||||
|
Then the full toolbar scrolls sideways in one row without wrapping
|
||||||
|
And a 24 or 32 px fade marks each side that has hidden buttons, and none on a side with nothing hidden
|
||||||
|
When the toolbar is scrolled to the end
|
||||||
|
Then the link, "Clear formatting" and "Image" buttons are visible, each 40 px
|
||||||
|
And at 1440 px the toolbar is unchanged and shows no fade
|
||||||
|
|
||||||
|
Scenario Outline: Selections that straddle a link or span blocks
|
||||||
|
Given the body is "<p>We also check the <a href=\"/a\">timber windows</a> before</p><p>any tiling starts.</p>"
|
||||||
|
And the selection is <selection>
|
||||||
|
When the user opens the dialog with the text unchanged and submits "/b"
|
||||||
|
Then the new link covers the whole selected range and replaces any partial link inside it
|
||||||
|
And no error occurs, and no text of the body is lost
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| selection |
|
||||||
|
| "check the timber" (plain text and part of a link)|
|
||||||
|
| "windows before" (part of a link and plain text) |
|
||||||
|
| "before" to "any tiling" (across two paragraphs) |
|
||||||
|
|
||||||
|
Scenario: Links survive the HTML body format and reach the other formats
|
||||||
|
Given a link "timber windows" to "/articles/winter-checklist" opening in a new tab is in the body
|
||||||
|
When the user saves and reloads /article/12/edit
|
||||||
|
Then PATCH /v1/article/12 carried the anchor with href, target="_blank" and rel="noopener noreferrer"
|
||||||
|
And the reloaded editor shows the link, and its edit dialog has the toggle on
|
||||||
|
And a link saved without the toggle carries neither target nor rel
|
||||||
|
When a client sends GET /v1/article/12?format=json, or ?format=markdown
|
||||||
|
Then json holds a link mark with href "/articles/winter-checklist" on "timber windows", and markdown holds [timber windows](/articles/winter-checklist), with no target or rel
|
||||||
|
|
||||||
|
Scenario Outline: An unsafe href already in a body is neutralised, and the next save rewrites the stored body
|
||||||
|
Given GET /v1/article/12 resolves a body containing <a href="<href>">x</a>, or the user pastes that HTML into the body
|
||||||
|
When the editor loads the body
|
||||||
|
Then the text "x" is kept without a link, the link button is not active on it, and clicking it navigates nowhere
|
||||||
|
And the load alone does not mark the draft dirty and sends no request, so the stored body is still unchanged
|
||||||
|
When the user makes any edit and saves
|
||||||
|
Then PATCH /v1/article/12 carries the neutralised body, without the unsafe href, so the stored body is silently rewritten without the link
|
||||||
|
And the body the editor serialises never contains "javascript:", "data:" or "vbscript:" in an href
|
||||||
|
And a paste is itself an edit, so in the paste case the draft is dirty straight away
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| href |
|
||||||
|
| javascript:alert(1) |
|
||||||
|
| data:text/html,<b> |
|
||||||
|
| vbscript:msgbox(1) |
|
||||||
@@ -0,0 +1,60 @@
|
|||||||
|
# QA: Inserting, editing and removing a link in the article body
|
||||||
|
|
||||||
|
## Automated (Vitest + Vue Test Utils, `task test:web`)
|
||||||
|
|
||||||
|
Mount EditorPage at `/article/12/edit` with the `editor_core.qa.md` fixture and the body
|
||||||
|
`<p>Every bathroom is different. We also check the timber windows before any tiling starts.</p>`.
|
||||||
|
Mock `request` for GET and PATCH /v1/article/12 only. Tiptap runs for real in jsdom; drive selection
|
||||||
|
through the editor instance. `request` is never called except by steps 8 and 9. Mock `matchMedia` for
|
||||||
|
`pointer: coarse` and for the viewport width.
|
||||||
|
|
||||||
|
1. **Button states, Examples-driven** - default, tooltip text per platform (Windows and Linux "Insert link (Ctrl+K)", macOS "Insert link (⌘K)", none on touch), focus ring class, active for cursor-in and for partial or full selection, disabled for an image selection, and Ctrl/Cmd+K inert in Preview and with `disabled`.
|
||||||
|
2. **Create, Examples-driven (3 rows)** - Ctrl+K and the button: title, prefill, focus target, toggle off; submit; body HTML holds the anchor; "Unsaved changes"; zero requests.
|
||||||
|
3. **Edit and remove, Examples-driven (3 rows)** - Edit and Ctrl+K entry, prefilled fields incl. the toggle, change href in place, no-op leaves a Saved draft Saved, "Remove link" with no confirm and undo restoring href and target.
|
||||||
|
4. **Validation, Examples-driven** - every row of both validation Outlines, plus the accepted-forms Outline: exact error text, dialog open, body and dirty state unchanged, focus target, and the trimmed href; the blur case. For the unsafe rows assert the body HTML never has "javascript:", "data:" or "vbscript:" in an href.
|
||||||
|
5. **Long URL** - the `title` attribute holds the full 90-character value, the dialog has no horizontal overflow, "Save link" is enabled.
|
||||||
|
6. **Leave without saving, Examples-driven** - Cancel, Esc, outside click: nothing changes; focus returns.
|
||||||
|
7. **Dialog/sheet and popover/sheet, Examples-driven** - width mock gives dialog or sheet; fine pointer gives popover (Esc closes), coarse gives sheet with three 48 px rows; Open calls `window.open(url, '_blank', 'noopener,noreferrer')`; Remove has no confirm and is undoable; "Open in new tab" gives `target="_blank" rel="noopener noreferrer"`, off gives neither.
|
||||||
|
8. **Round trip** - save with a new-tab link: the PATCH body has the anchor with target and rel; remount with it: link and toggle restored; without the toggle no target or rel.
|
||||||
|
9. **Unsafe hrefs, Examples-driven** - on load: text kept, no link, button not active, draft not dirty, zero requests; then an edit and Save: the PATCH body has no unsafe href. Paste of the same HTML: same neutralising, draft dirty.
|
||||||
|
10. **Selection edge cases, Examples-driven (3 rows)** - the new link covers the range, a partial link is replaced, no throw, and the text content before and after is identical. Then the French completeness check: every new key is in `messages.ts` and the dialog title and two error strings are spot-checked.
|
||||||
|
|
||||||
|
## Follow-ups and notes (not asserted here)
|
||||||
|
|
||||||
|
- **Follow-up Go slice (out of scope):** `?format=html` returns the stored HTML as is, and `safeHref` runs only for markdown and json. An API client that PATCHes `<a href="javascript:...">` gets it back in the html read. A separate Go slice should sanitise href schemes in the converter and probably reject them on write. The SPA sanitising here is defence in depth only.
|
||||||
|
- **Board-vs-reality note for the next Claude Design pass:** row 16 says the URL field "truncates in the middle of the line", and the board draws an ellipsis in the text. CSS cannot truncate the middle of an `<input>`. The implementation is a single scrolling line with the full URL in `title`.
|
||||||
|
- **Design gap for the next pass:** the helper text "Links open in the same tab unless you turn on a new tab." is in the board only. `components.md` ("LinkModal") needs it.
|
||||||
|
- **README undercount:** `docs/design/README.md` says "11 states"; `screens/editor.md` has 17 link rows (11-27). All 17 are covered.
|
||||||
|
|
||||||
|
## Visual: `task visual:check -- editor`
|
||||||
|
|
||||||
|
Setups go in `web/visual/states.ts` with the board's sample data: article "How we price a bathroom renovation", SaveStatus "Unsaved changes", link text "timber windows", URL "/articles/winter-checklist" (rows 13, 20, 22-26), "www.example" (14), "#measuring" (15), and for row 16 the text "planning guidance" with the 90-character URL above. Hover, focus and selection (rows 18, 23-26) are forced pseudo-states in the setup. If a row cannot be matched within 10 %, stop and ask the user: no per-state exception without `approvedBy`. No row is clock-sensitive.
|
||||||
|
|
||||||
|
| Row | State |
|
||||||
|
|---|---|
|
||||||
|
| 11 | Link: create from selection |
|
||||||
|
| 12 | Link: create with no selection |
|
||||||
|
| 13 | Link: edit existing (toggle on, Remove link) |
|
||||||
|
| 14 | Link: invalid URL |
|
||||||
|
| 15 | Link: empty text |
|
||||||
|
| 16 | Link: long URL |
|
||||||
|
| 17 | Link button: default |
|
||||||
|
| 18 | Link button: hover and tooltip (desktop only) |
|
||||||
|
| 19 | Link button: focus-visible |
|
||||||
|
| 20 | Link button: active |
|
||||||
|
| 21 | Link button: disabled (image selected) |
|
||||||
|
| 22 | Link popover (desktop) and sheet (mobile) |
|
||||||
|
| 23-26 | Rendered link: default, hover, focus, selected |
|
||||||
|
| 27 | Toolbar overflow (390 px, scrolled to the end; desktop unchanged) |
|
||||||
|
|
||||||
|
- [ ] Keyboard and focus: Tab order, Enter/Space on the button, focus trap and return, Esc on the popover, Enter on a focused link.
|
||||||
|
- [ ] Hover and motion: tooltip delay, underline thickening, sheet slide.
|
||||||
|
- [ ] Screen reader: aria-pressed, dialog labelling, error association.
|
||||||
|
|
||||||
|
## Manual verification
|
||||||
|
|
||||||
|
- **Ctrl/Cmd+K** in Chrome, Firefox, Safari and Edge: the browser shortcut is prevented only inside the focused editor.
|
||||||
|
- **macOS tooltip** on a real Mac.
|
||||||
|
- **Real touch** on a phone: a tap on a link opens the sheet and does not follow the link; the sideways toolbar scroll and fades work, including iOS momentum.
|
||||||
|
- **IME** in the Link text field.
|
||||||
|
- **Save and public read** against `task dev`: save a new-tab link, then GET ?format=html, ?format=json and ?format=markdown, and open the public page.
|
||||||
@@ -17,13 +17,16 @@ Feature: The editor's Library tab, picking an image from the media library
|
|||||||
a bottom sheet on mobile
|
a bottom sheet on mobile
|
||||||
And the footer reads "Cancel", and on the Library tab also a primary "Insert image" that is
|
And the footer reads "Cancel", and on the Library tab also a primary "Insert image" that is
|
||||||
disabled until an image is selected
|
disabled until an image is selected
|
||||||
And the Library tab calls GET /v1/media/ through useApi with limit=24, with q only while a
|
And the Library tab calls GET /v1/media/?q=Q&page=N&size=25 through useApi, with q only while a
|
||||||
search is set and cursor only when loading more (no filter and no sort parameter), and the
|
search is set and page 1, then 2, 3, ... when loading more (no filter and no sort parameter),
|
||||||
Upload tab is specified in features/editor_image_upload.feature
|
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
|
And the response is { items, total, page, size, counts }, newest first; "Load more" shows while
|
||||||
|
the loaded count is below the response total (the matching count, not counts.all); sizes read "8 KB" and
|
||||||
"3.9 MB", dimensions read "2400 × 1600" (an SVG reads "Vector"), dates are absolute
|
"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
|
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 }
|
picker mocks use total 48 and counts { all: 48, unused: 2, duplicates: 2 }
|
||||||
|
And this slice is amended by features/media_pagination_api.feature: cursor and limit are gone,
|
||||||
|
LIBRARY_PAGE_LIMIT 24 became the page size 25, and a mock with items equal to its total is the last page
|
||||||
And an image is "in this article" when an image node with its id as data-image-id is in
|
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;
|
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
|
in the examples below images 1 (north-wall.jpg) and 4 (logo-renew.svg) are in the article
|
||||||
@@ -42,13 +45,13 @@ Feature: The editor's Library tab, picking an image from the media library
|
|||||||
Rule: Which tab opens
|
Rule: Which tab opens
|
||||||
|
|
||||||
Scenario: The library has images, so Library opens
|
Scenario: The library has images, so Library opens
|
||||||
Given GET /v1/media/?limit=24 resolves 200 with the 12-image fixture
|
Given GET /v1/media/?page=1&size=25 resolves 200 with the 12-image fixture
|
||||||
When the user activates the toolbar's "Image" button
|
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"
|
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
|
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
|
Scenario: The library is empty, so Upload opens
|
||||||
Given GET /v1/media/?limit=24 resolves 200 with no item and no search set
|
Given GET /v1/media/?page=1&size=25 resolves 200 with no item and no search set
|
||||||
When the dialog opens
|
When the dialog opens
|
||||||
Then the Upload tab is selected, in its idle state
|
Then the Upload tab is selected, in its idle state
|
||||||
When the user selects the Library tab
|
When the user selects the Library tab
|
||||||
@@ -56,9 +59,9 @@ Feature: The editor's Library tab, picking an image from the media library
|
|||||||
|
|
||||||
Scenario: A dropped file opens Upload and sends no list request
|
Scenario: A dropped file opens Upload and sends no list request
|
||||||
When the user drops "before.png" onto the editor
|
When the user drops "before.png" onto the editor
|
||||||
Then the Upload tab is selected and no GET /v1/media/?limit=24 is sent
|
Then the Upload tab is selected and no GET /v1/media/?page=1&size=25 is sent
|
||||||
When the user selects the Library tab
|
When the user selects the Library tab
|
||||||
Then GET /v1/media/?limit=24 is sent
|
Then GET /v1/media/?page=1&size=25 is sent
|
||||||
|
|
||||||
Rule: Browsing
|
Rule: Browsing
|
||||||
|
|
||||||
@@ -75,7 +78,7 @@ Feature: The editor's Library tab, picking an image from the media library
|
|||||||
Then the line reads "Newest first"
|
Then the line reads "Newest first"
|
||||||
|
|
||||||
Scenario: Load more is hidden on the last page
|
Scenario: Load more is hidden on the last page
|
||||||
Given the response has next_cursor null
|
Given the loaded items equal the response total (for example total 12 with the 12-image fixture)
|
||||||
Then "Load more" is not shown
|
Then "Load more" is not shown
|
||||||
|
|
||||||
Scenario Outline: A tile's accessible name
|
Scenario Outline: A tile's accessible name
|
||||||
@@ -167,16 +170,16 @@ Feature: The editor's Library tab, picking an image from the media library
|
|||||||
Scenario: Typing searches after a debounce
|
Scenario: Typing searches after a debounce
|
||||||
Given the Library tab shows the 12-image fixture
|
Given the Library tab shows the 12-image fixture
|
||||||
When the user types "wall"
|
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
|
Then after a 120 ms debounce GET /v1/media/ is sent with q=wall, page=1 and size=25
|
||||||
And skeleton tiles show after 150 ms, and any selection is cleared
|
And skeleton tiles show after 150 ms, and any selection is cleared
|
||||||
|
|
||||||
Scenario: The x in the field clears the search
|
Scenario: The x in the field clears the search
|
||||||
Given the search field holds "wall" with results shown
|
Given the search field holds "wall" with results shown
|
||||||
When the user activates the x in the field
|
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
|
Then the field is empty and GET /v1/media/ is sent with page=1 and size=25 and no q
|
||||||
|
|
||||||
Scenario: No results
|
Scenario: No results
|
||||||
Given GET /v1/media/?q=wall&limit=24 resolves 200 with no item
|
Given GET /v1/media/?q=wall&page=1&size=25 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
|
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
|
And the search field still shows "wall" above it, and "Insert image" is disabled
|
||||||
When the user activates "Clear search"
|
When the user activates "Clear search"
|
||||||
@@ -185,23 +188,23 @@ Feature: The editor's Library tab, picking an image from the media library
|
|||||||
Rule: Load more
|
Rule: Load more
|
||||||
|
|
||||||
Scenario: Loading more shows progress and appends
|
Scenario: Loading more shows progress and appends
|
||||||
Given the first page resolved with 12 images, next_cursor "c24"
|
Given the first page resolved with 12 images and total 48
|
||||||
When the user activates "Load more"
|
When the user activates "Load more"
|
||||||
Then GET /v1/media/ is sent with limit=24 and cursor=c24
|
Then GET /v1/media/ is sent with page=2 and size=25
|
||||||
And the button reads "Loading…" with a loader-circle and is disabled, and one row of skeleton tiles shows at the end
|
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
|
And focus stays on the button
|
||||||
When the request resolves 200 with 12 more images
|
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
|
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
|
Scenario: The next page and the search combine
|
||||||
Given the search "wall" is active and the page has next_cursor "c24"
|
Given the search "wall" is active and the response total is above the loaded count
|
||||||
When the user activates "Load more"
|
When the user activates "Load more"
|
||||||
Then GET /v1/media/ is sent with q=wall, limit=24 and cursor=c24
|
Then GET /v1/media/ is sent with q=wall, page=2 and size=25
|
||||||
|
|
||||||
Rule: Empty and failed
|
Rule: Empty and failed
|
||||||
|
|
||||||
Scenario: Empty library
|
Scenario: Empty library
|
||||||
Given the Library tab is selected and GET /v1/media/?limit=24 resolved with no item
|
Given the Library tab is selected and GET /v1/media/?page=1&size=25 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"
|
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
|
And "Insert image" is disabled
|
||||||
When the user activates "Upload an image"
|
When the user activates "Upload an image"
|
||||||
|
|||||||
@@ -2,29 +2,29 @@
|
|||||||
|
|
||||||
## Automated (Vitest + Vue Test Utils, `task test:web`)
|
## 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.
|
Mock `request` for `GET /v1/media/` by parsed query. Use the 12-image fixture from `media_browse.feature` as `items`, with `total: 48`, `page`, `size: 25` and `counts: {all: 48, unused: 2, duplicates: 2}` (amended by `features/media_pagination_api.feature`: `next_cursor`, `cursor` and `limit` are gone). 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.
|
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.
|
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.
|
3. **Drop sends no list request** - drop a file; assert no `?page=1&size=25` 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.
|
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".
|
5. **Active search hides the count** - the line reads "Newest first".
|
||||||
6. **Last page** - `next_cursor: null` hides "Load more".
|
6. **Last page** - a total equal to the loaded count (for example 12) hides "Load more".
|
||||||
7. **Accessible names** - the three Examples.
|
7. **Accessible names** - the three Examples.
|
||||||
8. **Selection** - click, Enter and Space each select; check, outline, "Insert image" enabled.
|
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".
|
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.
|
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 `""`.
|
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.
|
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`.
|
13. **Search** - type "wall"; at 119 ms no request, at 120 ms the request has `q=wall&page=1&size=25`; 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.
|
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`.
|
15. **Load more** - request has `page=2&size=25`; 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 `page=2`.
|
||||||
16. **Failed to load, Examples 500 and network** - alert copy; "Try again" repeats the request; success replaces the alert.
|
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`
|
## 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:
|
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".
|
- Library mock: the 12-image fixture, `counts.all` 48, `total` 48; 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": 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.
|
- "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: loading": skeleton tiles.
|
||||||
@@ -46,9 +46,9 @@ 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.
|
- [ ] 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.
|
- [ ] Hover on a tile and on "Load more", and the focus ring.
|
||||||
- [ ] Motion: the dialog follows the standard 240 ms timing.
|
- [ ] 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 real library of more than 25 images through `task dev`: "Load more" and the page numbers.
|
||||||
- [ ] A screen reader reads the tile names and the alt text help.
|
- [ ] A screen reader reads the tile names and the alt text help.
|
||||||
|
|
||||||
## Manual verification
|
## Manual verification
|
||||||
|
|
||||||
Real `GET /v1/media/` with `q` and `cursor` against `task dev` with a live SQLite file.
|
Real `GET /v1/media/` with `q`, `page` and `size` against `task dev` with a live SQLite file.
|
||||||
@@ -330,12 +330,11 @@ Feature: Image variants settings screens, list and add/edit slide-over
|
|||||||
And its footer is 64 px high with "Cancel" and a primary "Add variant", and the status text is empty
|
And its footer is 64 px high with "Cancel" and a primary "Add variant", and the status text is empty
|
||||||
And focus moves to the Name field
|
And focus moves to the Name field
|
||||||
|
|
||||||
Scenario: Add variant opens a full page on mobile
|
Scenario: Add variant opens a bottom sheet on mobile
|
||||||
Given the viewport is below 640 px
|
Given the viewport is below 640 px
|
||||||
When the user activates "Add variant"
|
When the user activates "Add variant"
|
||||||
Then a full-screen page opens with a 56 px header holding an arrow-left back button and the title "Add variant", no x button
|
Then a tall bottom sheet opens as specified in features/variants_visual_conformance.feature, "Add variant is a tall bottom sheet on mobile", superseding the former full-page layout
|
||||||
And the form is followed by the Preview section, stacked, separated by a top border
|
And the form is followed by the Preview section, stacked, separated by a top border
|
||||||
And the footer is 72 px high with "Cancel" and "Add variant" sharing the width
|
|
||||||
|
|
||||||
Scenario: Edit opens with the stored values
|
Scenario: Edit opens with the stored values
|
||||||
When the user chooses "Edit" on the row "hero"
|
When the user chooses "Edit" on the row "hero"
|
||||||
|
|||||||
@@ -54,7 +54,7 @@ Mock navigator.clipboard. No test freezes the system date (this screen shows no
|
|||||||
recompute; deleting the last row shows Empty; failures 404 (reloads the list) / 500 -> toast.
|
recompute; deleting the last row shows Empty; failures 404 (reloads the list) / 500 -> toast.
|
||||||
14. **Reference card** — the 4 rows with badge words and icons, the exact JSON block text, the note;
|
14. **Reference card** — the 4 rows with badge words and icons, the exact JSON block text, the note;
|
||||||
absent in Loading/Empty/Error/Forbidden; one column below 640.
|
absent in Loading/Empty/Error/Forbidden; one column below 640.
|
||||||
15. **Slide-over open/close** — desktop slide-over vs mobile full page (back arrow, no x), titles
|
15. **Slide-over open/close** — desktop slide-over vs mobile bottom sheet (grabber, x; full-page back arrow superseded by features/variants_visual_conformance.feature), titles
|
||||||
"Add variant" / "Edit variant: hero", focus on Name, pristine close without dialog, dirty close
|
"Add variant" / "Edit variant: hero", focus on Name, pristine close without dialog, dirty close
|
||||||
via Cancel/x/back/Escape opens "Discard changes?" with the right text, Keep editing / Discard
|
via Cancel/x/back/Escape opens "Discard changes?" with the right text, Keep editing / Discard
|
||||||
changes behaviours, focus return to the opener.
|
changes behaviours, focus return to the opener.
|
||||||
@@ -135,7 +135,7 @@ Preview sample: north-wall.jpg, 4032 × 3024, 3.9 MB.
|
|||||||
`minmax(0,1.1fr) 104px 76px 72px 68px 92px 92px 132px 44px`, 36 px header, 48 px rows; cards 12 px
|
`minmax(0,1.1fr) 104px 76px 72px 68px 92px 92px 132px 44px`, 36 px header, 48 px rows; cards 12 px
|
||||||
padding with the name+switch line, the spec line, then count+menu; slide-over 960 px with a
|
padding with the name+switch line, the spec line, then count+menu; slide-over 960 px with a
|
||||||
440 px form column; compare box 3:2, chips 8 px from the top corners, handle 32 px (44 px on
|
440 px form column; compare box 3:2, chips 8 px from the top corners, handle 32 px (44 px on
|
||||||
mobile) centred on a 2 px divider; footer 64 px (72 px on mobile).
|
mobile) centred on a 2 px divider; footer 64 px (mobile sheet footer: see features/variants_visual_conformance.feature).
|
||||||
- [ ] Not drawn, no visual state: toggle failures, the purge/delete failure toasts, the 409-free
|
- [ ] Not drawn, no visual state: toggle failures, the purge/delete failure toasts, the 409-free
|
||||||
status toasts, the 422 mapping, the clipboard states "Copied" (add only if the board draws it: it
|
status toasts, the 422 mapping, the clipboard states "Copied" (add only if the board draws it: it
|
||||||
does not, so Vitest only), singular footer.
|
does not, so Vitest only), singular footer.
|
||||||
|
|||||||
@@ -7,7 +7,7 @@ Feature: Integration screen (API reference)
|
|||||||
Background:
|
Background:
|
||||||
Given /integration is a verified route (meta.auth "verified") rendered as IntegrationPage
|
Given /integration is a verified route (meta.auth "verified") rendered as IntegrationPage
|
||||||
inside DashboardShell, per docs/design/routes.md
|
inside DashboardShell, per docs/design/routes.md
|
||||||
And the screen makes no /v1 calls; api: none (static)
|
And the screen makes one call, GET /v1/image-variants, for owner and admin sessions only (features/integration_images.feature)
|
||||||
And the PageHeader shows breadcrumb "Integration", title "API reference" and description
|
And the PageHeader shows breadcrumb "Integration", title "API reference" and description
|
||||||
"Everything a developer needs to build on RenewCMS."
|
"Everything a developer needs to build on RenewCMS."
|
||||||
And the endpoint catalogue is a typed static data file at web/src/data/apiCatalogue.ts, and the view only renders it
|
And the endpoint catalogue is a typed static data file at web/src/data/apiCatalogue.ts, and the view only renders it
|
||||||
@@ -37,7 +37,7 @@ Feature: Integration screen (API reference)
|
|||||||
Scenario: Default, every card collapsed
|
Scenario: Default, every card collapsed
|
||||||
When the user navigates to /integration
|
When the user navigates to /integration
|
||||||
Then the intro reads "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."
|
Then the intro reads "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."
|
||||||
And a "Base URL" row shows window.location.origin in a monospace box with a "Copy" button (icon copy)
|
And a "Base URL" label sits above a CodeSnippet with the single tab "Base URL" showing window.location.origin and a "Copy" button (icon copy)
|
||||||
And every EndpointCard is collapsed as a 44 px row: method badge, mono path, one-line description, chips, chevron
|
And every EndpointCard is collapsed as a 44 px row: method badge, mono path, one-line description, chips, chevron
|
||||||
And the sticky section index lists the sections on desktop and a "Jump to" select lists them on mobile
|
And the sticky section index lists the sections on desktop and a "Jump to" select lists them on mobile
|
||||||
|
|
||||||
@@ -69,8 +69,8 @@ Feature: Integration screen (API reference)
|
|||||||
And a "Request body" table lists:
|
And a "Request body" table lists:
|
||||||
| Name | Type | Required | Rule |
|
| Name | Type | Required | Rule |
|
||||||
| title | string | Yes | 3 to 200 characters. Can't be changed later. |
|
| title | string | Yes | 3 to 200 characters. Can't be changed later. |
|
||||||
| body | string | Yes | Up to 10 000 characters. |
|
| body | string | No | No length limit. |
|
||||||
And tabs fetch, curl and Response show, fetch active, with a CodeBlock labelled "JavaScript" and a ghost "Copy" button
|
And one CodeSnippet with the tabs fetch, curl and Response shows, fetch active, with a "Copy" button
|
||||||
And an "Errors" list shows a status chip with a one-line caption for 400, 401
|
And an "Errors" list shows a status chip with a one-line caption for 400, 401
|
||||||
|
|
||||||
Scenario: Query parameters table, new UI beyond the board, user-approved
|
Scenario: Query parameters table, new UI beyond the board, user-approved
|
||||||
@@ -90,8 +90,8 @@ Feature: Integration screen (API reference)
|
|||||||
Then <method> <path> lists these fields: <fields>
|
Then <method> <path> lists these fields: <fields>
|
||||||
Examples:
|
Examples:
|
||||||
| method | path | fields |
|
| method | path | fields |
|
||||||
| POST | /v1/article/ | title string required 3-200; body string required max 10000 |
|
| POST | /v1/article/ | title string required 3-200; body string optional, no length limit |
|
||||||
| PATCH | /v1/article/{id} | body string required max 10000 |
|
| PATCH | /v1/article/{id} | body string optional, no length limit |
|
||||||
| PATCH | /v1/media/{id} | filename string required |
|
| PATCH | /v1/media/{id} | filename string required |
|
||||||
| POST | /v1/media/merge | keep_id number required >0; merge_ids number[] required min 1 each >0 |
|
| POST | /v1/media/merge | keep_id number required >0; merge_ids number[] required min 1 each >0 |
|
||||||
| POST | /v1/media/ | multipart/form-data, 1 file field named "file" |
|
| POST | /v1/media/ | multipart/form-data, 1 file field named "file" |
|
||||||
@@ -114,7 +114,7 @@ Feature: Integration screen (API reference)
|
|||||||
Scenario: Authentication section
|
Scenario: Authentication section
|
||||||
Then card "Public" reads "No key needed. Two read-only routes, and only online articles are returned." and names GET /v1/article/ and GET /v1/article/{id}
|
Then card "Public" reads "No key needed. Two read-only routes, and only online articles are returned." and names GET /v1/article/ and GET /v1/article/{id}
|
||||||
And card "API key" reads "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."
|
And card "API key" reads "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."
|
||||||
And its CodeBlock has tabs curl and fetch for GET /v1/auth/me, using the current origin
|
And its CodeSnippet has tabs curl and fetch for GET /v1/auth/me, using the current origin
|
||||||
And it says "Keys start with `rcms_` and are shown in full once, when you create them."
|
And it says "Keys start with `rcms_` and are shown in full once, when you create them."
|
||||||
And a "Manage API keys" link navigates to /integration/api-keys
|
And a "Manage API keys" link navigates to /integration/api-keys
|
||||||
And Note 1 reads "A key can't create, list or revoke API keys, verify or cancel a registration, 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."
|
And Note 1 reads "A key can't create, list or revoke API keys, verify or cancel a registration, 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."
|
||||||
@@ -139,7 +139,7 @@ Feature: Integration screen (API reference)
|
|||||||
| 409 | There's already a pending invite for this address. / This invite has already been accepted. |
|
| 409 | There's already a pending invite for this address. / This invite has already been accepted. |
|
||||||
| 429 | Too many requests. Please try again later. |
|
| 429 | Too many requests. Please try again later. |
|
||||||
| 500 | Internal server error |
|
| 500 | Internal server error |
|
||||||
And a sample shows "HTTP/1.1 403 Forbidden", "Content-Type: text/plain", a blank line, and "This action needs a real session."
|
And a CodeSnippet with the single tab "Error response · text/plain" shows "HTTP/1.1 403 Forbidden", "Content-Type: text/plain", a blank line, and "This action needs a real session."
|
||||||
And the table does not use the SPA copy of docs/design/states.md
|
And the table does not use the SPA copy of docs/design/states.md
|
||||||
|
|
||||||
Scenario Outline: Per-endpoint error captions use the real strings
|
Scenario Outline: Per-endpoint error captions use the real strings
|
||||||
@@ -169,15 +169,15 @@ Feature: Integration screen (API reference)
|
|||||||
Given the app is served from origin "{origin}"
|
Given the app is served from origin "{origin}"
|
||||||
When the user activates the Base URL "Copy" button
|
When the user activates the Base URL "Copy" button
|
||||||
Then "{origin}" is written to the clipboard
|
Then "{origin}" is written to the clipboard
|
||||||
And the button shows icon check and "Copied", announced to assistive technology
|
And the button, named "Copy code", shows icon check and "Copied", announced politely
|
||||||
When 2 seconds elapse
|
When 2 seconds elapse
|
||||||
Then the button reverts to icon copy and "Copy"
|
Then the button reverts to icon copy and "Copy"
|
||||||
|
|
||||||
Scenario: Copied, CodeBlock is independent of Base URL
|
Scenario: Copied, CodeSnippet is independent of Base URL
|
||||||
Given a card is expanded
|
Given a card is expanded
|
||||||
When the user activates that CodeBlock's "Copy JavaScript example" button
|
When the user activates that CodeSnippet's "Copy code" button
|
||||||
Then that card's exact code string is written to the clipboard and only that button reads "Copied"
|
Then the active tab's exact code string is written to the clipboard and only that button reads "Copied"
|
||||||
And the Base URL button and other CodeBlocks are unaffected
|
And the Base URL button and other CodeSnippets are unaffected
|
||||||
|
|
||||||
Scenario: Examples use the current origin and the API key header
|
Scenario: Examples use the current origin and the API key header
|
||||||
Then every fetch and curl example starts from "{origin}" and carries no ?format= query
|
Then every fetch and curl example starts from "{origin}" and carries no ?format= query
|
||||||
@@ -189,5 +189,7 @@ Feature: Integration screen (API reference)
|
|||||||
Then the page scrolls to that anchor and the item reports aria-current "true"
|
Then the page scrolls to that anchor and the item reports aria-current "true"
|
||||||
And on mobile the "Jump to" select opens and lists the same sections
|
And on mobile the "Jump to" select opens and lists the same sections
|
||||||
|
|
||||||
Scenario: The page stays static
|
Scenario: Only the image variants calls
|
||||||
Then no /v1 request is made while the page renders or while any card is expanded
|
Then the only /v1 request is GET /v1/image-variants, sent for owner and admin sessions on mount, on "Try again" and on window focus
|
||||||
|
And expanding or collapsing any card makes no /v1 request
|
||||||
|
And a session that is neither owner nor admin makes no /v1 request
|
||||||
@@ -4,7 +4,7 @@
|
|||||||
|
|
||||||
Mount IntegrationPage inside DashboardShell with a resolved verified session and a test router at
|
Mount IntegrationPage inside DashboardShell with a resolved verified session and a test router at
|
||||||
/integration. Stub `window.location.origin` to `https://cms.renew.example` (the board's sample) and
|
/integration. Stub `window.location.origin` to `https://cms.renew.example` (the board's sample) and
|
||||||
`navigator.clipboard.writeText` per case. No `/v1` mocks are needed. A spec fails if any `/v1` call
|
`navigator.clipboard.writeText` per case. Mock only GET /v1/image-variants (see integration_images.qa.md). A spec fails if any other `/v1` call
|
||||||
is made.
|
is made.
|
||||||
|
|
||||||
Catalogue spec (pure data, no mount, imports web/src/data/apiCatalogue.ts):
|
Catalogue spec (pure data, no mount, imports web/src/data/apiCatalogue.ts):
|
||||||
@@ -21,14 +21,14 @@ Catalogue spec (pure data, no mount, imports web/src/data/apiCatalogue.ts):
|
|||||||
- article: id, title, body, body_format, is_online, created_at, updated_at;
|
- article: id, title, body, body_format, is_online, created_at, updated_at;
|
||||||
- media item: id, filename, url, size, content_type, width, height, sha256, uploaded_by,
|
- media item: id, filename, url, size, content_type, width, height, sha256, uploaded_by,
|
||||||
created_at, used_in, duplicate;
|
created_at, used_in, duplicate;
|
||||||
- media list: items, next_cursor, counts (all, unused, duplicates);
|
- media list: items, total, page, size, counts (all, unused, duplicates), no next_cursor;
|
||||||
- merge: articles_updated, merged;
|
- merge: articles_updated, merged;
|
||||||
- usage: id, title, published;
|
- usage: id, title, published;
|
||||||
- user list item: id, kind, username, display_name, email, role, status, created_at;
|
- user list item: id, kind, username, display_name, email, role, status, created_at;
|
||||||
- invite: id, kind, email, status, created_at, expires_at;
|
- invite: id, kind, email, status, created_at, expires_at;
|
||||||
- settings: version.
|
- settings: version.
|
||||||
Any other key fails the spec. "images" and "status" are explicitly rejected on articles.
|
Any other key fails the spec. "images" and "status" are explicitly rejected on articles.
|
||||||
5. Request-body tables equal the validate tags (title 3-200, body max 10000, filename, keep_id,
|
5. Request-body tables equal the validate tags (title 3-200, body optional with no length limit, filename, keep_id,
|
||||||
merge_ids, display_name, email). The multipart field is "file". Query tables: `format` on every
|
merge_ids, display_name, email). The multipart field is "file". Query tables: `format` on every
|
||||||
article route, and q, hash, cursor, filter, sort, limit on GET /v1/media/.
|
article route, and q, hash, cursor, filter, sort, limit on GET /v1/media/.
|
||||||
6. The three invite routes carry "Owner only", a 403 "Only the owner can do this." caption and the
|
6. The three invite routes carry "Owner only", a 403 "Only the owner can do this." caption and the
|
||||||
@@ -44,12 +44,12 @@ Component specs, one per design state:
|
|||||||
invite rows show "Owner only".
|
invite rows show "Owner only".
|
||||||
2. **Group scrolled, one card expanded**: click the POST /v1/article/ row. Assert the Query
|
2. **Group scrolled, one card expanded**: click the POST /v1/article/ row. Assert the Query
|
||||||
parameters table above the Request body table, the body rows, tabs fetch/curl/Response with fetch
|
parameters table above the Request body table, the body rows, tabs fetch/curl/Response with fetch
|
||||||
active, the "JavaScript" CodeBlock, and the Errors list with 400 and 401.
|
active in one CodeSnippet, and the Errors list with 400 and 401.
|
||||||
3. **Copied: base URL**: fake timers; click Copy. Clipboard gets the origin; check icon and "Copied";
|
3. **Copied: base URL**: fake timers; click Copy. Clipboard gets the origin; check icon and "Copied";
|
||||||
announced; reverts after 2 s.
|
announced; reverts after 2 s.
|
||||||
4. **Copied: CodeBlock**: expand a card; click "Copy JavaScript example". Clipboard gets that code,
|
4. **Copied: CodeSnippet**: expand a card; click "Copy code". Clipboard gets the active tab's code,
|
||||||
only that button reads "Copied", and it reverts after 2 s.
|
only that button reads "Copied", and it reverts after 2 s.
|
||||||
5. **Authentication**: both cards, curl/fetch tabs for GET /v1/auth/me, the "Manage API keys" link
|
5. **Authentication**: both cards, a CodeSnippet with curl/fetch tabs for GET /v1/auth/me, the "Manage API keys" link
|
||||||
href /integration/api-keys, Note 1, Note 2.
|
href /integration/api-keys, Note 1, Note 2.
|
||||||
6. **Session only**: the corrected banner; lock icon and "Session only" chip only on rows that
|
6. **Session only**: the corrected banner; lock icon and "Session only" chip only on rows that
|
||||||
answer 403; the caption on the login family; no expand control; the "Public auth flow" rows with
|
answer 403; the caption on the login family; no expand control; the "Public auth flow" rows with
|
||||||
@@ -61,6 +61,7 @@ Component specs, one per design state:
|
|||||||
9. **Tabs**: curl and Response render for a card. curl contains the stubbed origin and the
|
9. **Tabs**: curl and Response render for a card. curl contains the stubbed origin and the
|
||||||
Authorization header only on non-public routes. Not visually checked.
|
Authorization header only on non-public routes. Not visually checked.
|
||||||
10. **Notes**: format note, image-prefix note, CORS note.
|
10. **Notes**: format note, image-prefix note, CORS note.
|
||||||
|
11. **Base URL and error sample**: both are CodeSnippets (single tabs "Base URL" and "Error response · text/plain").
|
||||||
|
|
||||||
## Visual (`task visual:check -- integration`, desktop and mobile, light and dark)
|
## Visual (`task visual:check -- integration`, desktop and mobile, light and dark)
|
||||||
|
|
||||||
@@ -78,7 +79,7 @@ diff, sets the smallest `maxPercent` that is sufficient, writes the reason, and
|
|||||||
- [ ] Default (exception: owner-only chips and rate-limit line)
|
- [ ] Default (exception: owner-only chips and rate-limit line)
|
||||||
- [ ] Group scrolled, one card expanded (exception: Query parameters table)
|
- [ ] Group scrolled, one card expanded (exception: Query parameters table)
|
||||||
- [ ] Copied: base URL (must pass 10 %)
|
- [ ] Copied: base URL (must pass 10 %)
|
||||||
- [ ] Copied: CodeBlock (must pass 10 %)
|
- [ ] Copied: CodeSnippet (must pass 10 %)
|
||||||
- [ ] Authentication (must pass 10 %; Note 1 text changed)
|
- [ ] Authentication (must pass 10 %; Note 1 text changed)
|
||||||
- [ ] Session only (exception: banner, 13th row, captions, Public auth flow block)
|
- [ ] Session only (exception: banner, 13th row, captions, Public auth flow block)
|
||||||
- [ ] Errors (exception: 409 row)
|
- [ ] Errors (exception: 409 row)
|
||||||
@@ -88,7 +89,7 @@ None of these states is clock-sensitive, so none is skipped.
|
|||||||
|
|
||||||
## Manual
|
## Manual
|
||||||
- Keyboard and focus order: index, Base URL Copy, each row (Enter/Space), tab strip (arrow keys),
|
- Keyboard and focus order: index, Base URL Copy, each row (Enter/Space), tab strip (arrow keys),
|
||||||
CodeBlock Copy, the pre (tabindex 0), Jump to on mobile.
|
CodeSnippet Copy, the pre (tabindex 0), Jump to on mobile.
|
||||||
- Hover and motion on ghost Copy buttons and rows.
|
- Hover and motion on ghost Copy buttons and rows.
|
||||||
- Find-in-page and a deep link to an `#ep-...` anchor.
|
- Find-in-page and a deep link to an `#ep-...` anchor.
|
||||||
- Real origin in a production build and under `task dev`.
|
- Real origin in a production build and under `task dev`.
|
||||||
|
|||||||
@@ -0,0 +1,305 @@
|
|||||||
|
Feature: Integration: images and variants, and CodeSnippet as the only code block
|
||||||
|
|
||||||
|
As a developer building a site on RenewCMS
|
||||||
|
I want the Integration page to explain image variants and give me copyable, correct URLs
|
||||||
|
So that I can request the right image size without reading the source
|
||||||
|
|
||||||
|
Background:
|
||||||
|
Given the spec of record is docs/design/screens/integration.md ("Integration: images and ?v="),
|
||||||
|
docs/design/screens/integration-api-keys.md, docs/design/components.md (CodeSnippet), the boards
|
||||||
|
docs/design/source/IntegrationImages.dc.html and CodeSnippet.dc.html, and docs/design/routes.md
|
||||||
|
And this slice is SPA only: no Go change, and the image API is the one of features/image-variants.feature
|
||||||
|
And /integration is a verified route rendered as IntegrationPage inside DashboardShell, per
|
||||||
|
features/integration.feature
|
||||||
|
And the section "Images and variants" has the anchor id "images", sits where the board draws it (after the API groups and before "Session only" and "Errors"), and has an entry "Images and variants" in the section index and the "Jump to" select
|
||||||
|
And the section index and the "Jump to" select list the sections in page order, so the "Images and variants" entry sits right before "Session only"
|
||||||
|
And the board and its own index disagree on this position, which is logged for the design pass
|
||||||
|
And the section title is an h2 "Images and variants" (18/26) with sub headings h3 (14/22)
|
||||||
|
And the section intro reads "Every image in the media library can be requested as a named variant. Add the
|
||||||
|
?v=<variant-name> parameter to the image URL. The original file is never changed, and a variant is generated the
|
||||||
|
first time it is requested. Variants are managed in Settings, Media, Variants."
|
||||||
|
And the section calls, with a relative URL through useApi only, GET /v1/image-variants, an owner/admin-only route
|
||||||
|
And an item has the fields name, width, height, fit, format, quality, generate_on_upload, enabled,
|
||||||
|
generated_files and cache_size, and items arrive in name order
|
||||||
|
And only items with enabled true are "enabled variants"; the order of the API response is kept
|
||||||
|
And "first variant" below means the first enabled variant, "second" and "third" the next ones, each falling back to the first when absent
|
||||||
|
And {origin} is window.location.origin and {image} is the builder image, "north-wall.jpg", a fixed sample with no media lookup
|
||||||
|
And a variant URL is "{origin}/media/{image}?v={name}"
|
||||||
|
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 section uses Nuxt UI components and design tokens only, with no raw colour
|
||||||
|
And the list is read through the useImageVariantsStore
|
||||||
|
And the board sample data is {origin} "https://cms.renew.example", image "north-wall.jpg" and these variants, in this order:
|
||||||
|
| name | width | height | format |
|
||||||
|
| thumb | 400 | 300 | webp |
|
||||||
|
| card | 800 | null | webp |
|
||||||
|
| hero | 1200 | 630 | webp |
|
||||||
|
| square | 600 | 600 | jpeg |
|
||||||
|
| og | 1200 | 630 | jpeg |
|
||||||
|
| banner | 1600 | 400 | webp |
|
||||||
|
| teaser | 640 | 360 | webp |
|
||||||
|
| sidebar | 320 | null | webp |
|
||||||
|
| gallery | 1000 | 750 | webp |
|
||||||
|
| avatar | 96 | 96 | webp |
|
||||||
|
| wide | 1920 | 800 | webp |
|
||||||
|
| mini | 120 | 90 | webp |
|
||||||
|
|
||||||
|
Rule: CodeSnippet is the only code block
|
||||||
|
|
||||||
|
Scenario: CodeSnippet anatomy
|
||||||
|
Given a CodeSnippet with the tabs curl, HTML and JavaScript
|
||||||
|
Then a header row at least 44 px high holds the tab list (aria-label "Language") on the left and the Copy button on the right
|
||||||
|
And the selected tab has text --ui-text-highlighted, weight 500 and a 2 px --ui-primary underline
|
||||||
|
And unselected tabs have --ui-text-toned and weight 400
|
||||||
|
And below it a pre with tabindex 0 shows the active tab's code in IBM Plex Mono 12/19, scrolls horizontally and has no syntax colouring
|
||||||
|
And the background is --ui-bg-elevated with a --ui-border border and no corner radius
|
||||||
|
And the Copy button is at least 44 px wide, reads "Copy" with icon copy and has the accessible name "Copy code"
|
||||||
|
And each tab and the Copy button show a 2 px --ui-primary focus ring when focused with the keyboard
|
||||||
|
|
||||||
|
Scenario: A CodeSnippet with one tab shows a plain label
|
||||||
|
Given a CodeSnippet with a single tab "Base URL"
|
||||||
|
Then the label is plain --ui-text-muted text, not a tab, with no underline
|
||||||
|
|
||||||
|
Scenario: Copy writes the active tab and reads Copied for 2 s
|
||||||
|
Given a CodeSnippet with the tabs curl, HTML and JavaScript and the JavaScript tab active
|
||||||
|
When the user activates "Copy"
|
||||||
|
Then the JavaScript code is written to the clipboard
|
||||||
|
And the button shows icon check and "Copied" in --ui-success
|
||||||
|
And the text lives in an aria-live "polite" region, so "Copied" is announced politely
|
||||||
|
When 2 seconds elapse
|
||||||
|
Then the button reads "Copy" with icon copy again
|
||||||
|
|
||||||
|
Scenario: Two CodeSnippets copy independently
|
||||||
|
Given the page shows several CodeSnippets
|
||||||
|
When the user activates "Copy" on one of them
|
||||||
|
Then only that one reads "Copied"
|
||||||
|
|
||||||
|
Scenario Outline: Every code block of the product is a CodeSnippet
|
||||||
|
Then <place> renders as a CodeSnippet with <tabs>
|
||||||
|
And no CodeBlock, no shiki highlighted block and no hand-rolled copy button remains there
|
||||||
|
Examples:
|
||||||
|
| place | tabs |
|
||||||
|
| Base URL on /integration (label "Base URL" above it) | one tab "Base URL" with {origin} |
|
||||||
|
| the Authentication "API key" example | tabs curl and fetch, GET /v1/auth/me |
|
||||||
|
| an expanded EndpointCard | tabs fetch, curl and Response, fetch active |
|
||||||
|
| the Errors section sample | one tab "Error response · text/plain" |
|
||||||
|
| the "Request an image" snippet | tabs curl, HTML and JavaScript |
|
||||||
|
| the URL builder output | one tab "URL" |
|
||||||
|
| the one-time key of ApiKeyReveal on /integration/api-keys | one tab "API key" |
|
||||||
|
|
||||||
|
Scenario: The old component is removed
|
||||||
|
Then web/src/components/CodeBlock.vue no longer exists and nothing imports it, including EndpointCard.vue and IntegrationView.vue
|
||||||
|
And web/src/components/CodeText.vue stays, because it renders inline code in prose and not a code block
|
||||||
|
And the shiki highlighter helpers and styles used only by CodeBlock are removed when nothing else uses them
|
||||||
|
And the hand-rolled Base URL box, the error sample pre and the key box of ApiKeyReveal are gone
|
||||||
|
|
||||||
|
Scenario: The one-time key reveal keeps its behaviour
|
||||||
|
Given the ApiKeyReveal dialog opens after POST /v1/api-key answers 201
|
||||||
|
Then the key is shown in a CodeSnippet with one tab "API key" and "Copy"
|
||||||
|
And the Copy button receives focus when the dialog opens, as before
|
||||||
|
And activating it writes the full key to the clipboard and reads "Copied" for 2 s, announced politely
|
||||||
|
And the warning "You won't be able to see this key again." and the text "Closing this window discards the key from the screen. Copy it first." stay unchanged
|
||||||
|
|
||||||
|
Rule: The variants list is reloaded
|
||||||
|
|
||||||
|
Scenario: Reload triggers
|
||||||
|
Given the session role is "owner" or "admin"
|
||||||
|
Then GET /v1/image-variants is sent on mount
|
||||||
|
And it is sent again on "Try again"
|
||||||
|
And it is sent again on every window focus event while /integration is shown
|
||||||
|
And a reload keeps the active snippet tab and the builder selection when the selected variant is still enabled
|
||||||
|
|
||||||
|
Scenario: A non-admin never calls the API
|
||||||
|
Given the session role is neither "owner" nor "admin"
|
||||||
|
Then no request to GET /v1/image-variants is sent on mount, on focus or on any other trigger
|
||||||
|
|
||||||
|
Rule: Section content
|
||||||
|
|
||||||
|
Background:
|
||||||
|
Given the session role is "owner"
|
||||||
|
|
||||||
|
Scenario: I1. Many variants
|
||||||
|
Given GET /v1/image-variants answers 200 with the twelve sample variants enabled and "print" (disabled)
|
||||||
|
When the user opens /integration#images
|
||||||
|
Then the h3 "Request an image" shows a CodeSnippet with tabs "curl", "HTML", "JavaScript", with HTML active
|
||||||
|
And the h3 "Variants" shows "12 enabled variants"
|
||||||
|
And the table has the columns Name, Dimensions, Format and Example URL and 12 rows, in API order
|
||||||
|
And the "thumb" row reads "thumb", "400×300", "WebP", "/media/north-wall.jpg?v=thumb"
|
||||||
|
And the "card" row reads "800 × auto"
|
||||||
|
And the table body scrolls vertically at 264 px, because there are more than 6 rows
|
||||||
|
And the note reads "Disabled variants are not served. A request for one returns 400 "Unknown variant"."
|
||||||
|
And "print" is not a row
|
||||||
|
And the h3 "URL builder" shows the Image, Variant (default "thumb"), URL (CodeSnippet) and Preview
|
||||||
|
And the h3 "Responses" shows the responses table
|
||||||
|
|
||||||
|
Scenario: The disabled-variants note matches the backend
|
||||||
|
Given a variant "print" is disabled
|
||||||
|
When /media/north-wall.jpg?v=print is requested
|
||||||
|
Then the backend answers 400 application/json with {"status":400,"error":"unknown_variant","message":"Unknown variant","detail":"print"} and does not fall back to the original
|
||||||
|
And the note is shown only when the response contains at least one disabled variant
|
||||||
|
|
||||||
|
Scenario: The snippets use the first variants
|
||||||
|
Given the sample variants
|
||||||
|
Then the curl tab reads: curl -O "https://cms.renew.example/media/north-wall.jpg?v=thumb"
|
||||||
|
And the HTML tab reads:
|
||||||
|
"""
|
||||||
|
<img
|
||||||
|
src="https://cms.renew.example/media/north-wall.jpg?v=card"
|
||||||
|
srcset="https://cms.renew.example/media/north-wall.jpg?v=thumb 400w,
|
||||||
|
https://cms.renew.example/media/north-wall.jpg?v=card 800w,
|
||||||
|
https://cms.renew.example/media/north-wall.jpg?v=hero 1200w"
|
||||||
|
sizes="(min-width: 800px) 800px, 100vw"
|
||||||
|
alt="North wall">
|
||||||
|
"""
|
||||||
|
And the JavaScript tab reads:
|
||||||
|
"""
|
||||||
|
const res = await fetch("https://cms.renew.example/media/north-wall.jpg?v=thumb")
|
||||||
|
if (!res.ok) throw new Error(await res.text())
|
||||||
|
const blob = await res.blob()
|
||||||
|
"""
|
||||||
|
And the srcset widths 400w, 800w and 1200w are sample values, not read from the variants
|
||||||
|
|
||||||
|
Scenario: Tables and snippet scroll on narrow screens
|
||||||
|
Given a viewport of 390 px
|
||||||
|
Then the variants table keeps a minimum width of 520 px and scrolls horizontally inside its border
|
||||||
|
And the Responses table keeps a minimum width of 560 px and scrolls horizontally
|
||||||
|
And the CodeSnippet body scrolls horizontally and the page itself does not
|
||||||
|
|
||||||
|
Scenario: I2. One variant
|
||||||
|
Given GET /v1/image-variants answers 200 with only "thumb" enabled
|
||||||
|
Then the Variants heading reads "1 enabled variant" and the table has one row without a vertical scroll limit
|
||||||
|
And the three snippets use "thumb" for the first, second and third variant
|
||||||
|
And the "Disabled variants are not served" note is not shown
|
||||||
|
|
||||||
|
Scenario: I3. No variants, admin
|
||||||
|
Given the session role is "admin"
|
||||||
|
And GET /v1/image-variants answers 200 with {"items": []} or only disabled variants
|
||||||
|
Then an empty block with the layers icon shows "No image variants yet"
|
||||||
|
And its text reads "Until you add a variant, any request with the ?v= parameter returns status 400 unknown_variant. Requests without it return the original image."
|
||||||
|
And a primary button "Go to image variants" navigates to /settings/media/variants
|
||||||
|
And the snippets use the placeholder <variant-name>
|
||||||
|
And no table and no URL builder are drawn
|
||||||
|
And the Responses table is drawn
|
||||||
|
|
||||||
|
Scenario: I4. No variants, not an admin
|
||||||
|
Given the session role is neither "owner" nor "admin"
|
||||||
|
Then no request to GET /v1/image-variants is sent
|
||||||
|
And the empty block shows "No image variants yet"
|
||||||
|
And its text reads "Ask an owner or admin to add one. Until you do, any request with the ?v= parameter returns status 400 unknown_variant. Requests without it return the original image."
|
||||||
|
And there is no button and no link
|
||||||
|
And the snippets use the placeholder <variant-name>
|
||||||
|
|
||||||
|
Scenario: The empty-state copy is corrected against the backend
|
||||||
|
Then the I3 and I4 texts above replace the design copy "the ?v= parameter is not accepted and every request returns the original image", which is false
|
||||||
|
And the backend returns 400 unknown_variant for any ?v= value when no variants exist, and serves the original only without ?v
|
||||||
|
And the board copy is logged as wrong for the design pass, and docs/design is not edited
|
||||||
|
|
||||||
|
Scenario: I5. Variant removed
|
||||||
|
Given the URL builder has "hero" selected
|
||||||
|
And a reload of the list returns no enabled "hero"
|
||||||
|
Then the Variant field reads "hero (removed)" and has a --ui-warning border
|
||||||
|
And the URL snippet reads "https://cms.renew.example/media/north-wall.jpg?v=hero"
|
||||||
|
And a warning alert (role alert, triangle-alert icon) reads the title "The variant "hero" no longer exists"
|
||||||
|
And its text reads "There is no fallback to the original. Requests with ?v=hero return status 400 with the body { "status": 400, "error": "unknown_variant", "message": "Unknown variant", "detail": "hero" }. Remove the parameter to get the original image, or pick another variant."
|
||||||
|
And the Preview is dimmed to 50 %, 4 / 3, and reads "No preview: unknown variant"
|
||||||
|
|
||||||
|
Scenario: A reload on window focus can trigger I5
|
||||||
|
Given the builder has "hero" selected and the list was loaded with "hero" enabled
|
||||||
|
When "hero" is disabled or deleted elsewhere and the window receives a focus event
|
||||||
|
Then GET /v1/image-variants is sent again and I5 is shown
|
||||||
|
|
||||||
|
Scenario: I6. Loading
|
||||||
|
Given GET /v1/image-variants has not answered
|
||||||
|
Then three skeleton blocks of 140, 200 and 120 px (--ui-bg-accented) fill a region with aria-busy "true"
|
||||||
|
And the "Request an image" snippet, the variants table, the URL builder and the Responses table are not drawn
|
||||||
|
And the intro paragraph is drawn
|
||||||
|
|
||||||
|
Scenario Outline: I7. Error loading
|
||||||
|
Given GET /v1/image-variants fails with <failure>
|
||||||
|
Then an error alert (role alert, circle-x icon) reads "Couldn't load image variants"
|
||||||
|
And its text reads "The snippets below still work. The variant list and the URL builder need a connection."
|
||||||
|
And a button "Try again" is shown
|
||||||
|
And the "Request an image" snippet is drawn with the placeholder <variant-name>
|
||||||
|
And no table, no URL builder and no Responses table are drawn
|
||||||
|
When the user activates "Try again"
|
||||||
|
Then GET /v1/image-variants is sent again
|
||||||
|
Examples:
|
||||||
|
| failure |
|
||||||
|
| status 500 |
|
||||||
|
| a network failure |
|
||||||
|
|
||||||
|
Scenario: A 403 on the list is handled as not an admin
|
||||||
|
Given the session role is "owner" but GET /v1/image-variants answers 403
|
||||||
|
Then I4 is shown
|
||||||
|
And a 401 is left to the global handler of features/api_client_global_error_handling.feature
|
||||||
|
|
||||||
|
Scenario: I8. Snippet copied
|
||||||
|
Given the sample variants and the HTML tab active
|
||||||
|
When the user activates "Copy" on the "Request an image" snippet
|
||||||
|
Then the HTML code is written to the clipboard
|
||||||
|
And the button reads "Copied" with icon check for 2 s, announced politely
|
||||||
|
And the URL builder's Copy button still reads "Copy"
|
||||||
|
|
||||||
|
Scenario: The URL builder
|
||||||
|
Given the sample variants
|
||||||
|
Then the Image field is a select showing "north-wall.jpg" and the Variant field is a select listing the enabled variants
|
||||||
|
When the user picks "square" in Variant
|
||||||
|
Then the URL snippet reads "https://cms.renew.example/media/north-wall.jpg?v=square"
|
||||||
|
And the Preview is a framed placeholder with aspect-ratio width / height of the variant, and 4 / 3 when the width or the height is null, shows the label "square · 600×600 · JPEG" and is announced with role img and the same aria-label
|
||||||
|
And the Preview is at most 240 px high and full width
|
||||||
|
And no image is requested from the server
|
||||||
|
|
||||||
|
Scenario: I9. URL builder copied
|
||||||
|
Given the URL builder shows "https://cms.renew.example/media/north-wall.jpg?v=thumb"
|
||||||
|
When the user activates "Copy" on the URL snippet
|
||||||
|
Then that exact URL is written to the clipboard
|
||||||
|
And the button reads "Copied" for 2 s, announced politely
|
||||||
|
And the "Request an image" snippet's button still reads "Copy"
|
||||||
|
|
||||||
|
Scenario: The Responses table
|
||||||
|
Given any state except Loading and Error loading
|
||||||
|
Then the table has the columns Request, Status and Response and these rows:
|
||||||
|
| request | status | response | body |
|
||||||
|
| /media/photo.png?v=thumb | 200 | The variant image. Generated on first request. | |
|
||||||
|
| /media/photo.png?v=unknown | 400 | Unknown variant | { "status": 400, "error": "unknown_variant", "message": "Unknown variant", "detail": "unknown" } |
|
||||||
|
| /media/photo.png?width=400 | 400 | Unsupported parameter | { "status": 400, "error": "unsupported_parameter", "message": "Unsupported parameter", "detail": "width" } |
|
||||||
|
| /media/missing.png?v=thumb | 404 | Not found | 404 page not found |
|
||||||
|
| /media/huge.png?v=thumb | 413 | Source image too large | The source image is too large to generate this variant. |
|
||||||
|
| /media/photo.png?v=thumb | 500 | Unable to read the file | Unable to read the file |
|
||||||
|
And the body of the 400 rows is application/json and monospace --ui-text-muted below the response text
|
||||||
|
And the 404 body is text/plain "404 page not found"
|
||||||
|
And the 413 and 500 bodies are text/plain
|
||||||
|
And the table has no 409 and no 422 row
|
||||||
|
And the 413 and 500 rows are added although the board lacks them, because the handler returns them, and this is logged for the design pass
|
||||||
|
|
||||||
|
Scenario: The error sample tab names its content type
|
||||||
|
Then the Errors section sample keeps its single tab "Error response · text/plain"
|
||||||
|
And the image JSON errors are covered only by the Responses table, where their bodies are application/json
|
||||||
|
And no snippet labelled text/plain shows an unknown_variant or unsupported_parameter body
|
||||||
|
|
||||||
|
Scenario: The page calls only the image variants route
|
||||||
|
When the user opens /integration as an owner or admin
|
||||||
|
Then GET /v1/image-variants is sent once on mount, plus once per "Try again" and once per window focus event
|
||||||
|
And no other /v1 call is made
|
||||||
|
And for any other role no /v1 call is made
|
||||||
|
|
||||||
|
Rule: The existing Integration surfaces use CodeSnippet
|
||||||
|
|
||||||
|
Scenario: Authentication example
|
||||||
|
Then the "API key" card shows one CodeSnippet with tabs curl and fetch for GET /v1/auth/me, curl active, using {origin}
|
||||||
|
And there is no outer UTabs wrapper and no label "Shell" or "JavaScript"
|
||||||
|
|
||||||
|
Scenario: Endpoint card examples
|
||||||
|
When the user expands a card
|
||||||
|
Then one CodeSnippet holds the tabs fetch, curl and Response, fetch active
|
||||||
|
And the tab list uses the underline style, not the UTabs link style
|
||||||
|
And the Copy button copies the active tab and its accessible name is "Copy code"
|
||||||
|
And the "Errors" list below it is unchanged
|
||||||
|
|
||||||
|
Scenario: Base URL and error sample
|
||||||
|
Then "Base URL" is a label above a CodeSnippet whose only tab is "Base URL" and whose code is {origin}
|
||||||
|
And the Errors sample is a CodeSnippet reading "HTTP/1.1 403 Forbidden", "Content-Type: text/plain", a blank line, "This action needs a real session."
|
||||||
|
|
||||||
|
Scenario: Copy buttons of the Integration page are independent
|
||||||
|
When the user copies the Base URL
|
||||||
|
Then only the Base URL button reads "Copied"
|
||||||
@@ -0,0 +1,114 @@
|
|||||||
|
# QA: Integration images and variants, and CodeSnippet as the only code block
|
||||||
|
|
||||||
|
SPA only. No Go test, no live server, no SMTP, no real SQLite.
|
||||||
|
|
||||||
|
## Automated (Vitest + Vue Test Utils, `task test:web`)
|
||||||
|
|
||||||
|
Common setup: mount IntegrationPage inside DashboardShell at /integration with a test router, a resolved
|
||||||
|
verified session whose role is set per case, and `window.location.origin` stubbed to
|
||||||
|
`https://cms.renew.example`. Mock `/v1` through the same `useApi` seam as `variantsTestKit.ts`.
|
||||||
|
Stub `navigator.clipboard.writeText` per case and use fake timers. A spec fails on any `/v1` call
|
||||||
|
that is not listed for the case.
|
||||||
|
|
||||||
|
Variants fixture: the twelve board variants of the feature plus "print" (enabled false), in the board order, with
|
||||||
|
full item fields (fit, quality, generate_on_upload, generated_files, cache_size).
|
||||||
|
|
||||||
|
CodeSnippet component spec (no router, no `/v1`):
|
||||||
|
1. Three tabs: header with tablist aria-label "Language", the first tab selected with an underline class,
|
||||||
|
the Copy button named "Copy code".
|
||||||
|
2. A click on a tab switches the pre content. The Copy button writes the active tab's code.
|
||||||
|
3. One tab renders a muted label, not a role tab.
|
||||||
|
4. Copy: clipboard called with the code, "Copied" and icon check inside an aria-live "polite" element,
|
||||||
|
back to "Copy" after 2000 ms (advance 1999 and 2000). Two instances copy independently.
|
||||||
|
5. The pre has tabindex "0" and no syntax-highlight markup.
|
||||||
|
|
||||||
|
Integration images specs, one per design state, each with the mocked `/v1` call:
|
||||||
|
1. **Many variants** (owner): GET /v1/image-variants -> 200 with the fixture. Assert the section order (Media
|
||||||
|
group, Images and variants, Session only, Errors), anchor "images", the section index entry, "12 enabled variants",
|
||||||
|
12 table rows with "print" absent, the 264 px max-height class on the table body, the disabled note, exact curl,
|
||||||
|
HTML and JavaScript strings, HTML tab active, the Responses rows and bodies.
|
||||||
|
2. **One variant**: 200 with only "thumb" enabled. "1 enabled variant", one row, no max-height limit, the three
|
||||||
|
snippet slots all use "thumb", no disabled note.
|
||||||
|
3. **No variants, admin**: role admin, 200 with {"items": []}. Empty block, text, the "Go to image variants" link with
|
||||||
|
href /settings/media/variants, placeholder <variant-name> in the snippets, no table, no builder, Responses present.
|
||||||
|
Repeat with a fixture containing only disabled variants.
|
||||||
|
4. **No variants, not an admin**: role "member" (or no role). Assert no GET /v1/image-variants call on mount or on a
|
||||||
|
window focus event, the non-admin text, no link and no button. Add: role owner with a 403 answer renders the same state.
|
||||||
|
5. **Variant removed**: load the fixture, select "hero", make the mock return a list without "hero", then dispatch
|
||||||
|
`window.dispatchEvent(new Event('focus'))`. Assert a second GET, "hero (removed)", the warning alert title and text
|
||||||
|
with the exact 400 body, the URL snippet ends with ?v=hero, the preview label "No preview: unknown variant", 4 / 3
|
||||||
|
aspect and 50 % opacity. Repeat with the reload triggered by "Try again" after a failed first load.
|
||||||
|
6. **Loading**: GET /v1/image-variants pending. Assert three skeletons inside an aria-busy region, and no snippet,
|
||||||
|
no table, no builder, no Responses table.
|
||||||
|
7. **Error loading**: 500, then a rejected fetch. Assert the alert copy, the snippet present with
|
||||||
|
<variant-name>, no table and no builder, no Responses table. Click "Try again" and assert a second call
|
||||||
|
and the success state replaces the alert.
|
||||||
|
8. **Snippet copied**: click Copy on the "Request an image" snippet. Clipboard receives the active (HTML) code, button
|
||||||
|
reads "Copied" in an aria-live polite region, reverts after 2 s, and the builder's button is unaffected.
|
||||||
|
9. **URL builder copied**: the clipboard receives "https://cms.renew.example/media/north-wall.jpg?v=thumb".
|
||||||
|
Pick "square" first and assert the URL, preview label "square · 600×600 · JPEG" and the 600 / 600 aspect ratio.
|
||||||
|
|
||||||
|
Behaviour specs:
|
||||||
|
10. **Reload triggers**: mount sends one GET; each focus event sends one more; "Try again" sends one more; a reload with
|
||||||
|
the selected variant still enabled keeps the active tab and the selection. A non-admin sends none on any trigger.
|
||||||
|
11. **Responses table**: the two 400 bodies are the exact JSON strings of the feature; the 404 body is
|
||||||
|
"404 page not found"; the 413 body is "The source image is too large to generate this variant." and the 500 body is
|
||||||
|
"Unable to read the file"; no 409 or 422 row.
|
||||||
|
12. **Error sample label**: the Errors sample tab reads "Error response · text/plain" and no snippet in the images
|
||||||
|
section carries a text/plain label.
|
||||||
|
|
||||||
|
Migration specs (update or replace the existing assertions of `IntegrationView.spec.ts`, the EndpointCard spec
|
||||||
|
and the ApiKeys specs):
|
||||||
|
13. Base URL is a CodeSnippet with the single tab "Base URL", origin in the code, Copy -> "Copied" -> "Copy" after 2 s.
|
||||||
|
14. Authentication example: tabs curl and fetch for GET /v1/auth/me, no "Shell" or "JavaScript" label.
|
||||||
|
15. Expanded EndpointCard (POST /v1/article/): tabs fetch, curl, Response in one CodeSnippet, fetch active,
|
||||||
|
Copy copies the active tab, only that button reads "Copied". The Errors list is unchanged.
|
||||||
|
16. Errors sample is a CodeSnippet containing the four sample lines.
|
||||||
|
17. ApiKeyReveal: the key is in a CodeSnippet with the single tab "API key", the Copy button is focused when the
|
||||||
|
dialog opens, and Copy writes the full key and reads "Copied" for 2 s.
|
||||||
|
18. Source guard: nothing imports `@/components/CodeBlock.vue` (EndpointCard.vue and IntegrationView.vue included),
|
||||||
|
the file is deleted, and `CodeText.vue` still exists.
|
||||||
|
19. The Integration page makes the calls listed in the feature for owner and admin, and none for other roles. The old
|
||||||
|
"page stays static" assertions in `IntegrationView.spec.ts` are changed accordingly.
|
||||||
|
20. Every new string has a French entry (the existing i18n completeness spec must pass).
|
||||||
|
|
||||||
|
## Visual (`task visual:check -- integration`, desktop and mobile, light and dark)
|
||||||
|
|
||||||
|
Every capture must be within 10 %. Group "Integration: images" (board `IntegrationImages.dc.html` through AppFrame),
|
||||||
|
setups in `web/visual/states.ts`, with the board's sample data: origin `https://cms.renew.example`, image
|
||||||
|
`north-wall.jpg`, the twelve variants of the feature (plus disabled "print" so the note shows in Many), role admin
|
||||||
|
unless stated.
|
||||||
|
|
||||||
|
| State | Mock |
|
||||||
|
|---|---|
|
||||||
|
| Many variants | GET /v1/image-variants -> 12 enabled + "print" disabled, HTML tab active, builder on "thumb" |
|
||||||
|
| One variant | -> only "thumb" |
|
||||||
|
| No variants, admin | -> {"items": []}, role admin |
|
||||||
|
| No variants, not an admin | role without owner/admin, no call |
|
||||||
|
| Variant removed | builder on "hero", list without "hero" after the reload (first 5 as the board) |
|
||||||
|
| Loading | request never resolves |
|
||||||
|
| Error loading | status 500 |
|
||||||
|
| Snippet copied | Many with the snippet in the Copied state (clipboard stubbed) |
|
||||||
|
| URL builder copied | Many with the URL snippet in the Copied state |
|
||||||
|
|
||||||
|
Approved visual exceptions (user, own turn), each with `approvedBy` "Florian Sylvain":
|
||||||
|
- I2 One variant, desktop light, `maxPercent` just above the measured value (about 16 %), reason "board draws the striped preview offset by 32 px".
|
||||||
|
- I8 Snippet copied, desktop light, `maxPercent` just above the measured value (about 12 %), same reason.
|
||||||
|
- Errors, mobile, `maxPercent` just above the measured value (about 18.5 %), reason "the board changed; already 17.33 % at HEAD". Listed as a design-pass item.
|
||||||
|
- The `integration-api-keys` mobile failures (14 to 24 %) are NOT excepted. They predate this slice (floating inset dialog versus the board's flush bottom sheet, an overlay-pattern slice). They stay red and documented, and this slice's gate is scoped to the Integration screen.
|
||||||
|
|
||||||
|
Also re-run the existing groups affected by the migration and keep them within 10 %: Integration ("1. Default",
|
||||||
|
"2. Group scrolled, one card expanded", "3a. Copied: base URL", "3b. Copied: CodeSnippet", "4. Authentication",
|
||||||
|
"6. Errors") and API keys ("One-time reveal", "One-time reveal: copied"). The board names stay as the design gives
|
||||||
|
them. Existing pre-approved exceptions stay as recorded. Skipped: none are clock-sensitive.
|
||||||
|
|
||||||
|
## Manual checks (not coverable by screenshots)
|
||||||
|
- Keyboard: tab order inside a CodeSnippet is tabs, then Copy, then the `pre` (tabindex 0). Arrow keys move
|
||||||
|
between tabs. Enter and Space activate Copy. The focus ring is 2 px primary.
|
||||||
|
- A screen reader announces "Copied" politely after Copy, and not again on "Copy" returning.
|
||||||
|
- Hover and motion: Copy and tabs hover states, no motion on copy other than the label swap.
|
||||||
|
- Find-in-page and the index entry "Images and variants" scroll to `#images`; opening `/integration#images` lands on the section.
|
||||||
|
- The Variants table scrolls inside its 264 px body with the mouse wheel and keyboard, and the header stays visible.
|
||||||
|
- Real clipboard in a browser (secure context) copies the exact snippet text.
|
||||||
|
- Against a running server: `?v=<disabled>`, `?v=<unknown>` and `?width=400` answer 400 application/json with the
|
||||||
|
documented bodies, and a missing image answers 404 text/plain "404 page not found".
|
||||||
@@ -20,8 +20,12 @@ Feature: Media page, part 1: browse and manage
|
|||||||
And useMedia is a composable over useApi. It exposes the list state (items, counts, loading,
|
And useMedia is a composable over useApi. It exposes the list state (items, counts, loading,
|
||||||
error), the request functions for list, usage, rename and delete, and the copy helper, and
|
error), the request functions for list, usage, rename and delete, and the copy helper, and
|
||||||
it maps ApiError and NetworkError to the states below
|
it maps ApiError and NetworkError to the states below
|
||||||
And MediaPage calls GET /v1/media/ with the query built from the URL, always with limit=100,
|
And MediaPage calls GET /v1/media/ with the query built from the URL, always with an explicit
|
||||||
and every request carries the jwt cookie through useApi
|
page and size (page=1&size=25 by default, or the stored size), and every request carries
|
||||||
|
the jwt cookie through useApi
|
||||||
|
And this slice is amended by features/media_pagination_api.feature and
|
||||||
|
features/media_pagination_screen.feature: limit=100 and next_cursor are gone, the body is
|
||||||
|
{ items, total, page, size, counts }, and the list is paginated
|
||||||
And search, tab, sort and view live in the URL query string so the view can be linked and
|
And search, tab, sort and view live in the URL query string so the view can be linked and
|
||||||
survives a reload: ?q= (search text), ?filter= ("unused" or "duplicates"; absent means
|
survives a reload: ?q= (search text), ?filter= ("unused" or "duplicates"; absent means
|
||||||
All), ?sort= ("oldest", "name" or "largest"; absent means Newest), ?view= ("list"; absent
|
All), ?sort= ("oldest", "name" or "largest"; absent means Newest), ?view= ("list"; absent
|
||||||
@@ -90,10 +94,10 @@ Feature: Media page, part 1: browse and manage
|
|||||||
| 10 | bathroom-tiles.png | 860 KB | 1800 × 1200 | PNG | 0 | Marta Alves | 4 Aug 2026 | alpha |
|
| 10 | bathroom-tiles.png | 860 KB | 1800 × 1200 | PNG | 0 | Marta Alves | 4 Aug 2026 | alpha |
|
||||||
| 11 | lime-plaster.jpg | 2.1 MB | 3200 × 2133 | JPEG | 2 | Inès Duarte | 19 Jul 2026 | |
|
| 11 | lime-plaster.jpg | 2.1 MB | 3200 × 2133 | JPEG | 2 | Inès Duarte | 19 Jul 2026 | |
|
||||||
| 12 | floorboards.jpg | 2.4 MB | 3600 × 2400 | JPEG | 4 | Inès Duarte | 14 Jun 2026 | duplicate |
|
| 12 | floorboards.jpg | 2.4 MB | 3600 × 2400 | JPEG | 4 | Inès Duarte | 14 Jun 2026 | duplicate |
|
||||||
with counts { all: 12, unused: 2, duplicates: 2 }, and next_cursor null
|
with counts { all: 12, unused: 2, duplicates: 2 }, total 12, page 1, size 25
|
||||||
|
|
||||||
Scenario: Default, many images
|
Scenario: Default, many images
|
||||||
Given GET /v1/media/?filter=all&sort=newest&limit=100 resolves 200 with the 12-image fixture
|
Given GET /v1/media/?filter=all&sort=newest&page=1&size=25 resolves 200 with the 12-image fixture
|
||||||
When the user navigates to /media
|
When the user navigates to /media
|
||||||
Then the breadcrumb reads "Media" (mobile title "Media")
|
Then the breadcrumb reads "Media" (mobile title "Media")
|
||||||
And the tabs read "All 12", "Unused 2", "Duplicates 2", with "All" selected, and the
|
And the tabs read "All 12", "Unused 2", "Duplicates 2", with "All" selected, and the
|
||||||
@@ -144,7 +148,7 @@ Feature: Media page, part 1: browse and manage
|
|||||||
Scenario Outline: The query string is the source of truth for search, tab, sort and view
|
Scenario Outline: The query string is the source of truth for search, tab, sort and view
|
||||||
Given GET /v1/media/ is mocked
|
Given GET /v1/media/ is mocked
|
||||||
When the user opens /media<url>
|
When the user opens /media<url>
|
||||||
Then GET /v1/media/ is sent with "<request>" and limit=100
|
Then GET /v1/media/ is sent with "<request>" and page=1&size=25
|
||||||
And the control shows "<control>"
|
And the control shows "<control>"
|
||||||
|
|
||||||
Examples:
|
Examples:
|
||||||
@@ -161,7 +165,7 @@ Feature: Media page, part 1: browse and manage
|
|||||||
Scenario: Changing a control writes the query string and reloads the list
|
Scenario: Changing a control writes the query string and reloads the list
|
||||||
Given the Default state has loaded
|
Given the Default state has loaded
|
||||||
When the user types "wall" in the search field
|
When the user types "wall" in the search field
|
||||||
Then after a 120 ms debounce the URL gains ?q=wall and GET /v1/media/?q=wall&filter=all&sort=newest&limit=100 is sent
|
Then after a 120 ms debounce the URL gains ?q=wall and GET /v1/media/?q=wall&filter=all&sort=newest&page=1&size=25 is sent
|
||||||
When the user selects the "Unused" tab
|
When the user selects the "Unused" tab
|
||||||
Then the URL reads ?q=wall&filter=unused and the list is requested again
|
Then the URL reads ?q=wall&filter=unused and the list is requested again
|
||||||
When the user picks "Largest" in the sort menu
|
When the user picks "Largest" in the sort menu
|
||||||
@@ -187,7 +191,7 @@ Feature: Media page, part 1: browse and manage
|
|||||||
|
|
||||||
Scenario: No results, search and filter
|
Scenario: No results, search and filter
|
||||||
Given the Default state has loaded
|
Given the Default state has loaded
|
||||||
When the user selects "Unused" and types "wall" and GET /v1/media/?q=wall&filter=unused&sort=newest&limit=100 resolves 200 with zero items
|
When the user selects "Unused" and types "wall" and GET /v1/media/?q=wall&filter=unused&sort=newest&page=1&size=25 resolves 200 with zero items
|
||||||
Then a panel replaces the images with the search icon, title `No images match "wall"`, text "Nothing matches in Unused. Check the spelling, or clear the filters." and an outline "Clear filters" button
|
Then a panel replaces the images with the search icon, title `No images match "wall"`, text "Nothing matches in Unused. Check the spelling, or clear the filters." and an outline "Clear filters" button
|
||||||
When the user activates "Clear filters"
|
When the user activates "Clear filters"
|
||||||
Then the search field is emptied, the tab returns to "All", ?q and ?filter leave the URL, and the Default cards reappear
|
Then the search field is emptied, the tab returns to "All", ?q and ?filter leave the URL, and the Default cards reappear
|
||||||
|
|||||||
@@ -147,5 +147,6 @@ Manual checks screenshots cannot cover:
|
|||||||
- **Toast placement and stacking** on a live app.
|
- **Toast placement and stacking** on a live app.
|
||||||
- **Counts after a delete** against a live server: the background refresh gives the true Unused
|
- **Counts after a delete** against a live server: the background refresh gives the true Unused
|
||||||
and Duplicates counts.
|
and Duplicates counts.
|
||||||
- **A library above 100 images**: B1 requests `limit=100` and ignores `next_cursor`, so only the
|
- **A library above 25 images**: amended by `features/media_pagination_screen.feature`. B1 used to
|
||||||
first 100 show.
|
request `limit=100` and ignore `next_cursor`; the page now requests `page=1&size=25` (or the stored
|
||||||
|
size) and shows a paginator, so every image is reachable.
|
||||||
@@ -21,7 +21,7 @@ Package: `test` (black-box). New file `test/media_library_http_test.go`. Fake ty
|
|||||||
|
|
||||||
## HTTP checks
|
## HTTP checks
|
||||||
10. Auth table: each method+path from the outline with no cookie -> 401, stale cookie -> 401 with `apperr.UnauthorizedErrorMessage`, unverified cookie -> 403 with `apperr.VerificationRequiredErrorMessage`. Assert no fake method beyond the middleware's user lookup was called.
|
10. Auth table: each method+path from the outline with no cookie -> 401, stale cookie -> 401 with `apperr.UnauthorizedErrorMessage`, unverified cookie -> 403 with `apperr.VerificationRequiredErrorMessage`. Assert no fake method beyond the middleware's user lookup was called.
|
||||||
11. List: decode `{items, next_cursor, counts}`. Assert each row of the sort, filter, `q` and `hash` tables, the combined query, the paging walk (limit 2 across three pages ending in `next_cursor == null`), the empty library (`items` is `[]` in the raw JSON, not `null`), SVG `width`/`height` are JSON `null` (assert on the raw body), and `counts` is unchanged by `q`/`filter`. Assert every 400 query row, body equals `apperr.MediaQueryErrorMessage + "\n"`.
|
11. List (amended by `features/media_pagination_api.feature`): decode `{items, total, page, size, counts}`, with no `next_cursor`. Assert each row of the sort, filter, `q` and `hash` tables, the combined query, the paging walk (`size=5` across three pages with `page=1..3`, each reporting the same `total`), the empty library (`items` is `[]` in the raw JSON, not `null`), SVG `width`/`height` are JSON `null` (assert on the raw body), and `counts` is unchanged by `q`/`filter`. Assert every 400 query row, body equals `apperr.MediaQueryErrorMessage + "\n"`.
|
||||||
12. Upload: for each allowed type assert 201, the item fields, `sha256` equals the test's own hash, `uploaded_by`, the url regex, and one repo entry with `UploadedByID == 1`. Upload identical bytes twice: both 201, second has `duplicate: true`, list `counts.duplicates == 1`. Assert filename rules (no extension gets `.png`, path stripped). Assert 413/415/400 statuses and bodies, that `Create` is never called on rejection, boundary 10485760 vs 10485761, a missing `file` part -> 400, and an armed `Create` failure -> 500 `"Internal server error\n"`.
|
12. Upload: for each allowed type assert 201, the item fields, `sha256` equals the test's own hash, `uploaded_by`, the url regex, and one repo entry with `UploadedByID == 1`. Upload identical bytes twice: both 201, second has `duplicate: true`, list `counts.duplicates == 1`. Assert filename rules (no extension gets `.png`, path stripped). Assert 413/415/400 statuses and bodies, that `Create` is never called on rejection, boundary 10485760 vs 10485761, a missing `file` part -> 400, and an armed `Create` failure -> 500 `"Internal server error\n"`.
|
||||||
13. Rename: assert 200 with the new filename, the same `url`, the article body unchanged, and every invalid row -> 400 with `"Enter a filename.\n"` for the filename rows; 404 for 9999; 400 with `apperr.IdUint32ErrorMessage` for `abc`. Assert the repository filename is unchanged after each 400.
|
13. Rename: assert 200 with the new filename, the same `url`, the article body unchanged, and every invalid row -> 400 with `"Enter a filename.\n"` for the filename rows; 404 for 9999; 400 with `apperr.IdUint32ErrorMessage` for `abc`. Assert the repository filename is unchanged after each 400.
|
||||||
14. Delete: in-use image -> 204 with an empty body, article bodies byte-identical, `deleteCalls == [1]`; 404, 400, 500 rows. The "file already gone" case is a persistence behaviour and is a manual item.
|
14. Delete: in-use image -> 204 with an empty body, article bodies byte-identical, `deleteCalls == [1]`; 404, 400, 500 rows. The "file already gone" case is a persistence behaviour and is a manual item.
|
||||||
|
|||||||
@@ -0,0 +1,128 @@
|
|||||||
|
Feature: Media page remembers the chosen page size
|
||||||
|
|
||||||
|
As a verified RenewCMS user
|
||||||
|
I want the page size I choose on the Media page to be remembered
|
||||||
|
So that I do not have to pick it again each time I come back or refresh
|
||||||
|
|
||||||
|
Background:
|
||||||
|
Given this slice follows features/articles_page_size_memory.feature and extends features/media_pagination_screen.feature; the URL keeps ?size= as in that spec and no visual or API change is made
|
||||||
|
And the size options stay "5 per page", "25 per page", "50 per page", "100 per page" and the default stays 25
|
||||||
|
And the chosen size is stored in localStorage under the key renewcms-page-size-media as the bare number (for example 5), one key per paginated list; Articles uses renewcms-page-size-articles and Activity renewcms-page-size-activity, and the three do not affect each other
|
||||||
|
And a MEDIA_PAGE_SIZE_KEY constant joins ARTICLES_PAGE_SIZE_KEY and ACTIVITY_PAGE_SIZE_KEY in web/src/lib/pageSizeMemory.ts and the existing readStoredPageSize, storePageSize and resolvePageSize helpers are reused
|
||||||
|
And only choosing a size in the page-size select writes the stored value; loading a URL never writes it
|
||||||
|
And an explicit valid ?size= in the URL is authoritative for that load and does not change the stored value
|
||||||
|
And an invalid ?size= in the URL falls back to 25, never to the stored value, and is replaced in the URL (features/media_pagination_screen.feature)
|
||||||
|
And a stored value that is not 5, 25, 50 or 100 is treated as absent
|
||||||
|
And localStorage that is unavailable or throws on read or write never raises an error or breaks the page: reads act as absent and writes are ignored
|
||||||
|
And logout does not clear the stored size
|
||||||
|
And a size change still resets page to 1 and drops page from the URL
|
||||||
|
And the Duplicates tab ignores the stored size (it always loads with size=100) and never writes it
|
||||||
|
And the picker and hash lookups ignore the stored size (fixed size=25 and size=100)
|
||||||
|
And the requests are GET /v1/media/?filter=F&sort=S&page=P&size=Z as in features/media_pagination_api.feature
|
||||||
|
|
||||||
|
Scenario Outline: Choosing a size stores it
|
||||||
|
Given nothing is stored and the user is on /media
|
||||||
|
When the user chooses "<label>" in the page-size select
|
||||||
|
Then localStorage renewcms-page-size-media is "<stored>"
|
||||||
|
And on success the URL is <url>
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| label | stored | url |
|
||||||
|
| 5 per page | 5 | /media?size=5 |
|
||||||
|
| 25 per page | 25 | /media |
|
||||||
|
| 50 per page | 50 | /media?size=50 |
|
||||||
|
| 100 per page | 100 | /media?size=100 |
|
||||||
|
|
||||||
|
Scenario: The stored size is restored when the page is opened without a size
|
||||||
|
Given localStorage renewcms-page-size-media is "5"
|
||||||
|
When the user navigates to /media
|
||||||
|
Then GET ...&page=1&size=5 is sent
|
||||||
|
And the page-size select reads "5 per page"
|
||||||
|
And on success the URL is replaced (no history entry) by /media?size=5
|
||||||
|
|
||||||
|
Scenario: The size survives leaving the page and coming back
|
||||||
|
Given the user chose "5 per page" on /media
|
||||||
|
When the user navigates to /, then back to /media
|
||||||
|
Then GET ...&size=5 is sent and the select reads "5 per page"
|
||||||
|
|
||||||
|
Scenario: The size survives a full page refresh
|
||||||
|
Given the user chose "5 per page" on /media
|
||||||
|
When the page is reloaded on /media?size=5, or on /media with the URL typed in without a size
|
||||||
|
Then GET ...&size=5 is sent and the select reads "5 per page"
|
||||||
|
|
||||||
|
Scenario: The stored size is kept across paging, search, tabs, sort and view
|
||||||
|
Given localStorage renewcms-page-size-media is "50" and the user is on /media?size=50
|
||||||
|
When the user activates Next, switches to the "Unused" tab, sorts by "Largest", switches to list view or searches "wall"
|
||||||
|
Then every request carries size=50 and the stored value stays "50"
|
||||||
|
|
||||||
|
Scenario: Changing the size again replaces the stored one
|
||||||
|
Given localStorage renewcms-page-size-media is "5"
|
||||||
|
When the user chooses "100 per page"
|
||||||
|
Then localStorage renewcms-page-size-media is "100"
|
||||||
|
And the next visit to /media without a size sends size=100
|
||||||
|
|
||||||
|
Scenario: Returning to 25 is remembered too
|
||||||
|
Given localStorage renewcms-page-size-media is "5"
|
||||||
|
When the user chooses "25 per page"
|
||||||
|
Then localStorage renewcms-page-size-media is "25"
|
||||||
|
And the next visit to /media sends size=25 and the URL stays /media
|
||||||
|
|
||||||
|
Scenario: An explicit size in the URL wins and is not stored
|
||||||
|
Given localStorage renewcms-page-size-media is "5"
|
||||||
|
When the user navigates to /media?size=100
|
||||||
|
Then GET ...&size=100 is sent and the select reads "100 per page"
|
||||||
|
And localStorage renewcms-page-size-media is still "5"
|
||||||
|
And a later visit to /media sends size=5
|
||||||
|
|
||||||
|
Scenario: An explicit page with no size uses the stored size
|
||||||
|
Given localStorage renewcms-page-size-media is "5"
|
||||||
|
When the user navigates to /media?page=3
|
||||||
|
Then GET ...&page=3&size=5 is sent and on success the URL is replaced by /media?page=3&size=5
|
||||||
|
|
||||||
|
Scenario Outline: An invalid stored value falls back to 25
|
||||||
|
Given localStorage renewcms-page-size-media is "<stored>"
|
||||||
|
When the user navigates to /media
|
||||||
|
Then GET ...&page=1&size=25 is sent, the select reads "25 per page" and the URL is /media
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| stored |
|
||||||
|
| 10 |
|
||||||
|
| abc |
|
||||||
|
| 0 |
|
||||||
|
| -5 |
|
||||||
|
| 25.5 |
|
||||||
|
| |
|
||||||
|
|
||||||
|
Scenario: An invalid size in the URL ignores the stored one
|
||||||
|
Given localStorage renewcms-page-size-media is "5"
|
||||||
|
When the user navigates to /media?size=10
|
||||||
|
Then GET ... is sent with size=25 and the URL is replaced by /media
|
||||||
|
And localStorage renewcms-page-size-media is still "5"
|
||||||
|
|
||||||
|
Scenario Outline: Unavailable storage never breaks the page
|
||||||
|
Given localStorage <failure>
|
||||||
|
When the user navigates to /media
|
||||||
|
Then GET ...&page=1&size=25 is sent, the page renders and no error is shown
|
||||||
|
When the user chooses "50 per page"
|
||||||
|
Then GET ...&page=1&size=50 is sent and the URL is /media?size=50
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| failure |
|
||||||
|
| throws on getItem |
|
||||||
|
| throws on setItem (quota) |
|
||||||
|
| is undefined |
|
||||||
|
|
||||||
|
Scenario: Logging out keeps the stored size
|
||||||
|
Given localStorage renewcms-page-size-media is "5"
|
||||||
|
When the user logs out and logs in again and opens /media
|
||||||
|
Then GET ...&size=5 is sent
|
||||||
|
|
||||||
|
Scenario: The three lists keep separate sizes
|
||||||
|
Given localStorage has renewcms-page-size-articles "50", renewcms-page-size-activity "100" and renewcms-page-size-media "5"
|
||||||
|
When the user opens /article, /activity and /media in turn without a size
|
||||||
|
Then they send size=50, size=100 and size=5 respectively
|
||||||
|
|
||||||
|
Scenario: The Duplicates tab ignores the stored size
|
||||||
|
Given localStorage renewcms-page-size-media is "5"
|
||||||
|
When the user opens /media?filter=duplicates
|
||||||
|
Then the requests carry size=100, the stored value stays "5", and returning to the "All" tab sends size=5
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
# QA: Media page size memory (SPA)
|
||||||
|
|
||||||
|
## Automated (Vitest + Vue Test Utils, `task test:web`)
|
||||||
|
|
||||||
|
Add `web/src/views/__tests__/MediaPageSizeMemory.spec.ts`, mirroring `ArticlesPageSizeMemory.spec.ts` and `ActivityPageSizeMemory.spec.ts`: stub `localStorage` per test (a `Storage` fake, plus variants whose `getItem` or `setItem` throws, and `undefined`), use the `/v1/media/` mock of `mediaTestKit.ts` that honours `page` and `size`, and a real router. Extend `web/src/lib/__tests__/pageSizeMemory.spec.ts` for `MEDIA_PAGE_SIZE_KEY`.
|
||||||
|
|
||||||
|
1. Choose a size table (5, 25, 50, 100) with nothing stored: stored value per the table and URLs `/media?size=5`, `/media`, `/media?size=50`, `/media?size=100`.
|
||||||
|
2. Stored 5, open `/media`: request `size=5`, select reads "5 per page", URL replaced (not pushed) by `/media?size=5`.
|
||||||
|
3. Leave and come back (navigate to `/` then `/media`): `size=5`.
|
||||||
|
4. Reload on `/media?size=5` and on `/media` with a fresh mount: `size=5`.
|
||||||
|
5. Stored 50: Next, "Unused" tab, "Largest" sort, list view and search "wall" each carry `size=50`; the stored value stays "50".
|
||||||
|
6. Choose 100 after 5: stored "100", next visit `size=100`. Choose 25 after 5: stored "25", URL stays `/media`.
|
||||||
|
7. Explicit `?size=100` with stored 5: request `size=100`, stored still "5", later visit `size=5`.
|
||||||
|
8. `?page=3` with stored 5: request `page=3&size=5`, URL replaced by `/media?page=3&size=5`.
|
||||||
|
9. Invalid stored table (`10`, `abc`, `0`, `-5`, `25.5`, empty): request `size=25`, URL `/media`.
|
||||||
|
10. Invalid URL `?size=10` with stored 5: request `size=25`, URL `/media`, stored still "5".
|
||||||
|
11. Unavailable storage table (throws on getItem, throws on setItem, undefined): page renders, no error, `size=25`, then choosing 50 sends `size=50` and URL `/media?size=50`.
|
||||||
|
12. Logout and login keeps the key (clear the auth store only; storage untouched), then `/media` sends `size=5`.
|
||||||
|
13. Separate keys: articles 50, activity 100, media 5 -> the three views send 50, 100 and 5.
|
||||||
|
14. Duplicates tab: stored 5 -> requests carry `size=100`, stored unchanged, returning to All sends `size=5`.
|
||||||
|
15. Unit test of the lib: `readStoredPageSize`, `storePageSize` and `resolvePageSize` with the media key and the valid sizes 5/25/50/100.
|
||||||
|
|
||||||
|
No Visual part: no visual or design change.
|
||||||
|
|
||||||
|
## Manual verification
|
||||||
|
|
||||||
|
- In a real browser (`task dev`): choose "5 per page", refresh, close and reopen the tab, confirm the select and the URL; in DevTools confirm only `renewcms-page-size-media` changed.
|
||||||
|
- Block storage (private mode or disabled site data) and confirm the page still works.
|
||||||
@@ -0,0 +1,148 @@
|
|||||||
|
Feature: Paginated media listing
|
||||||
|
|
||||||
|
As an API consumer, the RenewCMS media page or the editor picker
|
||||||
|
I want GET /v1/media/ to answer one page of images with the total and the library-wide counts
|
||||||
|
So that large libraries load quickly and every consumer pages the same way
|
||||||
|
|
||||||
|
Background:
|
||||||
|
Given GET /v1/media/ is mounted inside the jwtauth.Verifier + Authenticator group of api/router.go, unchanged
|
||||||
|
And BREAKING CHANGE: the body is {"items": [...], "total": N, "page": P, "size": S, "counts": {"all": A, "unused": U, "duplicates": D}} in snake_case; next_cursor is removed and no X-Total-Count header is sent
|
||||||
|
And each item is the existing media item (id, filename, url, size, content_type, width, height, sha256, uploaded_by, created_at, used_in, duplicate, variant_count, variant_size) and items is [] rather than null
|
||||||
|
And paging follows the Activity and Articles convention: page is an integer >= 1 (default 1), size is one of 5, 25, 50, 100 (default 25)
|
||||||
|
And q, hash, filter (all, unused, duplicates), sort (newest, oldest, name, largest, total_size) and variants (with, without) keep their current meaning and validation; the default order is newest
|
||||||
|
And total is the number of images matching q, hash, filter and variants, before paging; page and size echo the values applied
|
||||||
|
And counts stays library-wide: it ignores q, hash, filter, variants and paging
|
||||||
|
And ordering is applied to the whole matching list before slicing, with id as the final tie-break, so pages never overlap or skip (newest and total_size are made deterministic; oldest, name and largest already tie on id)
|
||||||
|
And a page beyond the last answers 200 with items [] and the real total
|
||||||
|
And any invalid page, size, filter, sort, variants or hash answers 400 with the plain-text body "The media query is invalid." (apperr.MediaQueryErrorMessage); page and size are validated with validate tags through validator.Validate.Struct
|
||||||
|
And cursor and limit are no longer parameters: they are ignored, never an error, and have no effect on paging
|
||||||
|
And ListMediaUseCase reaches data only through domain interfaces; the domain ListQuery carries Page and Size instead of Cursor and Limit; the handler never touches a repository
|
||||||
|
And the SPA sends explicit page and size on every list call
|
||||||
|
|
||||||
|
Scenario: A bare request answers the envelope with the defaults
|
||||||
|
Given the library holds 30 images
|
||||||
|
When a verified client sends GET /v1/media/
|
||||||
|
Then the status is 200
|
||||||
|
And the body has page 1, size 25, total 30, 25 items and counts {"all": 30, "unused": U, "duplicates": D}
|
||||||
|
And the body has no next_cursor key
|
||||||
|
|
||||||
|
Scenario Outline: Defaults when only one parameter is given
|
||||||
|
Given the library holds 60 images
|
||||||
|
When a verified client sends GET /v1/media/?<query>
|
||||||
|
Then the body has page <page>, size <size>, total 60 and <count> items
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| query | page | size | count |
|
||||||
|
| page=2 | 2 | 25 | 25 |
|
||||||
|
| page=3 | 3 | 25 | 10 |
|
||||||
|
| size=5 | 1 | 5 | 5 |
|
||||||
|
| size=50 | 1 | 50 | 50 |
|
||||||
|
| size=100 | 1 | 100 | 60 |
|
||||||
|
|
||||||
|
Scenario: Pages partition the list with no overlap
|
||||||
|
Given the library holds 12 images
|
||||||
|
When a client requests ?page=1&size=5, ?page=2&size=5 and ?page=3&size=5
|
||||||
|
Then the pages hold 5, 5 and 2 items, total is 12 on each, and no id repeats
|
||||||
|
|
||||||
|
Scenario: Newest first with the id tie-break
|
||||||
|
Given images id 1 uploaded 2026-09-01, id 2 and id 3 uploaded 2026-09-03
|
||||||
|
When a client sends GET /v1/media/?size=5
|
||||||
|
Then the item ids are 3, 2, 1
|
||||||
|
|
||||||
|
Scenario Outline: Sort orders the whole library before paging
|
||||||
|
Given 12 images with distinct names, sizes and dates
|
||||||
|
When a client requests ?sort=<sort>&size=5 for pages 1, 2 and 3
|
||||||
|
Then the pages hold the whole ordered list in <order> with no repeat
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| sort | order |
|
||||||
|
| newest | created_at descending |
|
||||||
|
| oldest | created_at ascending |
|
||||||
|
| name | filename stem, case-insensitive ascending |
|
||||||
|
| largest | size descending |
|
||||||
|
| total_size | original size plus generated variant bytes, descending |
|
||||||
|
|
||||||
|
Scenario: Filter and variants narrow total and items but not the counts
|
||||||
|
Given 40 images of which 6 are unused and 3 hold generated variants, and the library counts are {"all": 40, "unused": 6, "duplicates": 2}
|
||||||
|
When a client sends GET /v1/media/?filter=unused&size=5
|
||||||
|
Then total is 6, the page holds 5 items and counts is {"all": 40, "unused": 6, "duplicates": 2}
|
||||||
|
When a client sends GET /v1/media/?variants=with
|
||||||
|
Then total is 3 and counts is unchanged
|
||||||
|
|
||||||
|
Scenario: Search combines with paging
|
||||||
|
Given 7 images whose filename contains "wall" and 20 others
|
||||||
|
When a client sends GET /v1/media/?q=wall&size=5&page=2
|
||||||
|
Then total is 7, the page holds 2 items and counts.all is 27
|
||||||
|
|
||||||
|
Scenario: Hash lookup returns every copy in one page
|
||||||
|
Given 3 images share the sha256 H
|
||||||
|
When a client sends GET /v1/media/?hash=H&page=1&size=100
|
||||||
|
Then total is 3 and items has the 3 copies
|
||||||
|
|
||||||
|
Scenario: Hash lookup with no paging uses the defaults
|
||||||
|
Given 3 images share the sha256 H
|
||||||
|
When a client sends GET /v1/media/?hash=H
|
||||||
|
Then the body has page 1, size 25, total 3 and 3 items
|
||||||
|
|
||||||
|
Scenario: A page beyond the last is empty with the real total
|
||||||
|
Given the library holds 12 images
|
||||||
|
When a client sends GET /v1/media/?page=99&size=5
|
||||||
|
Then the status is 200, items is [], total is 12, page is 99, size is 5 and counts.all is 12
|
||||||
|
|
||||||
|
Scenario: An empty library
|
||||||
|
Given the library is empty
|
||||||
|
When a client sends GET /v1/media/
|
||||||
|
Then the status is 200, items is [], total is 0 and counts is {"all": 0, "unused": 0, "duplicates": 0}
|
||||||
|
|
||||||
|
Scenario: counts ignores every filter and the page
|
||||||
|
Given the library holds 30 images
|
||||||
|
When a client sends GET /v1/media/?q=zzzz&page=3&size=5
|
||||||
|
Then items is [], total is 0 and counts.all is 30
|
||||||
|
|
||||||
|
Scenario Outline: cursor and limit are ignored
|
||||||
|
Given the library holds 30 images
|
||||||
|
When a client sends GET /v1/media/?<query>
|
||||||
|
Then the status is 200 and the body has page 1, size 25 and 25 items
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| query |
|
||||||
|
| cursor=abc |
|
||||||
|
| limit=5 |
|
||||||
|
| limit=0 |
|
||||||
|
| limit=abc |
|
||||||
|
| cursor=b2Zmc2V0OjU |
|
||||||
|
|
||||||
|
Scenario Outline: Invalid parameters answer 400
|
||||||
|
When a client sends GET /v1/media/?<query>
|
||||||
|
Then the status is 400
|
||||||
|
And the body is "The media query is invalid."
|
||||||
|
And the repository was not called
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| query |
|
||||||
|
| page=0 |
|
||||||
|
| page=-1 |
|
||||||
|
| page=abc |
|
||||||
|
| page= |
|
||||||
|
| page=1.5 |
|
||||||
|
| size=0 |
|
||||||
|
| size=10 |
|
||||||
|
| size=200 |
|
||||||
|
| size=abc |
|
||||||
|
| size= |
|
||||||
|
| page=0&size=5 |
|
||||||
|
| page=1&size=1000 |
|
||||||
|
| filter=archived |
|
||||||
|
| sort=biggest |
|
||||||
|
| variants= |
|
||||||
|
| variants=other |
|
||||||
|
| hash=notahash |
|
||||||
|
|
||||||
|
Scenario: Repository failure answers 500
|
||||||
|
Given the repository fails on its next call
|
||||||
|
When a client sends GET /v1/media/
|
||||||
|
Then the status is 500 and the body is "Internal server error"
|
||||||
|
|
||||||
|
Scenario: An unauthenticated caller is refused as before
|
||||||
|
When a client sends GET /v1/media/?page=1&size=5 without a valid jwt cookie
|
||||||
|
Then the response is the unchanged 401 of the auth group and the use case is not called
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
# QA: Paginated media listing (API)
|
||||||
|
|
||||||
|
## HTTP-level (Go, `test/`, `task test`)
|
||||||
|
|
||||||
|
Build `media.NewHandler(...)` over the real `ListMediaUseCase` and in-memory fakes of `image.Repository`, `article.Repository`, `user.Repository` and `image.VariantFileRepository` (extend the existing media fakes, keeping type names unique across files). Mount on a fresh `chi.NewRouter()` mirroring the media router in `api/router.go` (GET / inside `jwtauth.Verifier` + `jwtauth.Authenticator`, test `jwtauth.New("HS256", ...)`, valid `jwt` cookie with a `user_id` claim of a verified user). Call `validator.InitValidator()`. No live server, no SQLite file.
|
||||||
|
|
||||||
|
Helper: decode into {items []map, total, page, size int, counts {all, unused, duplicates}}; also assert the raw JSON contains `"items":[` (never null) and does not contain `next_cursor`.
|
||||||
|
|
||||||
|
1. Bare request: 30 images -> object, page 1, size 25, total 30, 25 items, no `next_cursor`.
|
||||||
|
2. Defaults table: page=2, page=3, size=5, size=50, size=100 on 60 images.
|
||||||
|
3. Partition: 12 images, pages 1-3 of size 5 -> 5, 5, 2; 12 distinct ids.
|
||||||
|
4. Order: equal-timestamp case -> ids 3,2,1. Sort table (newest, oldest, name, largest, total_size): 12 images, three pages, concatenation equals the full ordered list, no repeat. Ties break on id.
|
||||||
|
5. Filter/variants/q: unused -> total 6, counts unchanged; variants=with -> total 3; q=wall&size=5&page=2 -> total 7, 2 items, counts.all 27.
|
||||||
|
6. Hash: hash=H&page=1&size=100 -> 3 copies; hash=H alone -> page 1, size 25, 3 items.
|
||||||
|
7. Out of range: page=99&size=5 -> 200, raw `"items":[]`, total 12.
|
||||||
|
8. Empty library -> items [], total 0, counts 0/0/0.
|
||||||
|
9. counts library-wide: q=zzzz&page=3&size=5 -> items [], total 0, counts.all 30.
|
||||||
|
10. cursor/limit ignored: rows `cursor=abc`, `limit=5`, `limit=0`, `limit=abc`, a valid-looking old cursor -> 200, page 1, size 25, 25 items.
|
||||||
|
11. Invalid table (all rows): each -> 400, body exactly "The media query is invalid.", repository call counters stay 0.
|
||||||
|
12. Repository failure -> 500 "Internal server error".
|
||||||
|
13. Missing or invalid jwt cookie -> the auth group's 401, use case counter 0.
|
||||||
|
14. Use-case tests: `ListMediaUseCase.List` returns items, total, page, size and counts; slices after sorting; propagates a repository error (`errors.Is` on a sentinel); `Describe` is unchanged; `ListQuery.Validate` rejects page < 1 and sizes outside 5/25/50/100 with `ErrInvalidQuery`. `image.ListQuery.Cursor` and `.Limit`, `MediaPage.NextCursor`, `encodeCursor` and `decodeCursor` no longer exist.
|
||||||
|
15. Existing tests that read `next_cursor`, send `limit` or `cursor`, or call `NewListQuery` (media tests in `test/`, `features/media_library.qa.md`, `features/media_browse.qa.md`) are amended to the envelope; list them in the diff.
|
||||||
|
|
||||||
|
## Docs (verified by reading the diff)
|
||||||
|
|
||||||
|
- `docs/api.md` lines 99-103: replace `cursor` and `limit` with `page` (default 1) and `size` (5, 25, 50, 100; default 25); state the envelope (`items`, `total`, `page`, `size`, `counts`), that `counts` stays library-wide, that invalid values answer 400 "The media query is invalid.", and a "Breaking change" note: `next_cursor` is gone, `cursor` and `limit` are ignored.
|
||||||
|
- `docs/api/*.md`: grep for `/v1/media/` and `cursor`; update the media listing section if one exists.
|
||||||
|
- `web/src/data/apiCatalogue.ts` `med-list`: add `page`, `size`, `q`, `filter`, `sort`, `variants`, `hash` query entries, the 400 error, and a paged example (`total`, `page`, `size`, no `next_cursor`). Remove the `next_cursor` rule (line ~129, with its French entry in `web/src/i18n/messages.ts` line ~1606) if it is only used by media. Integration specs asserting the catalogue are amended.
|
||||||
|
- Flag for the user (read-only to agents): `docs/design/screens/integration.md` and `docs/design/source/IntegrationPage.dc.html` (med-list with no params), `docs/design/screens/media.md`, `routes.md`, `change-list.md` item 13b, `README.md` line 92 and `screens/media-picker.md`: all still say "array body" and "X-Total-Count".
|
||||||
|
- A release note under `docs/releases/` is the maintainer's call: flag it.
|
||||||
|
|
||||||
|
## Manual verification
|
||||||
|
|
||||||
|
- Real SQLite file via `task dev`: seed 60 images, check page=2&size=25, ordering by each sort and counts; the same on MySQL/PostgreSQL if available (no live DB in tests).
|
||||||
|
- An authenticated curl returns the envelope with no `next_cursor`.
|
||||||
@@ -0,0 +1,185 @@
|
|||||||
|
Feature: Media page pagination
|
||||||
|
|
||||||
|
As a verified owner or admin with many images
|
||||||
|
I want the Media library split into pages with a page-size menu and shareable URLs
|
||||||
|
So that I can browse a large library quickly and come back to the same page
|
||||||
|
|
||||||
|
Background:
|
||||||
|
Given /media is the verified Media route (features/media_browse.feature), per docs/design/routes.md "Pagination in the URL (Articles, Media)" and docs/design/screens/media.md states 44-52
|
||||||
|
And the Paginator and PageSizeSelect are the existing components used by Articles (AppPaginator.vue); no new component is created
|
||||||
|
And the page requests GET /v1/media/?q=Q&filter=F&sort=S&variants=V&page=P&size=Z and reads {items, total, page, size, counts} (features/media_pagination_api.feature); q and variants are sent only when set; page and size are always sent explicitly; the tab counts come from counts and do not change while searching
|
||||||
|
And page and size live in the URL: ?page=&size=, next to the existing q, filter, sort, variants and view; the defaults (page 1, size 25) are omitted from the URL
|
||||||
|
And an invalid or missing size falls back to the stored size (features/media_page_size_memory.feature) or 25, and an invalid page (not an integer >= 1) falls back to 1, both silently replaced in the URL with history.replace and never shown as an error
|
||||||
|
And a change to search, tab, sort, view, the variants filter or the page size resets page to 1 (and drops it from the URL); search keeps its 120 ms debounce
|
||||||
|
And the URL changes when a response succeeds, not when the request is sent
|
||||||
|
And the summary reads "Showing {from}–{to} of {total}" with locale-formatted numbers, from total (the filtered count), under the grid or list
|
||||||
|
And the Paginator has First, Previous, page numbers with ellipses marking skipped ranges, Next, Last, and the page-size select "5 per page", "25 per page", "50 per page", "100 per page" (it opens upward)
|
||||||
|
And the current page uses --rc-sand fill, --rc-on-sand text and a --ui-primary border and has aria-current="page"; disabled controls are at 40 % opacity; buttons are 32 px (44 px on mobile)
|
||||||
|
And on mobile the paginator is Previous, "Page N of M" and Next
|
||||||
|
And the paginator is hidden when total fits on one page; the summary and the page-size select stay
|
||||||
|
And the paginator sits under the grid in grid view and under the table (md and up) or card list (below md) in list view; its exact placement is taken from the board frame docs/design/source/MediaFrame.dc.html, not from components.md prose
|
||||||
|
And keyboard: Tab reaches the page-size select, first, previous, each page, next, last; Enter or Space activates; ArrowDown opens the page-size list, Enter selects, Esc closes; every control shows a 2 px --ui-primary focus outline with a 2 px offset
|
||||||
|
And the Duplicates tab (?filter=duplicates) is not paginated: it loads the whole duplicate set with size=100, requesting page 1, 2, ... until the loaded count reaches total, groups it by sha256 as today, shows no paginator, summary or page-size select, and drops page and size from the URL
|
||||||
|
And "Select all" covers the images on the current page only and reads "{n} images" for that page; changing page, size, search, tab, sort or view clears the selection
|
||||||
|
And the silent background refresh after a delete, upload or merge reloads the current page with no skeleton; when the current page has become empty and is past the last page, the list steps back to the last page and replaces the URL
|
||||||
|
And the first load and a change of search, tab or sort keep the existing skeleton after 150 ms and the "Couldn't load your images" alert (media.md states 4 and 42); the page-change error below applies only when images are already shown
|
||||||
|
And the fixture below is total 312, size 25 (13 pages) unless stated, with the board's own sample data
|
||||||
|
|
||||||
|
Scenario: 44 First page
|
||||||
|
Given GET /v1/media/?filter=all&sort=newest&page=1&size=25 resolves 200 with 25 items, total 312 and counts {all 312, unused 2, duplicates 2}
|
||||||
|
When the user navigates to /media
|
||||||
|
Then the summary reads "Showing 1–25 of 312"
|
||||||
|
And First and Previous are disabled, page 1 is current, Next and Last are enabled
|
||||||
|
And the URL has no page or size
|
||||||
|
|
||||||
|
Scenario: 45 Middle page
|
||||||
|
Given GET ...&page=7&size=25 resolves 200 with 25 items and total 312
|
||||||
|
When the user navigates to /media?page=7
|
||||||
|
Then the summary reads "Showing 151–175 of 312"
|
||||||
|
And page 7 is current with --rc-sand / --rc-on-sand and aria-current="page"
|
||||||
|
And ellipses mark the skipped ranges and every control is enabled
|
||||||
|
|
||||||
|
Scenario: 46 Last page
|
||||||
|
Given GET ...&page=13&size=25 resolves 200 with 12 items and total 312
|
||||||
|
When the user navigates to /media?page=13
|
||||||
|
Then the summary reads "Showing 301–312 of 312"
|
||||||
|
And Next and Last are disabled
|
||||||
|
|
||||||
|
Scenario: Single page
|
||||||
|
Given GET /v1/media/ resolves 200 with 12 items, total 12 and counts {all 12, unused 2, duplicates 2}
|
||||||
|
When the user navigates to /media
|
||||||
|
Then the summary reads "Showing 1–12 of 12" and the page-size select stays
|
||||||
|
And the paginator (First ... Last) is not rendered
|
||||||
|
|
||||||
|
Scenario: 47 List view, desktop and mobile
|
||||||
|
Given page 2 of 13 is shown with ?view=list
|
||||||
|
Then at md width or more the paginator sits under the table with the page numbers
|
||||||
|
And below md it sits under the card list as Previous, "Page 2 of 13", Next with 44 px controls and no page numbers
|
||||||
|
And in grid view on mobile the paginator is the same Previous, "Page 2 of 13", Next
|
||||||
|
|
||||||
|
Scenario: 48 Loading next page
|
||||||
|
Given the first page has loaded and GET ...&page=2 has not resolved
|
||||||
|
When the user activates Next
|
||||||
|
Then skeleton cards keep the grid height and the list is aria-busy="true"
|
||||||
|
And every paginator control is disabled and the summary reads "Loading page 2…"
|
||||||
|
When the request resolves 200
|
||||||
|
Then the images and summary of page 2 appear and the URL becomes /media?page=2
|
||||||
|
|
||||||
|
Scenario Outline: 49 Error loading a page keeps the previous images
|
||||||
|
Given page 6 is shown
|
||||||
|
When the user activates Next and GET ...&page=7 <failure>
|
||||||
|
Then the page-6 images stay, the URL stays /media?page=6 and the controls are re-enabled
|
||||||
|
And a notice reads "Couldn't load page 7. Showing page 6." with a "Retry" action
|
||||||
|
When the user activates "Retry"
|
||||||
|
Then GET ...&page=7 is sent again and, on 200, page 7 replaces the images, the URL becomes ?page=7 and the notice goes
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| failure |
|
||||||
|
| resolves with a 500 response |
|
||||||
|
| never reaches the server |
|
||||||
|
|
||||||
|
Scenario: 50 Page out of range redirects to the last page with a notice
|
||||||
|
Given GET ...&page=99 resolves 200 with items [] and total 312
|
||||||
|
When the user navigates to /media?page=99
|
||||||
|
Then the URL is replaced (no history entry) by /media?page=13 and GET ...&page=13 is sent
|
||||||
|
And the notice reads "That page doesn't exist. Showing the last page."
|
||||||
|
And the last-page state (46) is shown
|
||||||
|
|
||||||
|
Scenario: Out of range with total 0 shows the empty state, no redirect
|
||||||
|
Given GET ...&page=5 resolves 200 with items [] and total 0 and counts.all 0
|
||||||
|
When the user navigates to /media?page=5
|
||||||
|
Then the "No images yet" empty state shows and the URL is /media
|
||||||
|
|
||||||
|
Scenario: Out of range after a search with total 0 shows no results
|
||||||
|
Given GET ...&q=zzzz&page=5 resolves 200 with items [], total 0 and counts.all 312
|
||||||
|
When the user navigates to /media?q=zzzz&page=5
|
||||||
|
Then the no-results state (media.md state 6) shows and the URL is /media?q=zzzz
|
||||||
|
|
||||||
|
Scenario Outline: Search, tab, sort, view and variants changes reset to page 1
|
||||||
|
Given the user is on /media?page=7
|
||||||
|
When the user <action> and the request resolves
|
||||||
|
Then GET ... carries page=1
|
||||||
|
And on success the URL has no page
|
||||||
|
And the tab counts are unchanged by a search
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| action |
|
||||||
|
| types "wall" in the search field and the debounce elapses |
|
||||||
|
| selects the "Unused" tab |
|
||||||
|
| picks "Largest" in the sort menu |
|
||||||
|
| activates the list icon in the grid toggle |
|
||||||
|
| applies the "With variants" filter |
|
||||||
|
|
||||||
|
Scenario Outline: 51 Page size menu
|
||||||
|
Given the user is on /media?page=3
|
||||||
|
When the user opens the page-size select (it opens upward) and chooses "<label>"
|
||||||
|
Then GET ...&page=1&size=<size> is sent and, on success, the URL is <url>
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| label | size | url |
|
||||||
|
| 5 per page | 5 | /media?size=5 |
|
||||||
|
| 25 per page | 25 | /media |
|
||||||
|
| 50 per page | 50 | /media?size=50 |
|
||||||
|
| 100 per page | 100 | /media?size=100 |
|
||||||
|
|
||||||
|
Scenario Outline: Invalid URL values fall back silently
|
||||||
|
When the user navigates to /media?<query>
|
||||||
|
Then GET ... is sent with page=1 and size=25 and the URL is replaced by /media with no history entry
|
||||||
|
And no error or notice is shown
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| query |
|
||||||
|
| size=10&page=abc |
|
||||||
|
| page=0 |
|
||||||
|
| page=-2 |
|
||||||
|
| page=1.5 |
|
||||||
|
| size=0 |
|
||||||
|
| size=200 |
|
||||||
|
|
||||||
|
Scenario: Pagination is kept across the other controls
|
||||||
|
Given the URL is /media?size=50&sort=largest&filter=unused
|
||||||
|
When the user activates Next
|
||||||
|
Then every request carries size=50, sort=largest and filter=unused and the URL keeps them
|
||||||
|
|
||||||
|
Scenario: 52 Focus-visible
|
||||||
|
When the user tabs to Next
|
||||||
|
Then Next shows a 2 px --ui-primary outline with a 2 px offset
|
||||||
|
And the same ring shows on every paginator control and on the page-size select
|
||||||
|
|
||||||
|
Scenario: Keyboard, the page-size list
|
||||||
|
When the user focuses the page-size select and presses ArrowDown
|
||||||
|
Then the list opens; Enter selects the highlighted size; Esc closes it and returns focus to the select
|
||||||
|
|
||||||
|
Scenario: Select all covers the current page only
|
||||||
|
Given page 2 of 13 is shown with 25 images
|
||||||
|
Then the "Select all" row reads "Select all" and "25 images"
|
||||||
|
When the user activates "Select all"
|
||||||
|
Then 25 images are selected and the bulk bar announces "25 selected"
|
||||||
|
When the user activates Next and page 3 loads
|
||||||
|
Then no image is selected and the bulk bar is gone
|
||||||
|
|
||||||
|
Scenario: The Duplicates tab loads the whole set and shows no paginator
|
||||||
|
Given 130 images are duplicates, GET ...&filter=duplicates&sort=newest&page=1&size=100 resolves 200 with 100 items and total 130
|
||||||
|
And GET ...&filter=duplicates&page=2&size=100 resolves 200 with the remaining 30 items
|
||||||
|
When the user navigates to /media?filter=duplicates&page=4&size=5
|
||||||
|
Then page 1 and page 2 are requested with size=100, page 2 only because 100 < 130
|
||||||
|
And the groups are built from the 130 images, with no paginator, summary or page-size select
|
||||||
|
And the URL is replaced by /media?filter=duplicates
|
||||||
|
|
||||||
|
Scenario: Leaving the Duplicates tab returns to the paginated list
|
||||||
|
Given the Duplicates tab is shown
|
||||||
|
When the user selects the "All" tab
|
||||||
|
Then GET ...&filter=all&page=1&size=25 is sent and the paginator is shown
|
||||||
|
|
||||||
|
Scenario: Deleting the last image of the last page
|
||||||
|
Given the user is on the last page with a single image and deletes it (204)
|
||||||
|
Then the list reloads the previous page in the background and the URL is replaced by it
|
||||||
|
And the tab counts are recomputed from the new response
|
||||||
|
|
||||||
|
Scenario: A background refresh keeps the current page
|
||||||
|
Given page 7 is shown and the user renames, uploads or merges
|
||||||
|
Then the list is requested again in the background for page 7 with no skeleton
|
||||||
|
|
||||||
|
Scenario: Hash lookups do not touch the page
|
||||||
|
When the detail panel or the upload duplicate check looks up copies of an image
|
||||||
|
Then GET /v1/media/?hash=H&page=1&size=100 is sent, the URL does not change and the paginator is unaffected
|
||||||
@@ -0,0 +1,52 @@
|
|||||||
|
# QA: Media page pagination (SPA)
|
||||||
|
|
||||||
|
## Automated (Vitest + Vue Test Utils, `task test:web`)
|
||||||
|
|
||||||
|
Mock `/v1/media/` the way `web/src/views/__tests__/mediaTestKit.ts` does, extended so the mock honours `page` and `size`, builds the envelope `{items, total, page, size, counts}` and has no `next_cursor`. Use the 312-image fixture (25 per page) from the board's data in `docs/design/source/MediaFrame.dc.html`. Mount `MediaView` with a real router and Pinia. Reuse the helpers of `ArticlesPagination.spec.ts`.
|
||||||
|
|
||||||
|
One test per state:
|
||||||
|
1. 44 First page: request `?filter=all&sort=newest&page=1&size=25`; "Showing 1–25 of 312"; First/Previous disabled; URL without page or size.
|
||||||
|
2. 45 Middle page: `/media?page=7` -> "Showing 151–175 of 312"; `aria-current="page"` on 7; ellipses.
|
||||||
|
3. 46 Last page: `/media?page=13` -> 12 items, "Showing 301–312 of 312"; Next/Last disabled.
|
||||||
|
4. Single page: total 12 -> summary, page-size select, no First..Last.
|
||||||
|
5. 47 List view: `?view=list&page=2` -> paginator under the table (md) and the card list (below md, the "Page 2 of 13" form).
|
||||||
|
6. 48 Loading next page: pending page 2 -> skeleton cards, `aria-busy`, controls disabled, "Loading page 2…"; resolve -> URL `/media?page=2`.
|
||||||
|
7. 49 Error (500, network): previous images stay, URL unchanged, notice "Couldn't load page 7. Showing page 6." with Retry; Retry succeeds -> `?page=7`, notice gone.
|
||||||
|
8. 50 Out of range: `?page=99` with items [] and total 312 -> URL replaced by `?page=13` (assert `router.replace`, history length unchanged), notice text exact, last-page state.
|
||||||
|
9. Total 0 out of range: empty state, URL `/media`; with `q` -> no-results state.
|
||||||
|
10. Reset to page 1: table of search (120 ms debounce with fake timers on the timer only, never the system date), tab, sort, view, variants filter -> request carries `page=1`, URL has no page.
|
||||||
|
11. 51 Page-size menu table: 5, 25, 50, 100 -> request `page=1&size=N`; URLs per the table.
|
||||||
|
12. Invalid URL table (`size=10&page=abc`, `page=0`, `page=-2`, `page=1.5`, `size=0`, `size=200`): request page=1 size=25, URL replaced, no notice or alert.
|
||||||
|
13. Controls kept: Next with `size=50&sort=largest&filter=unused` keeps every param.
|
||||||
|
14. 52 Focus and keyboard: tab order select, first, previous, pages, next, last; ArrowDown opens, Enter selects, Esc closes and refocuses.
|
||||||
|
15. Select all: "25 images", 25 selected, page change clears the selection and the bulk bar.
|
||||||
|
16. Duplicates tab: with 130 duplicates, assert requests page=1 and page=2 at size=100, groups built from all 130, no paginator, URL drops page and size; selecting All returns to the paginated request.
|
||||||
|
17. Last-image delete: steps back one page and replaces the URL; counts refreshed.
|
||||||
|
18. Background refresh after rename/upload/merge: same page, no skeleton.
|
||||||
|
19. Hash lookups send `hash=H&page=1&size=100` (`findCopies`, `useMediaUpload`, `ImageUploader`).
|
||||||
|
20. Amended existing specs: every spec reading `next_cursor`, `limit=100`, `MEDIA_PAGE_LIMIT` or the old `/v1/media/?` mocks is migrated to the envelope and page/size requests; list them in the diff.
|
||||||
|
|
||||||
|
## Visual (`task visual:check -- media`)
|
||||||
|
|
||||||
|
Hard gate: every capture within 10 % at 1440×900 and 390×844, light and dark. Add `web/visual/states.ts` setups using the board's own sample data (312 images, 25 per page; filenames, sizes, uploaders and dates taken from the frame's script in `docs/design/source/MediaFrame.dc.html`; counts all 312 / unused 2 / duplicates 2):
|
||||||
|
|
||||||
|
| State | Setup |
|
||||||
|
| --- | --- |
|
||||||
|
| 44 Pagination: first page | `/media`, page 1 of 13 |
|
||||||
|
| 45 middle page | `/media?page=7` |
|
||||||
|
| 46 last page | `/media?page=13`, 12 items |
|
||||||
|
| 47 list view | `/media?view=list&page=2` |
|
||||||
|
| 48 loading next page | page 2 pending |
|
||||||
|
| 49 error loading a page | page 7 fails, page 6 shown |
|
||||||
|
| 50 page out of range | `/media?page=99` replaced by `?page=13` with the notice |
|
||||||
|
| 51 page-size menu | select open upward |
|
||||||
|
| 52 focus-visible | Next focused |
|
||||||
|
|
||||||
|
If a frame renders a relative date or greeting, mark that state `skip: clock-sensitive` and write no date-frozen test. The paginator's placement under the grid or list is checked against the board frame's markup, not `components.md` prose.
|
||||||
|
|
||||||
|
## Manual verification
|
||||||
|
|
||||||
|
- Keyboard: tab order and focus ring on every paginator control; ArrowDown/Enter/Esc in the page-size list; grid arrow-key navigation still works after a page change; focus is sensible after Next.
|
||||||
|
- Hover and motion on the paginator and skeleton.
|
||||||
|
- A real library of 60+ images through `task dev`: paging, size change, page past the end replaced with the notice, Duplicates tab loading beyond 100 duplicates.
|
||||||
|
- Screen reader: the summary and "Loading page N…" are announced; selection announcements after a page change.
|
||||||
@@ -10,13 +10,16 @@ Feature: Media page, part 2: upload, selection and duplicates
|
|||||||
DashboardShell, per docs/design/routes.md and docs/design/screens/media.md
|
DashboardShell, per docs/design/routes.md and docs/design/screens/media.md
|
||||||
And this slice is SPA only: the API from slice A is used unchanged, and no Go code, use case
|
And this slice is SPA only: the API from slice A is used unchanged, and no Go code, use case
|
||||||
or repository changes
|
or repository changes
|
||||||
|
And this slice is amended by features/media_pagination_screen.feature: "Select all" covers the
|
||||||
|
images of the current page only, the Duplicates tab loads the whole set at size=100 page after
|
||||||
|
page until the loaded count reaches total, and hash lookups send page=1&size=100
|
||||||
And this slice supersedes these B1 statements: the Upload button, the mobile pinned button and
|
And this slice supersedes these B1 statements: the Upload button, the mobile pinned button and
|
||||||
"Upload an image" are enabled; the Duplicates tab is enabled and ?filter=duplicates is a
|
"Upload an image" are enabled; the Duplicates tab is enabled and ?filter=duplicates is a
|
||||||
valid value; "Review duplicates" is enabled; Space on a card toggles selection; the checkbox,
|
valid value; "Review duplicates" is enabled; Space on a card toggles selection; the checkbox,
|
||||||
the "Select all" text and the partial state exist; the B2 states no longer carry
|
the "Select all" text and the partial state exist; the B2 states no longer carry
|
||||||
skip 'pending' in web/visual/states.ts
|
skip 'pending' in web/visual/states.ts
|
||||||
And the calls used are POST /v1/media/ (multipart field "file", sent with XMLHttpRequest so
|
And the calls used are POST /v1/media/ (multipart field "file", sent with XMLHttpRequest so
|
||||||
that upload progress is reported, with the jwt cookie), GET /v1/media/?hash=<sha256 hex>,
|
that upload progress is reported, with the jwt cookie), GET /v1/media/?hash=<sha256 hex>&page=1&size=100,
|
||||||
DELETE /v1/media/{id}, POST /v1/media/merge { keep_id, merge_ids } and the list call from
|
DELETE /v1/media/{id}, POST /v1/media/merge { keep_id, merge_ids } and the list call from
|
||||||
B1 with filter=duplicates; every other /v1 call goes through useApi
|
B1 with filter=duplicates; every other /v1 call goes through useApi
|
||||||
And 401 and 403 on any of these calls, including the XHR upload, send the user to
|
And 401 and 403 on any of these calls, including the XHR upload, send the user to
|
||||||
@@ -130,7 +133,7 @@ Feature: Media page, part 2: upload, selection and duplicates
|
|||||||
Scenario: A row whose content already exists
|
Scenario: A row whose content already exists
|
||||||
Given the user chooses "floorboards-2.jpg" (2.4 MB, valid)
|
Given the user chooses "floorboards-2.jpg" (2.4 MB, valid)
|
||||||
When the SHA-256 of the file is computed
|
When the SHA-256 of the file is computed
|
||||||
Then GET /v1/media/?hash=<that hex> is sent before any POST
|
Then GET /v1/media/?hash=<that hex>&page=1&size=100 is sent before any POST
|
||||||
And when it resolves 200 with the image "floorboards.jpg" (id 12, uploaded 14 Jun 2026 by Inès Duarte)
|
And when it resolves 200 with the image "floorboards.jpg" (id 12, uploaded 14 Jun 2026 by Inès Duarte)
|
||||||
Then the row shows "Already in your library", the text `Same as "floorboards.jpg", uploaded 14 Jun 2026 by Inès Duarte.`, and the buttons "Use existing" and "Upload anyway"
|
Then the row shows "Already in your library", the text `Same as "floorboards.jpg", uploaded 14 Jun 2026 by Inès Duarte.`, and the buttons "Use existing" and "Upload anyway"
|
||||||
And nothing is sent with POST /v1/media/ for it, and its concurrency slot is released
|
And nothing is sent with POST /v1/media/ for it, and its concurrency slot is released
|
||||||
@@ -146,7 +149,7 @@ Feature: Media page, part 2: upload, selection and duplicates
|
|||||||
And the image "floorboards.jpg" is selected, the bulk bar reads "1 selected", and the page announces "floorboards.jpg selected, 1 selected"
|
And the image "floorboards.jpg" is selected, the bulk bar reads "1 selected", and the page announces "floorboards.jpg selected, 1 selected"
|
||||||
|
|
||||||
Scenario: Use existing when the image is not in the loaded list
|
Scenario: Use existing when the image is not in the loaded list
|
||||||
Given the existing image is not in the loaded list because of the search, the tab or the 100 limit
|
Given the existing image is not in the loaded list because of the search, the tab or the current page
|
||||||
When the user activates "Use existing"
|
When the user activates "Use existing"
|
||||||
Then the search and the tab reset to All and the image is selected
|
Then the search and the tab reset to All and the image is selected
|
||||||
And if it is still not loaded the row is dropped without selecting
|
And if it is still not loaded the row is dropped without selecting
|
||||||
@@ -275,7 +278,7 @@ Feature: Media page, part 2: upload, selection and duplicates
|
|||||||
When 3 images are selected
|
When 3 images are selected
|
||||||
Then that checkbox shows the partial state
|
Then that checkbox shows the partial state
|
||||||
When the user activates it while it is partial
|
When the user activates it while it is partial
|
||||||
Then all 12 loaded images are selected and it shows checked
|
Then all 12 images of the current page are selected and it shows checked (never the other pages)
|
||||||
When the user activates it while it is checked
|
When the user activates it while it is checked
|
||||||
Then the selection is emptied
|
Then the selection is emptied
|
||||||
And in list view at md width or more the table header checkbox does the same; the mobile card list has no "Select all" row and is selected through its 44 px row checkboxes
|
And in list view at md width or more the table header checkbox does the same; the mobile card list has no "Select all" row and is selected through its 44 px row checkboxes
|
||||||
@@ -358,13 +361,13 @@ Feature: Media page, part 2: upload, selection and duplicates
|
|||||||
Scenario: The Duplicates tab is enabled
|
Scenario: The Duplicates tab is enabled
|
||||||
Given the Default state has loaded
|
Given the Default state has loaded
|
||||||
When the user selects the "Duplicates 2" tab
|
When the user selects the "Duplicates 2" tab
|
||||||
Then the URL gains ?filter=duplicates and the list is requested with filter=duplicates and limit=100
|
Then the URL gains ?filter=duplicates and the list is requested with filter=duplicates at size=100, page 1, 2, ... until the loaded count reaches total
|
||||||
And the tab is selected, and "Duplicates" carries the info-tinted count of groups
|
And the tab is selected, and "Duplicates" carries the info-tinted count of groups
|
||||||
And opening /media?filter=duplicates lands on the same view, and "Review duplicates" in the detail panel of "floorboards.jpg" is enabled and selects this tab
|
And opening /media?filter=duplicates lands on the same view, and "Review duplicates" in the detail panel of "floorboards.jpg" is enabled and selects this tab
|
||||||
And search applies, the sort menu and the view toggle show as on the other tabs, sort is sent with the request, and the view toggle has no effect on the groups view while the grid or list preference stays in the URL
|
And search applies, the sort menu and the view toggle show as on the other tabs, sort is sent with the request, and the view toggle has no effect on the groups view while the grid or list preference stays in the URL
|
||||||
|
|
||||||
Scenario: Duplicates, groups
|
Scenario: Duplicates, groups
|
||||||
Given GET /v1/media/?filter=duplicates&sort=newest&limit=100 resolves 200 with ids 5, 6, 7, 9 and 12
|
Given GET /v1/media/?filter=duplicates&sort=newest&page=1&size=100 resolves 200 with ids 5, 6, 7, 9 and 12
|
||||||
When the user opens the Duplicates tab
|
When the user opens the Duplicates tab
|
||||||
Then the images are grouped by sha256 into 2 bordered cards stacked with a 16 px gap, the group with the oldest suggested copy first
|
Then the images are grouped by sha256 into 2 bordered cards stacked with a 16 px gap, the group with the oldest suggested copy first
|
||||||
And group 1 has the header "Group 1" over "3 identical images · 2.4 MB each · 3600 × 2400", and group 2 has "Group 2" over "2 identical images · 3.1 MB each · 3600 × 2400"
|
And group 1 has the header "Group 1" over "3 identical images · 2.4 MB each · 3600 × 2400", and group 2 has "Group 2" over "2 identical images · 3.1 MB each · 3600 × 2400"
|
||||||
|
|||||||
@@ -13,7 +13,7 @@ Mount MediaPage in DashboardShell with a verified session and a test router at /
|
|||||||
3. **Entry points**: Upload (desktop header), the mobile pinned button and "Upload an image" each click the hidden `input[type=file]` (multiple, exact accept list).
|
3. **Entry points**: Upload (desktop header), the mobile pinned button and "Upload an image" each click the hidden `input[type=file]` (multiple, exact accept list).
|
||||||
4. **Drop overlay**: dragenter with Files shows the copy exactly; dragleave hides; drop starts uploads; a drag without Files shows nothing; mobile pinned button hidden while shown.
|
4. **Drop overlay**: dragenter with Files shows the copy exactly; dragleave hides; drop starts uploads; a drag without Files shows nothing; mobile pinned button hidden while shown.
|
||||||
5. **Queue**: 6 valid files give at most 2 XHRs open at once; order kept; header "Uploading 6 images" and "N of 6 done" counts settled rows; "Uploading 1 image" singular; progress 1.1 of 2.6 MB reads "Uploading 1.1 of 2.6 MB" with a 42 % bar; 201 gives "Added to your library"; a silent list reload follows; files added while open are appended.
|
5. **Queue**: 6 valid files give at most 2 XHRs open at once; order kept; header "Uploading 6 images" and "N of 6 done" counts settled rows; "Uploading 1 image" singular; progress 1.1 of 2.6 MB reads "Uploading 1.1 of 2.6 MB" with a 42 % bar; 201 gives "Added to your library"; a silent list reload follows; files added while open are appended.
|
||||||
6. **Duplicate check**: GET `?hash=` precedes POST; a match gives the Duplicate row with exact text (oldest match named); slot released; "Use existing" drops the row and selects the id (bulk bar "1 selected", live region text), including the reset-to-All path; "Upload anyway" sends POST; crypto undefined and lookup failure skip straight to POST.
|
6. **Duplicate check**: GET `?hash=...&page=1&size=100` precedes POST; a match gives the Duplicate row with exact text (oldest match named); slot released; "Use existing" drops the row and selects the id (bulk bar "1 selected", live region text), including the reset-to-All path; "Upload anyway" sends POST; crypto undefined and lookup failure skip straight to POST.
|
||||||
7. **Server statuses**: 201, 413, 415, 400, 500, network error: row copy and icon exact; "Try again" re-sends only that file with no new GET `?hash=`.
|
7. **Server statuses**: 201, 413, 415, 400, 500, network error: row copy and icon exact; "Try again" re-sends only that file with no new GET `?hash=`.
|
||||||
8. **Cancel**: row x aborts that XHR and removes the row, the next file starts; "Cancel all" aborts all and removes waiting rows; panel closes when empty.
|
8. **Cancel**: row x aborts that XHR and removes the row, the next file starts; "Cancel all" aborts all and removes waiting rows; panel closes when empty.
|
||||||
9. **Summary**: Examples-driven summary lines; "Upload finished" / "{n} images" and "Dismiss"; "Nothing was uploaded" with "3 files were rejected" and with "2 files need attention", no summary; live-region text; Dismiss removes every row.
|
9. **Summary**: Examples-driven summary lines; "Upload finished" / "{n} images" and "Dismiss"; "Nothing was uploaded" with "3 files were rejected" and with "2 files need attention", no summary; live-region text; Dismiss removes every row.
|
||||||
@@ -22,7 +22,7 @@ Mount MediaPage in DashboardShell with a verified session and a test router at /
|
|||||||
12. **Selection**: checkbox visibility (hover, focus, any selection, always on mobile); tick and Space toggle; Enter opens the panel and ticking does not; live-region texts for select, unselect and "Selection cleared"; the checkbox is not a tab stop; select-all states (unchecked, partial, checked) in the grid row and the table header (no row in the mobile card list); Escape closes the panel first and clears the selection next; Clear; selection cleared on q/tab/sort change, kept on view change.
|
12. **Selection**: checkbox visibility (hover, focus, any selection, always on mobile); tick and Space toggle; Enter opens the panel and ticking does not; live-region texts for select, unselect and "Selection cleared"; the checkbox is not a tab stop; select-all states (unchecked, partial, checked) in the grid row and the table header (no row in the mobile card list); Escape closes the panel first and clears the selection next; Clear; selection cleared on q/tab/sort change, kept on view change.
|
||||||
13. **Bulk bar**: copy, buttons, desktop and mobile placement classes, replaces the mobile pinned button.
|
13. **Bulk bar**: copy, buttons, desktop and mobile placement classes, replaces the mobile pinned button.
|
||||||
14. **Bulk delete**: dialog copy exact (title, description with the summed count, rows "Used in 2", "Used in 3", "Unused"), singular form; no usage request; in progress (one DELETE per id, buttons disabled, not dismissible); done (cards leave, selection empty, focus target, toast id and text, silent reload); partly failed (two removed, failed one stays selected, bar "1 selected", toast with Retry and no auto-dismiss, Retry re-sends only the failed DELETE); several failures title; 404 counted as deleted; all failed gives the inline alert.
|
14. **Bulk delete**: dialog copy exact (title, description with the summed count, rows "Used in 2", "Used in 3", "Unused"), singular form; no usage request; in progress (one DELETE per id, buttons disabled, not dismissible); done (cards leave, selection empty, focus target, toast id and text, silent reload); partly failed (two removed, failed one stays selected, bar "1 selected", toast with Retry and no auto-dismiss, Retry re-sends only the failed DELETE); several failures title; 404 counted as deleted; all failed gives the inline alert.
|
||||||
15. **Duplicates tab**: enabled, URL and request (`filter=duplicates`, limit=100), deep link, "Review duplicates" enabled and switching tab; sort and view toggle shown (sort sent with the request, toggle keeps the preference in the URL); grouping by sha256, group order, headers (including the SVG/unknown uploader case), column order, "Suggested" tag and footer, "Uploaded 14 Jun 2026 by Inès Duarte", "Used in 4 articles" opens the panel; suggested-copy Examples; empty state and "Back to all images"; badge absent at 0.
|
15. **Duplicates tab**: enabled, URL and request (`filter=duplicates`, size=100, page 1, 2, ... until total is reached; amended by `features/media_pagination_screen.feature`), deep link, "Review duplicates" enabled and switching tab; sort and view toggle shown (sort sent with the request, toggle keeps the preference in the URL); grouping by sha256, group order, headers (including the SVG/unknown uploader case), column order, "Suggested" tag and footer, "Uploaded 14 Jun 2026 by Inès Duarte", "Used in 4 articles" opens the panel; suggested-copy Examples; empty state and "Back to all images"; badge absent at 0.
|
||||||
16. **Merge**: dialog copy exact for floorboards.jpg and another kept copy, singular form; POST body `{ keep_id: 12, merge_ids: [5, 6] }`; in progress not dismissible; 200 gives group removed, toast id "media-merged-12" and text, live-region text, silent reload, "No duplicates" when last; 500 and network give the alert; 409 gives the alert and a reload; 404 gives the info toast and closes.
|
16. **Merge**: dialog copy exact for floorboards.jpg and another kept copy, singular form; POST body `{ keep_id: 12, merge_ids: [5, 6] }`; in progress not dismissible; 200 gives group removed, toast id "media-merged-12" and text, live-region text, silent reload, "No duplicates" when last; 500 and network give the alert; 409 gives the alert and a reload; 404 gives the info toast and closes.
|
||||||
17. **Global errors**: 401 and 403 from XHR upload, merge, delete and hash lookup call the same redirect handler as useApi; no local copy.
|
17. **Global errors**: 401 and 403 from XHR upload, merge, delete and hash lookup call the same redirect handler as useApi; no local copy.
|
||||||
18. **B1 regression**: media_browse specs updated for the superseded statements and the rest still passes.
|
18. **B1 regression**: media_browse specs updated for the superseded statements and the rest still passes.
|
||||||
|
|||||||
@@ -1,10 +1,10 @@
|
|||||||
Feature: Creating a new article from NewArticleModal
|
Feature: Creating a new article from NewArticleModal
|
||||||
|
|
||||||
As a verified RenewCMS owner
|
As a verified RenewCMS owner
|
||||||
I want NewArticleModal to take a title and a first paragraph, create the article as a draft
|
I want NewArticleModal to take only a title, create the article as a draft
|
||||||
over POST /v1/article/, and take me straight to the editor to keep writing
|
over POST /v1/article/, and take me straight to the editor to write it
|
||||||
So that starting a new article is a two-field, low-friction step instead of a full form, and I
|
So that starting a new article is a one-field, low-friction step and I land where I can
|
||||||
land where I can actually write it
|
actually write it
|
||||||
|
|
||||||
Background:
|
Background:
|
||||||
Given NewArticleModal is a UModal opened from Home's "New article" action (mobile header
|
Given NewArticleModal is a UModal opened from Home's "New article" action (mobile header
|
||||||
@@ -14,42 +14,37 @@ Feature: Creating a new article from NewArticleModal
|
|||||||
And every time it opens, it starts in the Default state: title "New article", text "It's
|
And every time it opens, it starts in the Default state: title "New article", text "It's
|
||||||
saved as a draft. Titles can't be changed later, so check it now.", an empty, focused Title
|
saved as a draft. Titles can't be changed later, so check it now.", an empty, focused Title
|
||||||
field with placeholder "e.g. Choosing tiles for a small bathroom", a CharacterCounter
|
field with placeholder "e.g. Choosing tiles for a small bathroom", a CharacterCounter
|
||||||
reading "0 / 200" and help "3 to 200 characters.", an empty First paragraph textarea with
|
reading "0 / 200" and help "3 to 200 characters.", a "Cancel" button and a "Create draft"
|
||||||
placeholder "Start writing. You'll continue in the editor." and help "You can format it and
|
button; there is no body or First paragraph field
|
||||||
add images in the editor.", a "Cancel" button and a "Create draft" button
|
|
||||||
And the Title field is sent as the request's title and is validated required, 3 to 200
|
And the Title field is sent as the request's title and is validated required, 3 to 200
|
||||||
characters, counted the same way as the CharacterCounter ([...str].length, which is rune
|
characters, counted the same way as the CharacterCounter ([...str].length, which is rune
|
||||||
count, matching article_title_rules.feature's server-side rune counting)
|
count, matching article_title_rules.feature's server-side rune counting)
|
||||||
And the First paragraph field is sent as the request's body and is validated required (at
|
And the request carries no body key; the server treats an absent body as "" per
|
||||||
least one character)
|
features/article_body_unlimited.feature
|
||||||
And each field validates on blur and again on submit; submitting while either field is
|
And the Title field validates on blur and again on submit; submitting while it is invalid
|
||||||
invalid sends no request, and shows both fields' errors at once if both are invalid: Title
|
sends no request: a title under 3 characters shows "Use at least 3 characters." in place of
|
||||||
under 3 characters shows "Use at least 3 characters." in place of its help text, with the
|
its help text, with the counter in its error style
|
||||||
counter in its error style; an empty First paragraph shows "Add a first paragraph. It can
|
And activating "Create draft" while the title is valid sends POST /v1/article/ with JSON
|
||||||
be a single sentence." in place of its help text
|
{"title": "<title>"}; while the request is in flight the Title field and both buttons are
|
||||||
And activating "Create draft" while both fields are valid sends POST /v1/article/ with JSON
|
disabled, the confirm button reads "Creating…" with a loading indicator, and the modal
|
||||||
{"title": "<title>", "body": "<first paragraph>"}; while the request is in flight both
|
cannot be dismissed by Cancel, Esc or a backdrop click
|
||||||
fields and both buttons are disabled, the confirm button reads "Creating…" with a loading
|
|
||||||
indicator, and the modal cannot be dismissed by Cancel, Esc or a backdrop click
|
|
||||||
And a 201 response closes the modal, emits created(article) with the response body, and (for
|
And a 201 response closes the modal, emits created(article) with the response body, and (for
|
||||||
this slice) HomeView.vue's created handler navigates to /article/{id}/edit and raises a
|
this slice) HomeView.vue's created handler navigates to /article/{id}/edit and raises a
|
||||||
toast: color success, icon i-lucide-circle-check, title "Draft created", description
|
toast: color success, icon i-lucide-circle-check, title "Draft created", description
|
||||||
"\"{title}\" is saved as a draft.", with id "article-created-{id}" per
|
"\"{title}\" is saved as a draft.", with id "article-created-{id}" per
|
||||||
docs/design/components.md's toast-id convention
|
docs/design/components.md's toast-id convention
|
||||||
And a 400 response — whether apperr.ArticleTitleErrorMessage for a title that passed this
|
And a 400 response is never shown verbatim; it re-enables the form with the title kept,
|
||||||
form's own check but still failed the server's, or any other 400 — is never shown verbatim;
|
shows "Check this title and try again." in place of the Title field's help text, and shows
|
||||||
it re-enables the form with both fields' current values kept, shows "Check this title and
|
an alert "Something in the form isn't valid. Check the highlighted fields."
|
||||||
try again." in place of the Title field's help text, and shows an alert "Something in the
|
And a 500 response or a request that never reaches the server re-enables the form with the
|
||||||
form isn't valid. Check the highlighted fields."; the First paragraph field shows no error
|
title kept and shows an alert "Couldn't create the article. Your text is still here. Try
|
||||||
And a 500 response or a request that never reaches the server re-enables the form with both
|
again in a moment.", with no field-level error
|
||||||
fields' current values kept and shows an alert "Couldn't create the article. Your text is
|
And "Cancel" always closes the modal immediately and discards the title, with no
|
||||||
still here. Try again in a moment.", with no field-level error
|
|
||||||
And "Cancel" always closes the modal immediately and discards both fields, with no
|
|
||||||
confirmation prompt, whenever the form is not disabled by an in-flight request
|
confirmation prompt, whenever the form is not disabled by an in-flight request
|
||||||
And a 401 response is handled entirely by useApi's existing global handling
|
And a 401 response is handled entirely by useApi's existing global handling
|
||||||
(features/api_client_global_error_handling.feature): the session is cleared and the app
|
(features/api_client_global_error_handling.feature): the session is cleared and the app
|
||||||
navigates to /login?redirect=<path>&reason=expired; this slice adds no draft-preservation
|
navigates to /login?redirect=<path>&reason=expired; this slice adds no draft-preservation
|
||||||
behavior for the modal's fields, unlike the editor's session-expiry handling
|
behavior for the modal's field, unlike the editor's session-expiry handling
|
||||||
|
|
||||||
Scenario: Opening the modal shows the Default state
|
Scenario: Opening the modal shows the Default state
|
||||||
Given the user is on /home
|
Given the user is on /home
|
||||||
@@ -57,7 +52,7 @@ Feature: Creating a new article from NewArticleModal
|
|||||||
Then NewArticleModal opens with title "New article" and the text "It's saved as a draft.
|
Then NewArticleModal opens with title "New article" and the text "It's saved as a draft.
|
||||||
Titles can't be changed later, so check it now."
|
Titles can't be changed later, so check it now."
|
||||||
And the Title field is empty, focused, and its counter reads "0 / 200"
|
And the Title field is empty, focused, and its counter reads "0 / 200"
|
||||||
And the First paragraph field is empty
|
And there is no First paragraph field
|
||||||
And "Create draft" is present but the form has not been submitted
|
And "Create draft" is present but the form has not been submitted
|
||||||
|
|
||||||
Scenario: Validation — a title under 3 characters on blur
|
Scenario: Validation — a title under 3 characters on blur
|
||||||
@@ -67,34 +62,23 @@ Feature: Creating a new article from NewArticleModal
|
|||||||
And the counter reads "2 / 200" in its error style
|
And the counter reads "2 / 200" in its error style
|
||||||
And no request is sent
|
And no request is sent
|
||||||
|
|
||||||
Scenario: Validation — an empty first paragraph on blur
|
Scenario: Validation — submitting an invalid title sends nothing
|
||||||
Given the modal is open with a valid Title
|
Given the modal is open with Title "Ti"
|
||||||
When the user leaves the First paragraph field empty and moves focus away
|
|
||||||
Then the First paragraph field shows the error "Add a first paragraph. It can be a single
|
|
||||||
sentence."
|
|
||||||
And no request is sent
|
|
||||||
|
|
||||||
Scenario: Validation — submitting with both fields invalid shows both errors and sends nothing
|
|
||||||
Given the modal is open with Title "Ti" and an empty First paragraph
|
|
||||||
When the user activates "Create draft"
|
When the user activates "Create draft"
|
||||||
Then the Title field shows "Use at least 3 characters." and the First paragraph field shows
|
Then the Title field shows "Use at least 3 characters."
|
||||||
"Add a first paragraph. It can be a single sentence."
|
|
||||||
And POST /v1/article/ is never sent
|
And POST /v1/article/ is never sent
|
||||||
|
|
||||||
Scenario: Submitting disables the form and cannot be dismissed
|
Scenario: Submitting disables the form and cannot be dismissed
|
||||||
Given the modal is open with Title "Choosing tiles for a small bathroom" and First paragraph
|
Given the modal is open with Title "Choosing tiles for a small bathroom"
|
||||||
"Small rooms show every grout line, so we start with the floor."
|
|
||||||
When the user activates "Create draft"
|
When the user activates "Create draft"
|
||||||
Then POST /v1/article/ is sent with JSON {"title": "Choosing tiles for a small bathroom",
|
Then POST /v1/article/ is sent with JSON {"title": "Choosing tiles for a small bathroom"}
|
||||||
"body": "Small rooms show every grout line, so we start with the floor."}
|
And the Title field becomes disabled, "Cancel" becomes disabled, and the confirm button reads
|
||||||
And both fields become disabled, "Cancel" becomes disabled, and the confirm button reads
|
|
||||||
"Creating…" with a loading indicator
|
"Creating…" with a loading indicator
|
||||||
And pressing Esc or clicking the backdrop does not close the modal
|
And pressing Esc or clicking the backdrop does not close the modal
|
||||||
|
|
||||||
Scenario: A successful create closes the modal and hands off to the editor with a toast
|
Scenario: A successful create closes the modal and hands off to the editor with a toast
|
||||||
Given the user is on /home with the modal open, Title "Choosing tiles for a small bathroom"
|
Given the user is on /home with the modal open, Title "Choosing tiles for a small bathroom",
|
||||||
and First paragraph "Small rooms show every grout line, so we start with the floor.", and
|
and "Create draft" has been activated
|
||||||
"Create draft" has been activated
|
|
||||||
When POST /v1/article/ resolves 201 with the created article, id 42, is_online false
|
When POST /v1/article/ resolves 201 with the created article, id 42, is_online false
|
||||||
Then the modal closes
|
Then the modal closes
|
||||||
And the app navigates to /article/42/edit
|
And the app navigates to /article/42/edit
|
||||||
@@ -104,33 +88,29 @@ Feature: Creating a new article from NewArticleModal
|
|||||||
|
|
||||||
Scenario: Title rejected — a 400 that got past this form's own check
|
Scenario: Title rejected — a 400 that got past this form's own check
|
||||||
Given the modal is open with Title "Choosing tiles for a small bathroom" (already valid by
|
Given the modal is open with Title "Choosing tiles for a small bathroom" (already valid by
|
||||||
this form's own rule) and First paragraph "Small rooms show every grout line, so we start
|
this form's own rule), and "Create draft" has been activated
|
||||||
with the floor.", and "Create draft" has been activated
|
|
||||||
When POST /v1/article/ resolves 400
|
When POST /v1/article/ resolves 400
|
||||||
Then the modal re-enables, keeping both field values
|
Then the modal re-enables, keeping the title
|
||||||
And the Title field shows "Check this title and try again." in place of its help text
|
And the Title field shows "Check this title and try again." in place of its help text
|
||||||
And an alert reads "Something in the form isn't valid. Check the highlighted fields."
|
And an alert reads "Something in the form isn't valid. Check the highlighted fields."
|
||||||
And the First paragraph field shows no error
|
|
||||||
|
|
||||||
Scenario Outline: Error — a 500 or a network failure keeps the text and offers to retry
|
Scenario Outline: Error — a 500 or a network failure keeps the text and offers to retry
|
||||||
Given the modal is open with Title "Choosing tiles for a small bathroom" and First paragraph
|
Given the modal is open with Title "Choosing tiles for a small bathroom", and "Create draft"
|
||||||
"Small rooms show every grout line, so we start with the floor.", and "Create draft" has
|
has been activated
|
||||||
been activated
|
|
||||||
When POST /v1/article/ <failure>
|
When POST /v1/article/ <failure>
|
||||||
Then the modal re-enables, keeping both field values
|
Then the modal re-enables, keeping the title
|
||||||
And an alert reads "Couldn't create the article. Your text is still here. Try again in a
|
And an alert reads "Couldn't create the article. Your text is still here. Try again in a
|
||||||
moment."
|
moment."
|
||||||
And neither field shows a field-level error
|
And the Title field shows no field-level error
|
||||||
|
|
||||||
Examples:
|
Examples:
|
||||||
| failure |
|
| failure |
|
||||||
| resolves with a 500 response |
|
| resolves with a 500 response |
|
||||||
| never reaches the server |
|
| never reaches the server |
|
||||||
|
|
||||||
Scenario: Retrying after an Error succeeds
|
Scenario: Retrying after an Error succeeds
|
||||||
Given the modal is in the Error state after a 500, with Title "Choosing tiles for a small
|
Given the modal is in the Error state after a 500, with Title "Choosing tiles for a small
|
||||||
bathroom" and First paragraph "Small rooms show every grout line, so we start with the
|
bathroom" still in the field
|
||||||
floor." still in the fields
|
|
||||||
When the user activates "Create draft" again
|
When the user activates "Create draft" again
|
||||||
Then POST /v1/article/ is sent again with the same JSON body
|
Then POST /v1/article/ is sent again with the same JSON body
|
||||||
When it resolves 201 with the created article, id 42
|
When it resolves 201 with the created article, id 42
|
||||||
@@ -138,9 +118,8 @@ Feature: Creating a new article from NewArticleModal
|
|||||||
success, icon i-lucide-circle-check, title "Draft created", description "\"Choosing tiles
|
success, icon i-lucide-circle-check, title "Draft created", description "\"Choosing tiles
|
||||||
for a small bathroom\" is saved as a draft.", id "article-created-42"
|
for a small bathroom\" is saved as a draft.", id "article-created-42"
|
||||||
|
|
||||||
Scenario: Cancel discards the fields with no confirmation
|
Scenario: Cancel discards the title with no confirmation
|
||||||
Given the modal is open with Title "Choosing tiles for a small bathroom" and First paragraph
|
Given the modal is open with Title "Choosing tiles for a small bathroom"
|
||||||
"Small rooms show every grout line, so we start with the floor."
|
|
||||||
When the user activates "Cancel"
|
When the user activates "Cancel"
|
||||||
Then the modal closes immediately, with no confirmation prompt
|
Then the modal closes immediately, with no confirmation prompt
|
||||||
And no request is sent
|
And no request is sent
|
||||||
@@ -7,8 +7,10 @@ Only HomeView.vue is wired as a real `created` consumer in this slice: it listen
|
|||||||
the `/article/new` route stay pointed at the current ArticleView.vue placeholder until that page
|
the `/article/new` route stay pointed at the current ArticleView.vue placeholder until that page
|
||||||
exists; don't wire a `created` handler there yet.
|
exists; don't wire a `created` handler there yet.
|
||||||
|
|
||||||
The confirm button's label changes from the placeholder's "Create article" to the design's
|
The modal is title-only: the First paragraph field is removed and the POST body is `{"title": "..."}`
|
||||||
"Create draft" — this is a deliberate copy change, not a leftover.
|
with no `body` key (see features/article_body_unlimited.feature).
|
||||||
|
|
||||||
|
The confirm button's label is the design's "Create draft".
|
||||||
|
|
||||||
The Created toast uses `useToast().add({ id: 'article-created-{id}', color: 'success', icon:
|
The Created toast uses `useToast().add({ id: 'article-created-{id}', color: 'success', icon:
|
||||||
'i-lucide-circle-check', title: 'Draft created', description: '"{title}" is saved as a draft.' })`,
|
'i-lucide-circle-check', title: 'Draft created', description: '"{title}" is saved as a draft.' })`,
|
||||||
@@ -20,77 +22,70 @@ section (success/info close after 5 s).
|
|||||||
Mock `useApi`'s `request` for `POST /v1/article/` per case; no real backend, no httptest server.
|
Mock `useApi`'s `request` for `POST /v1/article/` per case; no real backend, no httptest server.
|
||||||
Mount HomePage (which owns NewArticleModal) inside DashboardShell with a resolved verified session,
|
Mount HomePage (which owns NewArticleModal) inside DashboardShell with a resolved verified session,
|
||||||
and a test router at `/home`. Sample data throughout: title "Choosing tiles for a small bathroom",
|
and a test router at `/home`. Sample data throughout: title "Choosing tiles for a small bathroom",
|
||||||
first paragraph "Small rooms show every grout line, so we start with the floor.", created article
|
created article id 42, is_online false.
|
||||||
id 42, is_online false.
|
|
||||||
|
|
||||||
1. **Default state on open** — click "New article"; assert the modal shows title "New article",
|
1. **Default state on open** — click "New article"; assert the modal shows title "New article",
|
||||||
the intro text, an empty focused Title field with counter "0 / 200" and help "3 to 200
|
the intro text, an empty focused Title field with counter "0 / 200" and help "3 to 200
|
||||||
characters.", an empty First paragraph field with its placeholder and help, "Cancel" and
|
characters.", "Cancel" and "Create draft", and no First paragraph field.
|
||||||
"Create draft".
|
2. **Blur validation** — type "Ti" into Title and blur; assert the error "Use at least 3
|
||||||
2. **Blur validation, Title** — type "Ti" into Title and blur; assert the error "Use at least 3
|
|
||||||
characters." replaces the help text and the counter "2 / 200" is in its error style; assert no
|
characters." replaces the help text and the counter "2 / 200" is in its error style; assert no
|
||||||
`request` call.
|
`request` call.
|
||||||
3. **Blur validation, First paragraph** — with a valid Title, leave First paragraph empty and
|
3. **Submit with an invalid title** — Title "Ti", click "Create draft"; assert the error shows and
|
||||||
blur; assert "Add a first paragraph. It can be a single sentence." appears; assert no
|
`request` is never called.
|
||||||
`request` call.
|
4. **Submitting state** — fill Title validly, click "Create draft"; assert `request` is called
|
||||||
4. **Submit with both fields invalid** — Title "Ti", empty First paragraph, click "Create draft";
|
once with `POST /v1/article/` and the JSON body exactly `{"title": "Choosing tiles for a small
|
||||||
assert both errors show and `request` is never called.
|
bathroom"}`; assert Title and Cancel become disabled, the confirm button reads "Creating…";
|
||||||
5. **Submitting state** — fill both fields validly, click "Create draft"; assert `request` is
|
assert pressing Escape and clicking the backdrop do not close the modal while unresolved.
|
||||||
called once with `POST /v1/article/` and the exact JSON body; assert both fields and Cancel
|
5. **Successful create hands off** — from Submitting, resolve `request` 201 with the fixture
|
||||||
become disabled, the confirm button reads "Creating…"; assert pressing Escape and clicking the
|
|
||||||
backdrop do not close the modal while unresolved.
|
|
||||||
6. **Successful create hands off** — from Submitting, resolve `request` 201 with the fixture
|
|
||||||
article (id 42); assert the modal closes; assert the router navigated to `/article/42/edit`;
|
article (id 42); assert the modal closes; assert the router navigated to `/article/42/edit`;
|
||||||
assert a toast was raised with id "article-created-42", color success, icon
|
assert a toast was raised with id "article-created-42", color success, icon
|
||||||
"i-lucide-circle-check", title "Draft created", and description "\"Choosing tiles for a small
|
"i-lucide-circle-check", title "Draft created", and description "\"Choosing tiles for a small
|
||||||
bathroom\" is saved as a draft."
|
bathroom\" is saved as a draft."
|
||||||
7. **Title rejected (400)** — from Submitting, resolve `request` rejecting with `ApiError(400)`;
|
6. **Title rejected (400)** — from Submitting, resolve `request` rejecting with `ApiError(400)`;
|
||||||
assert both field values are kept, the Title field shows "Check this title and try again.",
|
assert the title is kept, the Title field shows "Check this title and try again.", and an alert
|
||||||
an alert reads "Something in the form isn't valid. Check the highlighted fields.", and the
|
reads "Something in the form isn't valid. Check the highlighted fields."
|
||||||
First paragraph field shows no error.
|
7. **Error, Examples-driven** — from Submitting, (a) resolve `request` rejecting with
|
||||||
8. **Error, Examples-driven** — from Submitting, (a) resolve `request` rejecting with
|
`ApiError(500)`, (b) resolve it rejecting with `NetworkError`; in each, assert the title is
|
||||||
`ApiError(500)`, (b) resolve it rejecting with `NetworkError`; in each, assert both field values
|
kept, the alert reads "Couldn't create the article. Your text is still here. Try again in a
|
||||||
are kept, the alert reads "Couldn't create the article. Your text is still here. Try again in a
|
moment.", and the field shows no error.
|
||||||
moment.", and neither field shows an error.
|
8. **Retry after Error succeeds** — from the Error state (500), click "Create draft" again; assert
|
||||||
9. **Retry after Error succeeds** — from the Error state (500), click "Create draft" again; assert
|
|
||||||
`request` is called a second time with the same JSON body; resolve 201 with the fixture; assert
|
`request` is called a second time with the same JSON body; resolve 201 with the fixture; assert
|
||||||
the modal closes, the router navigated to `/article/42/edit`, and the same "Draft created" toast
|
the modal closes, the router navigated to `/article/42/edit`, and the same "Draft created" toast
|
||||||
(id "article-created-42") is raised.
|
(id "article-created-42") is raised.
|
||||||
10. **Cancel discards** — fill both fields, click "Cancel"; assert the modal closes immediately
|
9. **Cancel discards** — fill Title, click "Cancel"; assert the modal closes immediately with no
|
||||||
with no confirmation UI, and `request` was never called.
|
confirmation UI, and `request` was never called.
|
||||||
|
|
||||||
## Visual (manual verification — desktop and mobile, light and dark)
|
## Visual (manual verification — desktop and mobile, light and dark)
|
||||||
|
|
||||||
Reference: `docs/design/screens/new-article.md` and `docs/design/source/RenewCMS Screens
|
Reference: `docs/design/screens/new-article.md` and `docs/design/source/RenewCMS Screens
|
||||||
Back-office.dc.html`, group "New article". Run `task visual:check -- new-article` for each state
|
Back-office.dc.html`, group "New article". Run `task visual:check -- new-article` for each state
|
||||||
below and compare against the board frame; add each state's mock setup to `web/visual/states.ts`
|
below and compare against the board frame; add each state's mock setup to `web/visual/states.ts`
|
||||||
first, reusing this slice's sample data (title "Choosing tiles for a small bathroom", first
|
first, reusing this slice's sample data (title "Choosing tiles for a small bathroom"). This screen
|
||||||
paragraph "Small rooms show every grout line, so we start with the floor."). This screen has no
|
has no time-dependent content, so no fixed `now` is needed. The board frames may still draw a body
|
||||||
time-dependent content, so no fixed `now` is needed.
|
line in Submitting, Title rejected and Error; the design .md files are authoritative for the
|
||||||
|
title-only modal and the boards are a known follow-up.
|
||||||
|
|
||||||
- [ ] Default: empty, focused Title with counter "0 / 200", empty First paragraph, help text on
|
- [ ] Default: empty, focused Title with counter "0 / 200", help text, "Cancel" / "Create draft".
|
||||||
both fields, "Cancel" / "Create draft".
|
- [ ] Validation: Title "Ti" with counter "2 / 200" in error and "Use at least 3 characters."
|
||||||
- [ ] Validation: Title "Ti" with counter "2 / 200" in error and "Use at least 3 characters.";
|
- [ ] Submitting: Title filled and disabled, confirm reads "Creating…" with its loading state.
|
||||||
First paragraph error "Add a first paragraph. It can be a single sentence."
|
- [ ] Title rejected (400): Title filled, error "Check this title and try again.", alert
|
||||||
- [ ] Submitting: both fields filled and disabled, confirm reads "Creating…" with its loading
|
"Something in the form isn't valid. Check the highlighted fields."
|
||||||
state.
|
- [ ] Error: Title filled, alert "Couldn't create the article. Your text is still here. Try
|
||||||
- [ ] Title rejected (400): both fields filled, Title error "Check this title and try again.",
|
|
||||||
alert "Something in the form isn't valid. Check the highlighted fields."
|
|
||||||
- [ ] Error: both fields filled, alert "Couldn't create the article. Your text is still here. Try
|
|
||||||
again in a moment.", no field-level error.
|
again in a moment.", no field-level error.
|
||||||
- [ ] Created: no board frame; verified by Vitest (toast copy + navigation).
|
- [ ] Created: no board frame; verified by Vitest (toast copy + navigation).
|
||||||
- [ ] Keyboard/focus: Tab reaches Title (already focused on open) → First paragraph → Cancel →
|
- [ ] Keyboard/focus: Tab reaches Title (already focused on open) → Cancel → Create draft; Esc
|
||||||
Create draft; Esc closes the modal in every dismissible state and is blocked while
|
closes the modal in every dismissible state and is blocked while Submitting; the counter's
|
||||||
Submitting; the counter's live region announces only when its error/warn threshold is
|
live region announces only when its error threshold is crossed, not on every keystroke,
|
||||||
crossed, not on every keystroke, per CharacterCounter's a11y spec.
|
per CharacterCounter's a11y spec.
|
||||||
- [ ] Motion: modal open/close follows the standard 240 ms timing and stops under reduced motion.
|
- [ ] Motion: modal open/close follows the standard 240 ms timing and stops under reduced motion.
|
||||||
|
|
||||||
## Manual verification
|
## Manual verification
|
||||||
|
|
||||||
- **Real POST /v1/article/ round trip against a running server** — Vitest only mocks `useApi`;
|
- **Real POST /v1/article/ round trip against a running server** — Vitest only mocks `useApi`;
|
||||||
confirm the real 201/400/500 responses and that a genuinely-created article is retrievable at
|
confirm the real 201/400/500 responses, that a title-only create returns 201 with an empty body,
|
||||||
`/article/{id}/edit` against `task dev` with a live SQLite file, since automated tests never
|
and that the created article is retrievable at `/article/{id}/edit` against `task dev` with a
|
||||||
exercise the real Go handler or `CreateArticleUseCase`.
|
live SQLite file, since automated tests never exercise the real Go handler or
|
||||||
|
`CreateArticleUseCase`.
|
||||||
- **Toast placement and stacking on a live app** — confirm the "Draft created" toast's real
|
- **Toast placement and stacking on a live app** — confirm the "Draft created" toast's real
|
||||||
position, duration and stacking behavior (per docs/design/components.md's Toast rules) against
|
position, duration and stacking behavior (per docs/design/components.md's Toast rules) against
|
||||||
a running app, since Vitest only asserts that `useToast().add` was called with the right
|
a running app, since Vitest only asserts that `useToast().add` was called with the right
|
||||||
|
|||||||
@@ -8,8 +8,8 @@ Feature: Public and authenticated article listing
|
|||||||
|
|
||||||
Background:
|
Background:
|
||||||
Given internal/domain/article.Article has a json "is_online" field
|
Given internal/domain/article.Article has a json "is_online" field
|
||||||
And ListArticlesUseCase.ListOnlineArticles filters article.Filters{IsOnline: true} and
|
And ListArticlesUseCase.ListArticlesPage filters article.Filters{IsOnline: true} for an unverified
|
||||||
ListArticlesUseCase.ListAllArticles applies no filter, both already implemented
|
caller and applies no visibility filter for a verified one
|
||||||
And before this slice, GET /v1/article/ sits inside the jwtauth Verifier + Authenticator group
|
And before this slice, GET /v1/article/ sits inside the jwtauth Verifier + Authenticator group
|
||||||
in api/router.go along with GET /v1/article/{id}, POST /v1/article/ and DELETE /v1/article/{id},
|
in api/router.go along with GET /v1/article/{id}, POST /v1/article/ and DELETE /v1/article/{id},
|
||||||
so an anonymous request to any of them answers 401, not an online-only list
|
so an anonymous request to any of them answers 401, not an online-only list
|
||||||
@@ -19,7 +19,7 @@ Feature: Public and authenticated article listing
|
|||||||
And a later slice, features/public_article_read.feature, moves GET /v1/article/{id} into the
|
And a later slice, features/public_article_read.feature, moves GET /v1/article/{id} into the
|
||||||
same Verifier-only group as GET /v1/article/, so the 401 Examples table below is updated
|
same Verifier-only group as GET /v1/article/, so the 401 Examples table below is updated
|
||||||
accordingly
|
accordingly
|
||||||
And Handler.ListArticles decides between ListAllArticles and ListOnlineArticles by checking the
|
And Handler.ListArticles decides between a verified and an unverified ListArticlesPage call by checking the
|
||||||
request for a valid jwt, read with jwtauth.FromContext from the token the router-level
|
request for a valid jwt, read with jwtauth.FromContext from the token the router-level
|
||||||
jwtauth.Verifier (header and cookie sources) placed in the request context, rather than
|
jwtauth.Verifier (header and cookie sources) placed in the request context, rather than
|
||||||
requiring the router-level Authenticator middleware; article.NewHandler takes no token
|
requiring the router-level Authenticator middleware; article.NewHandler takes no token
|
||||||
|
|||||||
@@ -0,0 +1,39 @@
|
|||||||
|
Feature: Registering lands on the Check your email screen
|
||||||
|
As a visitor who has just created the owner account
|
||||||
|
I want to see the "Check your email" screen
|
||||||
|
So that I know to open the verification link, instead of being sent to log in with "Your session expired"
|
||||||
|
|
||||||
|
Background:
|
||||||
|
Given /register is a "public" route and /register/pending is a "session" route, per docs/design/routes.md
|
||||||
|
And POST /v1/auth/register is public and, on 200, sets the HttpOnly jwt cookie of the new unverified account
|
||||||
|
And the session store caches the result of GET /v1/auth/me, and a cached 401 is stored as session null with status "ready"
|
||||||
|
And RegisterView, on a 200 from POST /v1/auth/register, writes the submitted email to sessionStorage "renewcms:pendingEmail", awaits session.retry(), then navigates to /register/pending
|
||||||
|
|
||||||
|
Scenario: Register after the session store cached an anonymous 401
|
||||||
|
Given the visitor opened "/" first, GET /v1/auth/me answered 401, and the session store holds null with status "ready"
|
||||||
|
And the visitor is on /register
|
||||||
|
When the visitor submits username "marta", email "marta@renew.example" and a password of 8 or more characters
|
||||||
|
And POST /v1/auth/register answers 200
|
||||||
|
And the following GET /v1/auth/me answers 200 with verified false and email "marta@renew.example"
|
||||||
|
Then the session store holds an unverified account
|
||||||
|
And the app is on /register/pending, not /login
|
||||||
|
And no "Your session expired" alert is shown
|
||||||
|
And a ResultPanel titled "Check your email" reads "We sent a verification link to marta@renew.example. It expires in 2 hours."
|
||||||
|
And its actions are "Log out" and "Cancel registration"
|
||||||
|
|
||||||
|
Scenario: Register as the first page of the visit
|
||||||
|
Given the session store is idle and the visitor opened /register directly
|
||||||
|
When the visitor submits the form and POST /v1/auth/register answers 200
|
||||||
|
Then the app is on /register/pending with the "Check your email" panel for "marta@renew.example"
|
||||||
|
|
||||||
|
Scenario Outline: Register failures never navigate
|
||||||
|
Given the visitor is on /register with a valid form
|
||||||
|
When POST /v1/auth/register answers <status>
|
||||||
|
Then the app stays on /register
|
||||||
|
And <visible>
|
||||||
|
And GET /v1/auth/me is not called
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| status | visible |
|
||||||
|
| 403 | the "This site already has an owner" ResultPanel is shown |
|
||||||
|
| 500 | the error alert "Couldn't create the account" is shown |
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
# QA: Registering lands on the Check your email screen
|
||||||
|
|
||||||
|
## Automated (Vitest + Vue Test Utils, `task test:web`)
|
||||||
|
|
||||||
|
Mock `fetch` per case. Use a real router (`@/router`), a fresh Pinia and AuthShell with the Nuxt UI
|
||||||
|
plugin, as in RegisterView.spec.ts. No Go test: the API already sets the cookie on register.
|
||||||
|
|
||||||
|
1. **Stale anonymous session** (regression) — call `useSessionStore().check()` with `GET /v1/auth/me`
|
||||||
|
mocked to 401 so the store holds null / "ready". Mount RegisterView at /register, fill valid
|
||||||
|
values, submit. Mock `POST /v1/auth/register` to 200 and the next `GET /v1/auth/me` to 200
|
||||||
|
`{ verified: false, email: "marta@renew.example" }`. Assert after `flushPromises()` that the
|
||||||
|
current path is `/register/pending`, `/login` was never visited (no `reason=expired`), and
|
||||||
|
`sessionStorage["renewcms:pendingEmail"]` is "marta@renew.example". Must fail on the current code.
|
||||||
|
2. **Fresh store** — store idle, `/me` mocked to 200 unverified; assert the path is /register/pending.
|
||||||
|
3. **Failures** — 403 shows the owner-exists panel, 500 shows the error alert; in both the path stays
|
||||||
|
/register and `/me` is never fetched.
|
||||||
|
4. Update the existing test at RegisterView.spec.ts:328-370 so its fetch router also handles
|
||||||
|
`GET /v1/auth/me`.
|
||||||
|
|
||||||
|
## Visual
|
||||||
|
|
||||||
|
No new states. `task visual:check -- register` and `-- pending` must stay green.
|
||||||
|
|
||||||
|
## Manual
|
||||||
|
|
||||||
|
On a fresh install open `/`, go to Create the owner account, register, and confirm the "Check your
|
||||||
|
email" panel appears. Real SMTP delivery of the verification mail is manual.
|
||||||
@@ -0,0 +1,122 @@
|
|||||||
|
Feature: Shell design tokens and selected nav contrast
|
||||||
|
|
||||||
|
As the maintainer of RenewCMS
|
||||||
|
I want the new --rc-* tokens in the SPA and every selected nav item drawn in sand with on-sand text
|
||||||
|
So that the sidebar and drawer stay readable in both themes and match docs/design
|
||||||
|
|
||||||
|
Background:
|
||||||
|
Given web/src/assets/main.css declares the --rc-* tokens of docs/design/foundations.md
|
||||||
|
"New tokens", light values in :root and dark values in .dark
|
||||||
|
And DashboardShell renders the nav from web/src/components/DashboardShell.vue, with "Settings"
|
||||||
|
as the parent row (/settings) and a "Media" group holding "Variants"
|
||||||
|
(/settings/media/variants) and "Cache" (/settings/media/cache)
|
||||||
|
And the session role is "owner", so the Settings children are present
|
||||||
|
And a selected row is a link whose route is current, carrying aria-current="page"
|
||||||
|
|
||||||
|
Scenario Outline: The new tokens exist with the values given in foundations.md
|
||||||
|
When web/src/assets/main.css is loaded in the <theme> theme
|
||||||
|
Then <token> resolves to <value>
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| token | theme | value |
|
||||||
|
| --rc-sand | light | #e8dfd1 |
|
||||||
|
| --rc-sand | dark | #d4c5b0 |
|
||||||
|
| --rc-on-sand | light | #111111 |
|
||||||
|
| --rc-on-sand | dark | #111111 |
|
||||||
|
| --rc-success-soft | light | #eaefea |
|
||||||
|
| --rc-success-soft | dark | #1f241f |
|
||||||
|
| --rc-info-soft | light | #ebeef0 |
|
||||||
|
| --rc-info-soft | dark | #202428 |
|
||||||
|
| --rc-warning-soft | light | #f0ede6 |
|
||||||
|
| --rc-warning-soft | dark | #2a251e |
|
||||||
|
| --rc-error-soft | light | #f3eae9 |
|
||||||
|
| --rc-error-soft | dark | #2c201f |
|
||||||
|
| --rc-overlay | light | rgb(10 10 10 / 0.4) |
|
||||||
|
| --rc-overlay | dark | rgb(0 0 0 / 0.6) |
|
||||||
|
| --rc-shadow-pop | light | 0 4px 16px rgb(17 17 17 / 0.08), 0 1px 2px rgb(17 17 17 / 0.06) |
|
||||||
|
| --rc-shadow-pop | dark | 0 4px 16px rgb(0 0 0 / 0.5) |
|
||||||
|
| --rc-shadow-modal | light | 0 16px 48px rgb(17 17 17 / 0.18) |
|
||||||
|
| --rc-shadow-modal | dark | 0 16px 48px rgb(0 0 0 / 0.6) |
|
||||||
|
|
||||||
|
Scenario: No --ui-* token and no --rc-canvas are introduced
|
||||||
|
When web/src/assets/main.css is compared with docs/design/foundations.md
|
||||||
|
Then no --ui-* token value is changed
|
||||||
|
And --rc-canvas is not declared
|
||||||
|
|
||||||
|
Scenario Outline: N1 Parent selected: Settings is filled in sand with on-sand text and icon
|
||||||
|
Given the current route is /settings
|
||||||
|
And the theme is <theme>
|
||||||
|
When DashboardShell renders the desktop sidebar
|
||||||
|
Then the "Settings" row has aria-current="page"
|
||||||
|
And its background is --rc-sand and its label and icon colour are --rc-on-sand
|
||||||
|
And the "Media" group is visible with "Variants" and "Cache" unselected
|
||||||
|
And neither child row uses --rc-sand
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| theme |
|
||||||
|
| light |
|
||||||
|
| dark |
|
||||||
|
|
||||||
|
Scenario Outline: N2 and N3 Child selected: the child is filled and the parent is unfilled and bold
|
||||||
|
Given the current route is <path>
|
||||||
|
And the theme is <theme>
|
||||||
|
When DashboardShell renders the desktop sidebar
|
||||||
|
Then the "<child>" row has aria-current="page", background --rc-sand and label and icon colour --rc-on-sand
|
||||||
|
And the "Settings" row is not filled, has no aria-current, uses --ui-text-highlighted at weight 500 and shows the chevron pointing down
|
||||||
|
And the other child row is not filled
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| path | child | theme |
|
||||||
|
| /settings/media/variants | Variants | light |
|
||||||
|
| /settings/media/variants | Variants | dark |
|
||||||
|
| /settings/media/cache | Cache | light |
|
||||||
|
| /settings/media/cache | Cache | dark |
|
||||||
|
|
||||||
|
Scenario Outline: Hover, focus and active on a selected row keep sand and on-sand
|
||||||
|
Given the "<row>" row is selected on <path>
|
||||||
|
And the theme is <theme>
|
||||||
|
When the row is <interaction>
|
||||||
|
Then its background stays --rc-sand and its label and icon colour stay --rc-on-sand
|
||||||
|
And no white or --ui-text-muted colour is applied to its label or icon
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| row | path | interaction | theme |
|
||||||
|
| Settings | /settings | hovered | dark |
|
||||||
|
| Settings | /settings | focus-visible | dark |
|
||||||
|
| Settings | /settings | pressed | dark |
|
||||||
|
| Settings | /settings | hovered | light |
|
||||||
|
| Variants | /settings/media/variants | hovered | dark |
|
||||||
|
| Variants | /settings/media/variants | pressed | light |
|
||||||
|
| Cache | /settings/media/cache | focus-visible | dark |
|
||||||
|
|
||||||
|
Scenario: Focus on a selected row adds a 2 px --ui-primary outline
|
||||||
|
Given the "Settings" row is selected on /settings
|
||||||
|
When the row receives keyboard focus
|
||||||
|
Then it has a 2 px --ui-primary focus outline
|
||||||
|
And its background is still --rc-sand
|
||||||
|
|
||||||
|
Scenario Outline: N4 and N5 The mobile drawer uses the same selected treatment
|
||||||
|
Given the viewport is 390 x 844 and the theme is <theme>
|
||||||
|
And the current route is <path>
|
||||||
|
When the Menu button is activated
|
||||||
|
Then the drawer rows are 44 px tall
|
||||||
|
And the "<selected>" row has aria-current="page", background --rc-sand and label and icon colour --rc-on-sand
|
||||||
|
And <parent_state>
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| path | selected | parent_state | theme |
|
||||||
|
| /settings | Settings | the Media group lists Variants and Cache, unselected | light |
|
||||||
|
| /settings | Settings | the Media group lists Variants and Cache, unselected | dark |
|
||||||
|
| /settings/media/variants | Variants | the "Settings" row is unfilled and bold | light |
|
||||||
|
| /settings/media/variants | Variants | the "Settings" row is unfilled and bold | dark |
|
||||||
|
|
||||||
|
Scenario Outline: Other selected nav items use the same pairing
|
||||||
|
Given the current route is <path> and the theme is dark
|
||||||
|
When DashboardShell renders
|
||||||
|
Then the "<row>" row has background --rc-sand and label and icon colour --rc-on-sand
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| path | row |
|
||||||
|
| /home | Home |
|
||||||
|
| /users | Users |
|
||||||
|
| /activity | Activity |
|
||||||
@@ -0,0 +1,37 @@
|
|||||||
|
# QA: Shell design tokens and selected nav contrast (SPA only)
|
||||||
|
|
||||||
|
No /v1 behaviour changes. There is no httptest part.
|
||||||
|
|
||||||
|
## Automated (Vitest + Vue Test Utils, `task test:web`)
|
||||||
|
|
||||||
|
Mount DashboardShell with a test router and a resolved session (role "owner"). Mock the /v1 calls the shell issues (/v1/auth/me, and the update-check call if the shell makes one) so none go unmocked. Do not freeze the system date.
|
||||||
|
|
||||||
|
1. Token declarations: read web/src/assets/main.css as text; assert each token/theme/value row of the Examples table is declared in :root (light) or .dark (dark), and that --rc-canvas is absent.
|
||||||
|
2. Parent selected (N1): route /settings; the Settings link has aria-current="page" and the sand and on-sand classes (bg-(--rc-sand), text-(--rc-on-sand), or the equivalent in navUi); the Variants and Cache links have neither.
|
||||||
|
3. Child selected (N2, N3): routes /settings/media/variants and /settings/media/cache; the child link has the sand classes and aria-current; the Settings link has no sand class, no aria-current, the text-highlighted and font-medium classes, and the chevron open state (rotate-90).
|
||||||
|
4. Selected-row interaction classes: for the selected link, assert the class list includes the sand and on-sand variants for hover:, focus-visible: and active:, and includes no text-muted, text-white or text-inverted for the active state. Assert the leading icon inherits the on-sand colour.
|
||||||
|
5. Dark and light: repeat 2 and 3 with the `dark` class on the document root; assert the same class contract, since the tokens carry the theme.
|
||||||
|
6. Mobile drawer (N4, N5): open the drawer; assert 44 px row height classes and the same selected contract for /settings and /settings/media/variants.
|
||||||
|
7. Other routes: /home, /users, /activity selected links have the sand contract.
|
||||||
|
|
||||||
|
## Visual (`task visual:check`, gate: every capture within 10 %)
|
||||||
|
|
||||||
|
Each state's mocks reuse the board's own sample data from the "Settings navigation" frame in `RenewCMS Screens Back-office.dc.html`.
|
||||||
|
|
||||||
|
- `task visual:check -- settings` (the Settings screen states in docs/design/screens/settings.md and states.md)
|
||||||
|
- `task visual:check -- image-variants` for the nav states N1 to N5 (docs/design/screens/image-variants.md, "Settings navigation"; the screen key in web/visual/states.ts is `image-variants`).
|
||||||
|
|
||||||
|
Each capture is desktop 1440x900 and mobile 390x844, in light and dark. N4 and N5 are the mobile drawer states. None of these states are clock-sensitive.
|
||||||
|
|
||||||
|
| State | Route / trigger | Must show |
|
||||||
|
|---|---|---|
|
||||||
|
| N1 | /settings | Settings filled in sand, Media group visible, children unselected |
|
||||||
|
| N2 | /settings/media/variants | Settings unfilled and bold, Variants filled |
|
||||||
|
| N3 | /settings/media/cache | Settings unfilled and bold, Cache filled |
|
||||||
|
| N4 | Menu button on /settings | Drawer, 44 px rows, Settings filled |
|
||||||
|
| N5 | Menu button on /settings/media/variants | Drawer, Variants filled |
|
||||||
|
|
||||||
|
## Manual checks (screenshots cannot cover)
|
||||||
|
|
||||||
|
- Keyboard: Tab through the sidebar. The focus ring is 2 px --ui-primary on a selected row, and the sand fill stays.
|
||||||
|
- Hover and pressed on a selected row in dark mode: the label and icon never turn white or muted.
|
||||||
@@ -65,13 +65,13 @@ Feature: Use case baseline characterization
|
|||||||
Then the result is the articles with ids <ids>, and no error
|
Then the result is the articles with ids <ids>, and no error
|
||||||
|
|
||||||
Examples:
|
Examples:
|
||||||
| method | ids |
|
| method | ids |
|
||||||
| ListOnlineArticles | 1,3 |
|
| ListArticlesPage unverified | 1,3 |
|
||||||
| ListAllArticles | 1,2,3 |
|
| ListArticlesPage verified | 1,2,3 |
|
||||||
|
|
||||||
Scenario: Listing articles on an empty repository returns an empty slice, not an error
|
Scenario: Listing articles on an empty repository returns an empty slice, not an error
|
||||||
Given an empty article repository fake
|
Given an empty article repository fake
|
||||||
When ListOnlineArticles is called
|
When ListArticlesPage is called
|
||||||
Then the result is an empty slice and no error
|
Then the result is an empty slice and no error
|
||||||
|
|
||||||
Scenario Outline: UpdateArticle delegates each operation to the repository and surfaces not-found for an unknown id
|
Scenario Outline: UpdateArticle delegates each operation to the repository and surfaces not-found for an unknown id
|
||||||
|
|||||||
@@ -0,0 +1,109 @@
|
|||||||
|
Feature: Variants and Media screens match the merged design: visual setups, and the variant form as a bottom sheet on mobile
|
||||||
|
|
||||||
|
As the maintainer of RenewCMS
|
||||||
|
I want the visual check to cover every state of the image variants screens, and the variant form to follow the overlay pattern
|
||||||
|
So that the SPA matches the merged design on desktop and mobile, in light and dark
|
||||||
|
|
||||||
|
Background:
|
||||||
|
Given the spec of record is docs/design/screens/image-variants.md, docs/design/screens/media.md, docs/design/screens/media-picker.md, docs/design/states.md, docs/design/routes.md and the overlay pattern of docs/design/components.md
|
||||||
|
And this slice is SPA only: no Go file, route or API contract changes
|
||||||
|
And the behaviours of features/image_variants_media_screens.feature, features/image_variants_screens.feature and features/image_variants_editor_picker.feature stay as they are except where this file says so
|
||||||
|
And the merged board is "RenewCMS Screens Back-office.dc.html" and web/visual/check.ts already points to it, with state names in the form "V1a · Loaded"
|
||||||
|
And every new English string has a French entry in web/src/i18n/messages.ts, the page uses Nuxt UI components and design tokens only, and no comment is added to any file
|
||||||
|
And the session is the owner "Marta Alves" unless a scenario says otherwise
|
||||||
|
|
||||||
|
Rule: Every state of the six groups has a visual setup that passes
|
||||||
|
|
||||||
|
Scenario Outline: A group of the merged board is fully covered
|
||||||
|
Given the group "<group>" of the merged board lists the states "<states>"
|
||||||
|
When "task visual:check -- image-variants" runs
|
||||||
|
Then each of those states has a setup in web/visual/states.ts keyed by its exact board name
|
||||||
|
And each capture prints PASS at desktop and mobile, in light and dark, within 10 %
|
||||||
|
And no /v1 call is left unmocked and no size mismatch is reported
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| group | states |
|
||||||
|
| Variants list | V1a to V1l |
|
||||||
|
| Add edit variant | V2a to V2k |
|
||||||
|
| Media library | V3a to V3f |
|
||||||
|
| Image detail | V4a to V4h |
|
||||||
|
| Cache panel | V5a to V5j |
|
||||||
|
| Editor picker | V6a to V6e |
|
||||||
|
|
||||||
|
Scenario: Setups reuse the board's own sample data
|
||||||
|
Then each setup mocks /v1 with the titles, names, sizes, counts and variant rows drawn in the board frame
|
||||||
|
|
||||||
|
Scenario: Clock-sensitive states are skipped, not tuned
|
||||||
|
Given a state whose rendering depends on the current date or time
|
||||||
|
Then its setup carries skip: 'clock-sensitive', the check prints SKIP and no Vitest spec freezes the system date
|
||||||
|
|
||||||
|
Scenario: No visual exception is added without the user's approval
|
||||||
|
Given a capture cannot get within 10 %
|
||||||
|
Then the setup or the SPA is fixed
|
||||||
|
And no "exception" entry is added unless the user approved it explicitly (approvedBy)
|
||||||
|
|
||||||
|
Scenario: The gate is hard
|
||||||
|
When any capture exceeds 10 %, a state has no setup, or a /v1 call is unmocked
|
||||||
|
Then "task visual:check -- image-variants" exits non-zero
|
||||||
|
|
||||||
|
Rule: The Media library V3 states render the existing variants filter and total-size sort
|
||||||
|
|
||||||
|
The filter, the sort and their request parameters already exist. Media code changes only if a V3 capture fails the check.
|
||||||
|
|
||||||
|
Scenario Outline: The V3 states render the filter and the sort
|
||||||
|
Given the 12-image fixture of features/image_variants_media_screens.feature
|
||||||
|
When the setup of "<state>" is loaded on /media
|
||||||
|
Then the SPA shows "<visible>"
|
||||||
|
And GET /v1/media/ carries "<request>"
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| state | visible | request |
|
||||||
|
| V3a · Grid with badges | "N variants" badges on cards with cached files, none on cards without, "All" selected | no variants parameter |
|
||||||
|
| V3b · Sort menu | sort menu open, "Largest total size (original + variants)" last | n/a |
|
||||||
|
| V3c · Filter: With variants, sorted by total size | "With variants" selected, meta lines "total · original + variants" | variants=with&sort=total_size |
|
||||||
|
| V3d · Filter: Without variants | "Without" selected, no variants badge | variants=without |
|
||||||
|
| V3e · Filter: nothing to show | "With variants" selected, empty cache, "No images with variants" | variants=with |
|
||||||
|
|
||||||
|
Scenario: Existing filter and sort behaviour is unchanged
|
||||||
|
Then the URL, request and meta-line behaviour of "The variants filter" and "Sorting by total size" in features/image_variants_media_screens.feature still holds
|
||||||
|
|
||||||
|
Rule: The variant form follows the overlay pattern
|
||||||
|
|
||||||
|
Scenario: Add variant is a right slide-over on desktop
|
||||||
|
Given the viewport is 640 px wide or more
|
||||||
|
When the admin activates "Add variant"
|
||||||
|
Then the form opens as a slide-over 960 px wide at the right over the scrim, full height, with the list behind it
|
||||||
|
And the header has the title and a close button (x icon, accessible name "Close")
|
||||||
|
And the form is on the left and the live preview on the right
|
||||||
|
|
||||||
|
Scenario: Add variant is a tall bottom sheet on mobile
|
||||||
|
Given the viewport is below 640 px
|
||||||
|
When the admin activates "Add variant"
|
||||||
|
Then the form opens as a bottom sheet flush to the bottom, full width, 92 % of the viewport height
|
||||||
|
And a grabber (36 × 4, --ui-border-accented) is drawn at the top, with a close x button (44 px) in the header
|
||||||
|
And it is not a full page: the list stays visible above the sheet behind the scrim
|
||||||
|
And the Preview section is stacked under the form and the body scrolls
|
||||||
|
And the footer is sticky with "Cancel" and the primary action sharing the width, 44 px high
|
||||||
|
|
||||||
|
Scenario: Edit uses the same container
|
||||||
|
When the admin chooses "Edit" on the row "hero"
|
||||||
|
Then the form opens in the same container as Add variant at the current viewport and the title is "Edit variant: hero"
|
||||||
|
|
||||||
|
Scenario Outline: Dismissing the mobile sheet
|
||||||
|
Given the viewport is below 640 px
|
||||||
|
When the user <gesture>
|
||||||
|
Then <result>
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| gesture | result |
|
||||||
|
| closes a pristine form with x or Cancel | the sheet closes with no dialog and focus returns to the opener |
|
||||||
|
| swipes down or taps the scrim, pristine | the sheet closes |
|
||||||
|
| closes a dirty form (x, Cancel, Escape, swipe, scrim) | the "Discard changes?" dialog opens and the sheet stays |
|
||||||
|
| any dismissal while Saving | nothing closes |
|
||||||
|
|
||||||
|
Scenario: Mobile no longer shows a back arrow
|
||||||
|
Given the viewport is below 640 px
|
||||||
|
Then no arrow-left back button is in the form header
|
||||||
|
|
||||||
|
Scenario: Focus
|
||||||
|
Then focus is trapped in the sheet or slide-over and returns to the opener on close, and on open it moves to the Name field in create mode
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
# QA: Variants and Media visual conformance, variant form overlay
|
||||||
|
|
||||||
|
## Implementation note for coder (informational, not a QA assertion)
|
||||||
|
|
||||||
|
SPA only, no Go change. web/visual/check.ts already points to the merged Back-office board and uses "V1a · Loaded" names, so only web/visual/states.ts keys and setups and VariantFormSlideover.vue change. `GET /v1/media/` already accepts `variants=with|without` and `sort=total_size` (api/handlers/media/mediaHandler.go parseListQuery), and the filter and sort already exist in MediaToolbar.vue, MediaVariantsFilter.vue and MediaView.vue: reuse, do not rebuild; touch Media code only if a V3 capture fails. The variant form currently uses USlideover side="right" at every width with a mobile back arrow; the mobile case becomes a bottom sheet at 92 % height with a grabber, close x and sticky footer. The Media detail panel is out of scope. The French catalogue gets entries for any new string. Supersedes the "Add variant opens a full page on mobile" scenario of features/image_variants_screens.feature. Never add a visual `exception` without asking the user.
|
||||||
|
|
||||||
|
## Automated (Vitest + Vue Test Utils, `task test:web`)
|
||||||
|
|
||||||
|
Reuse `web/src/views/__tests__/variantsTestKit.ts` and `mediaTestKit.ts`. Mock useApi's `request` per case. Mock `matchMedia` for the 640 px breakpoint. No test freezes the system date.
|
||||||
|
|
||||||
|
1. **Mobile variant form is a bottom sheet** (below 640 px): bottom sheet, not full page; grabber, close x with a 44 px target, 92 % height class, sticky footer; no arrow-left back button; the list is still in the DOM behind the scrim.
|
||||||
|
2. **Desktop variant form is a right slide-over** (640 px and up): side right, 960 px max width class, close x with accessible name "Close", form and preview side by side.
|
||||||
|
3. **Edit uses the same container**: mount in edit mode at both widths and check the container and the title "Edit variant: hero".
|
||||||
|
4. **Dismissal**: pristine, Cancel, x, Escape and the scrim close with no dialog. Dirty, each opens "Discard changes?" and the sheet stays. Saving, nothing closes. Focus returns to the opener.
|
||||||
|
5. **Media library regression**: the existing MediaVariantsLibrary spec still passes unchanged.
|
||||||
|
6. **Visual setup guard** (optional): every state name of the six groups in check.ts has an entry in web/visual/states.ts.
|
||||||
|
|
||||||
|
## Visual (`task visual:check -- image-variants [state]`, desktop 1440×900 and mobile 390×844, light and dark)
|
||||||
|
|
||||||
|
Reference: the merged board and exact values in `docs/design/source/AppFrame.dc.html`, `VariantsFrame.dc.html` and `MediaFrame.dc.html`. The gate is hard: every non-skipped capture is within 10 % and the command exits 0. Setups use the board's sample data. No state is currently known to be clock-sensitive; if coder finds one, mark it `skip: 'clock-sensitive'` and list it in the report.
|
||||||
|
|
||||||
|
- [ ] Variants list: V1a Loaded, V1b Loading, V1c Empty, V1d Error loading, V1e Forbidden, V1f Row menu, V1g Row action in progress, V1h Purge confirm, V1i Delete confirm, V1j Delete in progress, V1k Request reference, V1l Entry: sidebar
|
||||||
|
- [ ] Add edit variant: V2a Create: pristine, V2b Create: dirty, V2c Field errors, V2d No dimension, V2e Name already taken, V2f Saving, V2g Save error, V2h Edit: pristine, V2i Edit: dirty, V2j Unsaved changes, V2k PNG: no quality (mobile captures show the bottom sheet)
|
||||||
|
- [ ] Media library: V3a Grid with badges, V3b Sort menu, V3c Filter: With variants, sorted by total size, V3d Filter: Without variants, V3e Filter: nothing to show, V3f Delete confirm
|
||||||
|
- [ ] Image detail: V4a Partly generated, V4b Nothing generated yet, V4c Generating, V4d Generation failed, V4e No variants defined, V4f Source is an SVG, V4h Preview dialog
|
||||||
|
- [ ] Cache panel: V5a Loaded, V5b Loading, V5c Empty cache, V5d Purging, V5e Purge done, V5f Purge failed, V5g Error loading, V5h Purge all: confirm, V5i Purge all: confirm, typed, V5j Purge unused: confirm
|
||||||
|
- [ ] Editor picker: V6a Variant select, V6b Select open, V6c No variants defined, V6d Variant deleted, V6e Variant disabled
|
||||||
|
- [ ] Final: the whole run ends with every capture at PASS or SKIP and exit code 0
|
||||||
|
|
||||||
|
## Manual checks (screenshots cannot cover them)
|
||||||
|
|
||||||
|
- On a 390 px viewport, the sheet opens from the bottom, swipes down to close, shows the grabber, and the sticky footer stays above the on-screen keyboard.
|
||||||
|
- Keyboard: Tab order in the sheet and the slide-over, Escape behaviour, focus return to "Add variant" or the row's Edit button.
|
||||||
|
- Open and close motion, and the preview divider keyboard handling inside the sheet.
|
||||||
|
- Hover and focus-visible on the segmented filter and the sort menu in the Media library.
|
||||||
@@ -23,6 +23,7 @@ require (
|
|||||||
golang.org/x/image v0.46.0
|
golang.org/x/image v0.46.0
|
||||||
golang.org/x/net v0.59.0
|
golang.org/x/net v0.59.0
|
||||||
golang.org/x/sync v0.23.0
|
golang.org/x/sync v0.23.0
|
||||||
|
golang.org/x/text v0.42.0
|
||||||
gopkg.in/gomail.v2 v2.0.0-20160411212932-81ebce5c23df
|
gopkg.in/gomail.v2 v2.0.0-20160411212932-81ebce5c23df
|
||||||
gorm.io/driver/mysql v1.6.0
|
gorm.io/driver/mysql v1.6.0
|
||||||
gorm.io/driver/postgres v1.6.3
|
gorm.io/driver/postgres v1.6.3
|
||||||
@@ -73,7 +74,6 @@ require (
|
|||||||
github.com/segmentio/asm v1.2.1 // indirect
|
github.com/segmentio/asm v1.2.1 // indirect
|
||||||
golang.org/x/exp v0.0.0-20251113190631-e25ba8c21ef6 // indirect
|
golang.org/x/exp v0.0.0-20251113190631-e25ba8c21ef6 // indirect
|
||||||
golang.org/x/sys v0.48.0 // indirect
|
golang.org/x/sys v0.48.0 // indirect
|
||||||
golang.org/x/text v0.42.0 // indirect
|
|
||||||
gopkg.in/alexcesaro/quotedprintable.v3 v3.0.0-20150716171945-2caba252f4dc // indirect
|
gopkg.in/alexcesaro/quotedprintable.v3 v3.0.0-20150716171945-2caba252f4dc // indirect
|
||||||
modernc.org/libc v1.67.0 // indirect
|
modernc.org/libc v1.67.0 // indirect
|
||||||
modernc.org/mathutil v1.7.1 // indirect
|
modernc.org/mathutil v1.7.1 // indirect
|
||||||
|
|||||||
@@ -1,11 +1,57 @@
|
|||||||
package article
|
package article
|
||||||
|
|
||||||
|
const (
|
||||||
|
StatusOnline = "online"
|
||||||
|
StatusDraft = "draft"
|
||||||
|
)
|
||||||
|
|
||||||
|
type SortField string
|
||||||
|
|
||||||
|
type SortDirection string
|
||||||
|
|
||||||
|
const (
|
||||||
|
SortByTitle SortField = "title"
|
||||||
|
SortByStatus SortField = "status"
|
||||||
|
SortByCreatedAt SortField = "created_at"
|
||||||
|
SortByUpdatedAt SortField = "updated_at"
|
||||||
|
|
||||||
|
SortAsc SortDirection = "asc"
|
||||||
|
SortDesc SortDirection = "desc"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Sort struct {
|
||||||
|
Field SortField
|
||||||
|
Direction SortDirection
|
||||||
|
}
|
||||||
|
|
||||||
|
func DefaultSort() Sort {
|
||||||
|
return Sort{Field: SortByUpdatedAt, Direction: SortDesc}
|
||||||
|
}
|
||||||
|
|
||||||
type Filters struct {
|
type Filters struct {
|
||||||
IsOnline *bool
|
IsOnline *bool
|
||||||
|
Page int
|
||||||
|
Size int
|
||||||
|
Q string
|
||||||
|
Status string
|
||||||
|
Sort Sort
|
||||||
|
}
|
||||||
|
|
||||||
|
type Counts struct {
|
||||||
|
All int `json:"all"`
|
||||||
|
Online int `json:"online"`
|
||||||
|
Draft int `json:"draft"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type PageResult struct {
|
||||||
|
Items []Article
|
||||||
|
Total int
|
||||||
}
|
}
|
||||||
|
|
||||||
type Repository interface {
|
type Repository interface {
|
||||||
FindByFilters(filters Filters) ([]Article, error)
|
FindByFilters(filters Filters) ([]Article, error)
|
||||||
|
FindPage(filters Filters) (PageResult, error)
|
||||||
|
CountByVisibility(onlineOnly bool) (Counts, error)
|
||||||
Get(id uint32) (Article, error)
|
Get(id uint32) (Article, error)
|
||||||
GetByName(name string) (Article, error)
|
GetByName(name string) (Article, error)
|
||||||
GetAll() []Article
|
GetAll() []Article
|
||||||
|
|||||||
@@ -26,8 +26,8 @@ const MaxImageSize int64 = 10485760
|
|||||||
const (
|
const (
|
||||||
MinFilenameRunes = 1
|
MinFilenameRunes = 1
|
||||||
MaxFilenameRunes = 100
|
MaxFilenameRunes = 100
|
||||||
DefaultListLimit = 24
|
DefaultListPage = 1
|
||||||
MaxListLimit = 100
|
DefaultListSize = 25
|
||||||
)
|
)
|
||||||
|
|
||||||
var allowedContentTypes = map[string]bool{
|
var allowedContentTypes = map[string]bool{
|
||||||
@@ -128,12 +128,12 @@ type ListQuery struct {
|
|||||||
Filter Filter
|
Filter Filter
|
||||||
Variants VariantsFilter
|
Variants VariantsFilter
|
||||||
Sort Sort
|
Sort Sort
|
||||||
Limit int
|
Page int
|
||||||
Cursor string
|
Size int
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewListQuery() ListQuery {
|
func NewListQuery() ListQuery {
|
||||||
return ListQuery{Filter: FilterAll, Sort: SortNewest, Limit: DefaultListLimit}
|
return ListQuery{Filter: FilterAll, Sort: SortNewest, Page: DefaultListPage, Size: DefaultListSize}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (q ListQuery) Validate() error {
|
func (q ListQuery) Validate() error {
|
||||||
@@ -152,7 +152,12 @@ func (q ListQuery) Validate() error {
|
|||||||
default:
|
default:
|
||||||
return ErrInvalidQuery
|
return ErrInvalidQuery
|
||||||
}
|
}
|
||||||
if q.Limit < 1 || q.Limit > MaxListLimit {
|
if q.Page < 1 {
|
||||||
|
return ErrInvalidQuery
|
||||||
|
}
|
||||||
|
switch q.Size {
|
||||||
|
case 5, 25, 50, 100:
|
||||||
|
default:
|
||||||
return ErrInvalidQuery
|
return ErrInvalidQuery
|
||||||
}
|
}
|
||||||
if q.Hash != "" && !sha256Pattern.MatchString(q.Hash) {
|
if q.Hash != "" && !sha256Pattern.MatchString(q.Hash) {
|
||||||
|
|||||||
@@ -5,6 +5,12 @@ import (
|
|||||||
"RenewCMS/internal/infrastructure/persistence/mappers"
|
"RenewCMS/internal/infrastructure/persistence/mappers"
|
||||||
entity "RenewCMS/internal/infrastructure/persistence/models"
|
entity "RenewCMS/internal/infrastructure/persistence/models"
|
||||||
|
|
||||||
|
"strings"
|
||||||
|
"unicode"
|
||||||
|
|
||||||
|
"golang.org/x/text/runes"
|
||||||
|
"golang.org/x/text/transform"
|
||||||
|
"golang.org/x/text/unicode/norm"
|
||||||
"gorm.io/gorm"
|
"gorm.io/gorm"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -26,12 +32,128 @@ func (a *ArticleRepository) FindByFilters(filters domain.Filters) ([]domain.Arti
|
|||||||
var entityArticles []entity.Article
|
var entityArticles []entity.Article
|
||||||
err := query.Find(&entityArticles).Error
|
err := query.Find(&entityArticles).Error
|
||||||
|
|
||||||
|
return toDomainArticles(entityArticles), err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *ArticleRepository) scoped(filters domain.Filters) *gorm.DB {
|
||||||
|
query := a.db.Model(&entity.Article{})
|
||||||
|
if filters.IsOnline != nil {
|
||||||
|
query = query.Where("is_online = ?", *filters.IsOnline)
|
||||||
|
}
|
||||||
|
switch filters.Status {
|
||||||
|
case domain.StatusOnline:
|
||||||
|
query = query.Where("is_online = ?", true)
|
||||||
|
case domain.StatusDraft:
|
||||||
|
query = query.Where("is_online = ?", false)
|
||||||
|
}
|
||||||
|
return query
|
||||||
|
}
|
||||||
|
|
||||||
|
var sortColumns = map[domain.SortField]string{
|
||||||
|
domain.SortByTitle: "LOWER(title)",
|
||||||
|
domain.SortByStatus: "is_online",
|
||||||
|
domain.SortByCreatedAt: "created_at",
|
||||||
|
domain.SortByUpdatedAt: "updated_at",
|
||||||
|
}
|
||||||
|
|
||||||
|
var sortDirections = map[domain.SortDirection]string{
|
||||||
|
domain.SortAsc: "ASC",
|
||||||
|
domain.SortDesc: "DESC",
|
||||||
|
}
|
||||||
|
|
||||||
|
func orderClause(sort domain.Sort) string {
|
||||||
|
column, ok := sortColumns[sort.Field]
|
||||||
|
direction, directionOk := sortDirections[sort.Direction]
|
||||||
|
if !ok || !directionOk {
|
||||||
|
column, direction = sortColumns[domain.SortByUpdatedAt], sortDirections[domain.SortDesc]
|
||||||
|
}
|
||||||
|
return column + " " + direction + ", id DESC"
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *ArticleRepository) FindPage(filters domain.Filters) (domain.PageResult, error) {
|
||||||
|
filters.Page = max(filters.Page, 1)
|
||||||
|
filters.Size = max(filters.Size, 0)
|
||||||
|
filters.Q = strings.TrimSpace(filters.Q)
|
||||||
|
if filters.Q != "" {
|
||||||
|
return a.findMatchingTitle(filters)
|
||||||
|
}
|
||||||
|
var total int64
|
||||||
|
if err := a.scoped(filters).Count(&total).Error; err != nil {
|
||||||
|
return domain.PageResult{}, err
|
||||||
|
}
|
||||||
|
var entityArticles []entity.Article
|
||||||
|
err := a.scoped(filters).Order(orderClause(filters.Sort)).Limit(filters.Size).Offset((filters.Page - 1) * filters.Size).Find(&entityArticles).Error
|
||||||
|
if err != nil {
|
||||||
|
return domain.PageResult{}, err
|
||||||
|
}
|
||||||
|
return domain.PageResult{Items: toDomainArticles(entityArticles), Total: int(total)}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *ArticleRepository) findMatchingTitle(filters domain.Filters) (domain.PageResult, error) {
|
||||||
|
var candidates []entity.Article
|
||||||
|
if err := a.scoped(filters).Select("id", "title").Order(orderClause(filters.Sort)).Find(&candidates).Error; err != nil {
|
||||||
|
return domain.PageResult{}, err
|
||||||
|
}
|
||||||
|
needle := foldForSearch(filters.Q)
|
||||||
|
matchingIds := make([]uint32, 0)
|
||||||
|
for _, candidate := range candidates {
|
||||||
|
if strings.Contains(foldForSearch(candidate.Title), needle) {
|
||||||
|
matchingIds = append(matchingIds, candidate.ID)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
start := min((filters.Page-1)*filters.Size, len(matchingIds))
|
||||||
|
end := min(start+filters.Size, len(matchingIds))
|
||||||
|
pageIds := matchingIds[start:end]
|
||||||
|
page := domain.PageResult{Items: []domain.Article{}, Total: len(matchingIds)}
|
||||||
|
if len(pageIds) == 0 {
|
||||||
|
return page, nil
|
||||||
|
}
|
||||||
|
var entityArticles []entity.Article
|
||||||
|
if err := a.db.Model(&entity.Article{}).Where("id IN ?", pageIds).Find(&entityArticles).Error; err != nil {
|
||||||
|
return domain.PageResult{}, err
|
||||||
|
}
|
||||||
|
byId := make(map[uint32]entity.Article, len(entityArticles))
|
||||||
|
for _, entityArticle := range entityArticles {
|
||||||
|
byId[entityArticle.ID] = entityArticle
|
||||||
|
}
|
||||||
|
ordered := make([]entity.Article, 0, len(pageIds))
|
||||||
|
for _, id := range pageIds {
|
||||||
|
if entityArticle, found := byId[id]; found {
|
||||||
|
ordered = append(ordered, entityArticle)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
page.Items = toDomainArticles(ordered)
|
||||||
|
return page, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *ArticleRepository) CountByVisibility(onlineOnly bool) (domain.Counts, error) {
|
||||||
|
var online, draft int64
|
||||||
|
if err := a.db.Model(&entity.Article{}).Where("is_online = ?", true).Count(&online).Error; err != nil {
|
||||||
|
return domain.Counts{}, err
|
||||||
|
}
|
||||||
|
if !onlineOnly {
|
||||||
|
if err := a.db.Model(&entity.Article{}).Where("is_online = ?", false).Count(&draft).Error; err != nil {
|
||||||
|
return domain.Counts{}, err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return domain.Counts{All: int(online + draft), Online: int(online), Draft: int(draft)}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func toDomainArticles(entityArticles []entity.Article) []domain.Article {
|
||||||
domainArticles := make([]domain.Article, 0, len(entityArticles))
|
domainArticles := make([]domain.Article, 0, len(entityArticles))
|
||||||
for _, entityArticle := range entityArticles {
|
for _, entityArticle := range entityArticles {
|
||||||
domainArticles = append(domainArticles, mappers.ArticleToDomain(entityArticle))
|
domainArticles = append(domainArticles, mappers.ArticleToDomain(entityArticle))
|
||||||
}
|
}
|
||||||
|
return domainArticles
|
||||||
|
}
|
||||||
|
|
||||||
return domainArticles, err
|
func foldForSearch(value string) string {
|
||||||
|
folder := transform.Chain(norm.NFD, runes.Remove(runes.In(unicode.Mn)), norm.NFC)
|
||||||
|
folded, _, err := transform.String(folder, value)
|
||||||
|
if err != nil {
|
||||||
|
return strings.ToLower(value)
|
||||||
|
}
|
||||||
|
return strings.ToLower(folded)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (a *ArticleRepository) Get(id uint32) (domain.Article, error) {
|
func (a *ArticleRepository) Get(id uint32) (domain.Article, error) {
|
||||||
@@ -131,11 +253,7 @@ func (a *ArticleRepository) FindByBodyContaining(filename string) ([]domain.Arti
|
|||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
domainArticles := make([]domain.Article, 0, len(entityArticles))
|
return toDomainArticles(entityArticles), nil
|
||||||
for _, entityArticle := range entityArticles {
|
|
||||||
domainArticles = append(domainArticles, mappers.ArticleToDomain(entityArticle))
|
|
||||||
}
|
|
||||||
return domainArticles, nil
|
|
||||||
}
|
}
|
||||||
|
|
||||||
var _ domain.Repository = &ArticleRepository{}
|
var _ domain.Repository = &ArticleRepository{}
|
||||||
@@ -11,21 +11,51 @@ func NewListArticlesUseCase(articleRepository article.Repository, bodyRenderer a
|
|||||||
return &ListArticlesUseCase{articleRepository, bodyRenderer}
|
return &ListArticlesUseCase{articleRepository, bodyRenderer}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (u *ListArticlesUseCase) ListOnlineArticles(format article.BodyFormat) ([]article.Article, error) {
|
type ListArticlesCommand struct {
|
||||||
online := true
|
Format article.BodyFormat
|
||||||
articles, err := u.articleRepository.FindByFilters(article.Filters{
|
Verified bool
|
||||||
IsOnline: &online,
|
Page int
|
||||||
})
|
Size int
|
||||||
if err != nil {
|
Q string
|
||||||
return nil, err
|
Status string
|
||||||
}
|
Sort article.Sort
|
||||||
return renderArticles(u.bodyRenderer, articles, format)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (u *ListArticlesUseCase) ListAllArticles(format article.BodyFormat) ([]article.Article, error) {
|
type ArticlePage struct {
|
||||||
articles, err := u.articleRepository.FindByFilters(article.Filters{})
|
Items []article.Article
|
||||||
|
Total int
|
||||||
|
Page int
|
||||||
|
Size int
|
||||||
|
Counts article.Counts
|
||||||
|
}
|
||||||
|
|
||||||
|
func (u *ListArticlesUseCase) ListArticlesPage(command ListArticlesCommand) (ArticlePage, error) {
|
||||||
|
counts, err := u.articleRepository.CountByVisibility(!command.Verified)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return ArticlePage{}, err
|
||||||
}
|
}
|
||||||
return renderArticles(u.bodyRenderer, articles, format)
|
page := ArticlePage{Items: []article.Article{}, Page: command.Page, Size: command.Size, Counts: counts}
|
||||||
|
if !command.Verified && command.Status == article.StatusDraft {
|
||||||
|
return page, nil
|
||||||
|
}
|
||||||
|
found, err := u.articleRepository.FindPage(pageFilters(command))
|
||||||
|
if err != nil {
|
||||||
|
return ArticlePage{}, err
|
||||||
|
}
|
||||||
|
rendered, err := renderArticles(u.bodyRenderer, found.Items, command.Format)
|
||||||
|
if err != nil {
|
||||||
|
return ArticlePage{}, err
|
||||||
|
}
|
||||||
|
page.Items = rendered
|
||||||
|
page.Total = found.Total
|
||||||
|
return page, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func pageFilters(command ListArticlesCommand) article.Filters {
|
||||||
|
filters := article.Filters{Page: command.Page, Size: command.Size, Q: command.Q, Status: command.Status, Sort: command.Sort}
|
||||||
|
if !command.Verified {
|
||||||
|
online := true
|
||||||
|
filters.IsOnline = &online
|
||||||
|
}
|
||||||
|
return filters
|
||||||
}
|
}
|
||||||
@@ -4,13 +4,9 @@ import (
|
|||||||
"RenewCMS/internal/domain/article"
|
"RenewCMS/internal/domain/article"
|
||||||
"RenewCMS/internal/domain/image"
|
"RenewCMS/internal/domain/image"
|
||||||
"RenewCMS/internal/domain/user"
|
"RenewCMS/internal/domain/user"
|
||||||
"encoding/base64"
|
|
||||||
"strconv"
|
|
||||||
"strings"
|
"strings"
|
||||||
)
|
)
|
||||||
|
|
||||||
const cursorPrefix = "offset:"
|
|
||||||
|
|
||||||
type MediaItem struct {
|
type MediaItem struct {
|
||||||
Image image.Image
|
Image image.Image
|
||||||
UploadedBy string
|
UploadedBy string
|
||||||
@@ -28,9 +24,11 @@ type MediaCounts struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type MediaPage struct {
|
type MediaPage struct {
|
||||||
Items []MediaItem
|
Items []MediaItem
|
||||||
NextCursor string
|
Total int
|
||||||
Counts MediaCounts
|
Page int
|
||||||
|
Size int
|
||||||
|
Counts MediaCounts
|
||||||
}
|
}
|
||||||
|
|
||||||
type ListMediaUseCase struct {
|
type ListMediaUseCase struct {
|
||||||
@@ -48,10 +46,6 @@ func (l *ListMediaUseCase) List(query image.ListQuery) (MediaPage, error) {
|
|||||||
if err := query.Validate(); err != nil {
|
if err := query.Validate(); err != nil {
|
||||||
return MediaPage{}, err
|
return MediaPage{}, err
|
||||||
}
|
}
|
||||||
offset, err := decodeCursor(query.Cursor)
|
|
||||||
if err != nil {
|
|
||||||
return MediaPage{}, err
|
|
||||||
}
|
|
||||||
|
|
||||||
usage, err := l.usageCounter()
|
usage, err := l.usageCounter()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -83,8 +77,9 @@ func (l *ListMediaUseCase) List(query image.ListQuery) (MediaPage, error) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pageEnd := min(offset+query.Limit, len(matching))
|
offset := (query.Page - 1) * query.Size
|
||||||
pageStart := min(offset, pageEnd)
|
pageStart := min(offset, len(matching))
|
||||||
|
pageEnd := min(pageStart+query.Size, len(matching))
|
||||||
names := newUploaderNames(l.userRepository)
|
names := newUploaderNames(l.userRepository)
|
||||||
items := []MediaItem{}
|
items := []MediaItem{}
|
||||||
for _, img := range matching[pageStart:pageEnd] {
|
for _, img := range matching[pageStart:pageEnd] {
|
||||||
@@ -103,11 +98,7 @@ func (l *ListMediaUseCase) List(query image.ListQuery) (MediaPage, error) {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
page := MediaPage{Items: items, Counts: counts}
|
return MediaPage{Items: items, Total: len(matching), Page: query.Page, Size: query.Size, Counts: counts}, nil
|
||||||
if pageEnd < len(matching) {
|
|
||||||
page.NextCursor = encodeCursor(pageEnd)
|
|
||||||
}
|
|
||||||
return page, nil
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (l *ListMediaUseCase) Describe(img image.Image) (MediaItem, error) {
|
func (l *ListMediaUseCase) Describe(img image.Image) (MediaItem, error) {
|
||||||
@@ -217,22 +208,3 @@ func matchesFilter(filter image.Filter, usedIn int, duplicate bool) bool {
|
|||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func encodeCursor(offset int) string {
|
|
||||||
return base64.RawURLEncoding.EncodeToString([]byte(cursorPrefix + strconv.Itoa(offset)))
|
|
||||||
}
|
|
||||||
|
|
||||||
func decodeCursor(cursor string) (int, error) {
|
|
||||||
if cursor == "" {
|
|
||||||
return 0, nil
|
|
||||||
}
|
|
||||||
raw, err := base64.RawURLEncoding.DecodeString(cursor)
|
|
||||||
if err != nil || !strings.HasPrefix(string(raw), cursorPrefix) {
|
|
||||||
return 0, image.ErrInvalidQuery
|
|
||||||
}
|
|
||||||
offset, err := strconv.Atoi(strings.TrimPrefix(string(raw), cursorPrefix))
|
|
||||||
if err != nil || offset < 0 {
|
|
||||||
return 0, image.ErrInvalidQuery
|
|
||||||
}
|
|
||||||
return offset, nil
|
|
||||||
}
|
|
||||||
@@ -9,6 +9,7 @@ const (
|
|||||||
activityRangeToday = "today"
|
activityRangeToday = "today"
|
||||||
activityRange7Days = "7d"
|
activityRange7Days = "7d"
|
||||||
activityRange30Days = "30d"
|
activityRange30Days = "30d"
|
||||||
|
activityRangeAll = "all"
|
||||||
activityRangeCustom = "custom"
|
activityRangeCustom = "custom"
|
||||||
activityDateLayout = "2006-01-02"
|
activityDateLayout = "2006-01-02"
|
||||||
activityDefaultSize = 25
|
activityDefaultSize = 25
|
||||||
@@ -47,6 +48,8 @@ func resolveActivityWindow(query ActivityQuery, now time.Time) (activityWindow,
|
|||||||
return activityWindow{from: end.AddDate(0, 0, -30), to: end}, nil
|
return activityWindow{from: end.AddDate(0, 0, -30), to: end}, nil
|
||||||
case activityRangeToday:
|
case activityRangeToday:
|
||||||
return activityWindow{from: time.Date(utc.Year(), utc.Month(), utc.Day(), 0, 0, 0, 0, time.UTC), to: end}, nil
|
return activityWindow{from: time.Date(utc.Year(), utc.Month(), utc.Day(), 0, 0, 0, 0, time.UTC), to: end}, nil
|
||||||
|
case activityRangeAll:
|
||||||
|
return activityWindow{from: time.Unix(0, 0).UTC(), to: end}, nil
|
||||||
case activityRangeCustom:
|
case activityRangeCustom:
|
||||||
return resolveCustomWindow(query)
|
return resolveCustomWindow(query)
|
||||||
default:
|
default:
|
||||||
|
|||||||
@@ -0,0 +1,77 @@
|
|||||||
|
package test
|
||||||
|
|
||||||
|
import (
|
||||||
|
"RenewCMS/api/pkg/apperr"
|
||||||
|
"RenewCMS/internal/domain/audit"
|
||||||
|
"encoding/csv"
|
||||||
|
"encoding/json"
|
||||||
|
"net/http"
|
||||||
|
"reflect"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestActivityRangeAll(t *testing.T) {
|
||||||
|
const day = 24 * time.Hour
|
||||||
|
|
||||||
|
t.Run("range=all covers every event", func(t *testing.T) {
|
||||||
|
e := newActivityHTTPEnv(t, 1000)
|
||||||
|
recent := e.seedBy(t, userActor(1, "a"), 2*day)
|
||||||
|
old := e.seedBy(t, userActor(1, "a"), 90*day, func(ev *audit.Event) {
|
||||||
|
ev.Params = map[string]any{"marker": "kept"}
|
||||||
|
})
|
||||||
|
|
||||||
|
got := decodeActivityList(t, e.get("/v1/activity?range=all", asUser(e, activityOwnerID))).ids()
|
||||||
|
if !sameIDs(got, []uint64{recent.ID, old.ID}) {
|
||||||
|
t.Errorf("expected both events listed, got %v", got)
|
||||||
|
}
|
||||||
|
|
||||||
|
raw := e.get("/v1/activity?range=all", asUser(e, activityOwnerID)).Body.String()
|
||||||
|
if !strings.Contains(raw, `"changes":[]`) || strings.Contains(raw, `"changes":null`) || !strings.Contains(raw, `"params":{}`) || !strings.Contains(raw, `"marker":"kept"`) {
|
||||||
|
t.Errorf("expected empty changes arrays, got %s", raw)
|
||||||
|
}
|
||||||
|
|
||||||
|
summary := e.get("/v1/activity/summary?range=all", asUser(e, activityOwnerID))
|
||||||
|
if summary.Code != http.StatusOK {
|
||||||
|
t.Fatalf("expected 200, got %d", summary.Code)
|
||||||
|
}
|
||||||
|
var counts map[string]any
|
||||||
|
_ = json.Unmarshal(summary.Body.Bytes(), &counts)
|
||||||
|
if counts["total"] != float64(2) {
|
||||||
|
t.Errorf("expected a summary total of 2, got %v", counts["total"])
|
||||||
|
}
|
||||||
|
|
||||||
|
export := e.get("/v1/activity/export?range=all", asUser(e, activityOwnerID))
|
||||||
|
rows, err := csv.NewReader(strings.NewReader(export.Body.String())).ReadAll()
|
||||||
|
if export.Code != http.StatusOK || err != nil || len(rows) != 3 {
|
||||||
|
t.Errorf("expected header and two rows, got %d %q %v", export.Code, export.Body.String(), err)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("Omitting range still means 7 days", func(t *testing.T) {
|
||||||
|
e := newActivityHTTPEnv(t, 1000)
|
||||||
|
recent := e.seedBy(t, userActor(1, "a"), 2*day)
|
||||||
|
e.seedBy(t, userActor(1, "a"), 90*day)
|
||||||
|
|
||||||
|
got := decodeActivityList(t, e.get("/v1/activity", asUser(e, activityOwnerID))).ids()
|
||||||
|
|
||||||
|
if !reflect.DeepEqual(got, []uint64{recent.ID}) {
|
||||||
|
t.Errorf("expected only the recent event, got %v", got)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("Other invalid ranges still answer 400", func(t *testing.T) {
|
||||||
|
for _, path := range []string{"/v1/activity", "/v1/activity/summary", "/v1/activity/export"} {
|
||||||
|
for _, query := range []string{"range=ALL", "range=everything", "range=year"} {
|
||||||
|
e := newActivityHTTPEnv(t, 1000)
|
||||||
|
assertPlain(t, e.get(path+"?"+query, asUser(e, activityOwnerID)), http.StatusBadRequest, activityMismatch)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("A non-owner export with range=all is still 403", func(t *testing.T) {
|
||||||
|
e := newActivityHTTPEnv(t, 1000)
|
||||||
|
assertPlain(t, e.get("/v1/activity/export?range=all", asUser(e, activityEditorID)), http.StatusForbidden, apperr.OwnerOrAdminRequiredErrorMessage)
|
||||||
|
})
|
||||||
|
}
|
||||||
@@ -514,7 +514,13 @@ func TestAPIKeysHttp(t *testing.T) {
|
|||||||
raw, _ := env.issueKey(apiKeyDevId, "ci")
|
raw, _ := env.issueKey(apiKeyDevId, "ci")
|
||||||
ids := func(rec *httptest.ResponseRecorder) []float64 {
|
ids := func(rec *httptest.ResponseRecorder) []float64 {
|
||||||
result := []float64{}
|
result := []float64{}
|
||||||
for _, entry := range apiKeyDecodeList(t, rec) {
|
var envelope struct {
|
||||||
|
Items []map[string]any `json:"items"`
|
||||||
|
}
|
||||||
|
if err := json.Unmarshal(rec.Body.Bytes(), &envelope); err != nil {
|
||||||
|
t.Fatalf("expected an article envelope, got %q: %v", rec.Body.String(), err)
|
||||||
|
}
|
||||||
|
for _, entry := range envelope.Items {
|
||||||
result = append(result, entry["id"].(float64))
|
result = append(result, entry["id"].(float64))
|
||||||
}
|
}
|
||||||
return result
|
return result
|
||||||
@@ -522,7 +528,7 @@ func TestAPIKeysHttp(t *testing.T) {
|
|||||||
|
|
||||||
withKey := env.withKey(t, http.MethodGet, "/v1/article", "", raw)
|
withKey := env.withKey(t, http.MethodGet, "/v1/article", "", raw)
|
||||||
assertAPIKeyStatus(t, withKey, http.StatusOK)
|
assertAPIKeyStatus(t, withKey, http.StatusOK)
|
||||||
if got := ids(withKey); len(got) != 2 || got[0] != 5 || got[1] != 6 {
|
if got := ids(withKey); len(got) != 2 || got[0] != 6 || got[1] != 5 {
|
||||||
t.Errorf("expected articles 5 and 6, got %v", got)
|
t.Errorf("expected articles 5 and 6, got %v", got)
|
||||||
}
|
}
|
||||||
anonymous := env.anonymous(t, http.MethodGet, "/v1/article", "")
|
anonymous := env.anonymous(t, http.MethodGet, "/v1/article", "")
|
||||||
|
|||||||
@@ -188,7 +188,7 @@ func TestArticleBodyFormatHttp(t *testing.T) {
|
|||||||
for _, expectation := range expectations {
|
for _, expectation := range expectations {
|
||||||
rec := serveBodyFormat(router, http.MethodGet, "/v1/article/"+expectation.query, "", nil)
|
rec := serveBodyFormat(router, http.MethodGet, "/v1/article/"+expectation.query, "", nil)
|
||||||
var items []bodyFormatResponse
|
var items []bodyFormatResponse
|
||||||
if err := json.Unmarshal(rec.Body.Bytes(), &items); err != nil {
|
if err := json.Unmarshal(articleItemsJSON(rec.Body.Bytes()), &items); err != nil {
|
||||||
t.Fatalf("failed to decode list: %v", err)
|
t.Fatalf("failed to decode list: %v", err)
|
||||||
}
|
}
|
||||||
if len(items) != 2 {
|
if len(items) != 2 {
|
||||||
@@ -318,7 +318,7 @@ func TestArticleBodyFormatHttp(t *testing.T) {
|
|||||||
router, _ := realRouter()
|
router, _ := realRouter()
|
||||||
rec := serveBodyFormat(router, http.MethodGet, "/v1/article/?format=json", "", verifiedCookie)
|
rec := serveBodyFormat(router, http.MethodGet, "/v1/article/?format=json", "", verifiedCookie)
|
||||||
var items []bodyFormatResponse
|
var items []bodyFormatResponse
|
||||||
if err := json.Unmarshal(rec.Body.Bytes(), &items); err != nil {
|
if err := json.Unmarshal(articleItemsJSON(rec.Body.Bytes()), &items); err != nil {
|
||||||
t.Fatalf("failed to decode list: %v", err)
|
t.Fatalf("failed to decode list: %v", err)
|
||||||
}
|
}
|
||||||
seen := map[uint32]bool{}
|
seen := map[uint32]bool{}
|
||||||
|
|||||||
@@ -0,0 +1,204 @@
|
|||||||
|
package test
|
||||||
|
|
||||||
|
import (
|
||||||
|
"RenewCMS/api/handlers/article"
|
||||||
|
"RenewCMS/api/middleware"
|
||||||
|
"RenewCMS/api/pkg/apperr"
|
||||||
|
validator "RenewCMS/api/pkg/validator"
|
||||||
|
"RenewCMS/internal/infrastructure/markdown"
|
||||||
|
"RenewCMS/internal/infrastructure/useCases"
|
||||||
|
"encoding/json"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/go-chi/chi/v5"
|
||||||
|
"github.com/go-chi/jwtauth/v5"
|
||||||
|
)
|
||||||
|
|
||||||
|
func newUnlimitedBodyRouter(articleRepo *mockArticleRepo, token *jwtauth.JWTAuth) *chi.Mux {
|
||||||
|
getUserUseCase := useCases.NewGetUserUseCase(newVerifiedUserRepo())
|
||||||
|
renderer := markdown.NewConverter()
|
||||||
|
articleHandler := article.NewHandler(
|
||||||
|
useCases.NewCreateArticleUseCase(articleRepo, renderer, discardRecorder),
|
||||||
|
useCases.NewGetArticleUseCase(articleRepo, renderer),
|
||||||
|
useCases.NewListArticlesUseCase(articleRepo, renderer),
|
||||||
|
useCases.NewDeleteArticleUseCase(articleRepo, discardRecorder),
|
||||||
|
useCases.NewUpdateArticleUseCase(articleRepo, renderer, discardRecorder),
|
||||||
|
getUserUseCase,
|
||||||
|
)
|
||||||
|
|
||||||
|
r := chi.NewRouter()
|
||||||
|
r.Route("/v1", func(r chi.Router) {
|
||||||
|
r.Route("/article", func(r chi.Router) {
|
||||||
|
r.Group(func(r chi.Router) {
|
||||||
|
r.Use(jwtauth.Verifier(token))
|
||||||
|
r.Group(func(r chi.Router) {
|
||||||
|
r.Use(jwtauth.Authenticator(token))
|
||||||
|
r.Use(middleware.RequireVerifiedUser(getUserUseCase))
|
||||||
|
r.Post("/", articleHandler.PostArticle)
|
||||||
|
r.Get("/{id}", articleHandler.GetArticle)
|
||||||
|
r.Patch("/{id}", articleHandler.UpdateArticleBody)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
})
|
||||||
|
})
|
||||||
|
return r
|
||||||
|
}
|
||||||
|
|
||||||
|
func serveUnlimitedBody(t *testing.T, router *chi.Mux, token *jwtauth.JWTAuth, method, target, payload string) *httptest.ResponseRecorder {
|
||||||
|
t.Helper()
|
||||||
|
req := newEditArticleBodyRequest(method, target, payload)
|
||||||
|
setEditArticleBodyJwtCookie(t, req, token)
|
||||||
|
rec := httptest.NewRecorder()
|
||||||
|
router.ServeHTTP(rec, req)
|
||||||
|
return rec
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestArticleBodyUnlimitedHttp(t *testing.T) {
|
||||||
|
validator.InitValidator()
|
||||||
|
token := jwtauth.New("HS256", []byte("test-secret"), nil)
|
||||||
|
const title = "Choosing tiles for a small bathroom"
|
||||||
|
|
||||||
|
createCases := []struct {
|
||||||
|
name string
|
||||||
|
query string
|
||||||
|
payload string
|
||||||
|
format string
|
||||||
|
rendered string
|
||||||
|
}{
|
||||||
|
{"markdown without body key", "", `{"title": "` + title + `"}`, "markdown", `""`},
|
||||||
|
{"html without body key", "?format=html", `{"title": "` + title + `"}`, "html", `""`},
|
||||||
|
{"json without body key", "?format=json", `{"title": "` + title + `"}`, "json", `[]`},
|
||||||
|
{"markdown with empty body", "", `{"title": "` + title + `", "body": ""}`, "markdown", `""`},
|
||||||
|
}
|
||||||
|
for _, tc := range createCases {
|
||||||
|
t.Run("Create with only a title succeeds in every body format: "+tc.name, func(t *testing.T) {
|
||||||
|
repo := newMockArticleRepo()
|
||||||
|
router := newUnlimitedBodyRouter(repo, token)
|
||||||
|
rec := serveUnlimitedBody(t, router, token, http.MethodPost, "/v1/article/"+tc.query, tc.payload)
|
||||||
|
|
||||||
|
if rec.Code != http.StatusCreated {
|
||||||
|
t.Fatalf("expected 201, got %d: %s", rec.Code, rec.Body.String())
|
||||||
|
}
|
||||||
|
var got struct {
|
||||||
|
Title string `json:"title"`
|
||||||
|
IsOnline bool `json:"is_online"`
|
||||||
|
BodyFormat string `json:"body_format"`
|
||||||
|
Body json.RawMessage `json:"body"`
|
||||||
|
}
|
||||||
|
if err := json.Unmarshal(rec.Body.Bytes(), &got); err != nil {
|
||||||
|
t.Fatalf("failed to decode response: %v", err)
|
||||||
|
}
|
||||||
|
if got.Title != title || got.IsOnline || got.BodyFormat != tc.format || string(got.Body) != tc.rendered {
|
||||||
|
t.Errorf("unexpected response: %s", rec.Body.String())
|
||||||
|
}
|
||||||
|
if len(repo.articles) != 1 {
|
||||||
|
t.Fatalf("expected one article, got %d", len(repo.articles))
|
||||||
|
}
|
||||||
|
for _, stored := range repo.articles {
|
||||||
|
if stored.Body != "" {
|
||||||
|
t.Errorf("expected empty stored body, got %q", stored.Body)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
t.Run("A body of 120,000 characters is accepted on create", func(t *testing.T) {
|
||||||
|
repo := newMockArticleRepo()
|
||||||
|
router := newUnlimitedBodyRouter(repo, token)
|
||||||
|
body := strings.Repeat("a", 120000)
|
||||||
|
rec := serveUnlimitedBody(t, router, token, http.MethodPost, "/v1/article/", `{"title": "`+title+`", "body": "`+body+`"}`)
|
||||||
|
|
||||||
|
if rec.Code != http.StatusCreated {
|
||||||
|
t.Fatalf("expected 201, got %d", rec.Code)
|
||||||
|
}
|
||||||
|
for _, stored := range repo.articles {
|
||||||
|
if stored.Body != body {
|
||||||
|
t.Errorf("stored body differs, length %d", len(stored.Body))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
for _, length := range []int{10001, 120000} {
|
||||||
|
t.Run("Update the body with no length limit: "+strconv.Itoa(length), func(t *testing.T) {
|
||||||
|
repo := newEditArticleBodyTestRepo()
|
||||||
|
router := newUnlimitedBodyRouter(repo, token)
|
||||||
|
body := strings.Repeat("a", length)
|
||||||
|
rec := serveUnlimitedBody(t, router, token, http.MethodPatch, "/v1/article/1", `{"body": "`+body+`"}`)
|
||||||
|
|
||||||
|
if rec.Code != http.StatusOK {
|
||||||
|
t.Fatalf("expected 200, got %d", rec.Code)
|
||||||
|
}
|
||||||
|
if len(repo.articles[1].Body) != length {
|
||||||
|
t.Errorf("expected %d characters, got %d", length, len(repo.articles[1].Body))
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
t.Run("Update the body to empty", func(t *testing.T) {
|
||||||
|
repo := newEditArticleBodyTestRepo()
|
||||||
|
router := newUnlimitedBodyRouter(repo, token)
|
||||||
|
rec := serveUnlimitedBody(t, router, token, http.MethodPatch, "/v1/article/1", `{"body": ""}`)
|
||||||
|
|
||||||
|
if rec.Code != http.StatusOK {
|
||||||
|
t.Fatalf("expected 200, got %d", rec.Code)
|
||||||
|
}
|
||||||
|
if repo.articles[1].Body != "" {
|
||||||
|
t.Errorf("expected empty body, got %q", repo.articles[1].Body)
|
||||||
|
}
|
||||||
|
get := serveUnlimitedBody(t, router, token, http.MethodGet, "/v1/article/1?format=json", "")
|
||||||
|
var got struct {
|
||||||
|
Body json.RawMessage `json:"body"`
|
||||||
|
}
|
||||||
|
if err := json.Unmarshal(get.Body.Bytes(), &got); err != nil {
|
||||||
|
t.Fatalf("failed to decode response: %v", err)
|
||||||
|
}
|
||||||
|
if string(got.Body) != "[]" {
|
||||||
|
t.Errorf("expected [], got %s", got.Body)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
titleCases := []struct {
|
||||||
|
name string
|
||||||
|
payload string
|
||||||
|
}{
|
||||||
|
{"missing title", `{"body": "Hello"}`},
|
||||||
|
{"title too short", `{"title": "Ti", "body": "Hello"}`},
|
||||||
|
{"title too long", `{"title": "` + strings.Repeat("a", 201) + `"}`},
|
||||||
|
}
|
||||||
|
for _, tc := range titleCases {
|
||||||
|
t.Run("Title rules are unchanged: "+tc.name, func(t *testing.T) {
|
||||||
|
repo := newMockArticleRepo()
|
||||||
|
router := newUnlimitedBodyRouter(repo, token)
|
||||||
|
rec := serveUnlimitedBody(t, router, token, http.MethodPost, "/v1/article/", tc.payload)
|
||||||
|
|
||||||
|
if rec.Code != http.StatusBadRequest {
|
||||||
|
t.Fatalf("expected 400, got %d", rec.Code)
|
||||||
|
}
|
||||||
|
if len(repo.articles) != 0 {
|
||||||
|
t.Errorf("expected no article, got %d", len(repo.articles))
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
t.Run("Existing guards on PATCH are unchanged", func(t *testing.T) {
|
||||||
|
repo := newEditArticleBodyTestRepo()
|
||||||
|
router := newUnlimitedBodyRouter(repo, token)
|
||||||
|
|
||||||
|
rec := serveUnlimitedBody(t, router, token, http.MethodPatch, "/v1/article/abc", `{"body": "x"}`)
|
||||||
|
if rec.Code != http.StatusBadRequest || rec.Body.String() != apperr.IdUint32ErrorMessage+"\n" {
|
||||||
|
t.Errorf("unexpected id guard: %d %q", rec.Code, rec.Body.String())
|
||||||
|
}
|
||||||
|
rec = serveUnlimitedBody(t, router, token, http.MethodPatch, "/v1/article/999", `{"body": "x"}`)
|
||||||
|
if rec.Code != http.StatusNotFound || rec.Body.String() != apperr.ArticleNotFoundErrorMessage+"\n" {
|
||||||
|
t.Errorf("unexpected not found guard: %d %q", rec.Code, rec.Body.String())
|
||||||
|
}
|
||||||
|
rec = serveUnlimitedBody(t, router, token, http.MethodPatch, "/v1/article/1", `not json`)
|
||||||
|
if rec.Code != http.StatusBadRequest || rec.Body.String() != apperr.BodyErrorMessage+"\n" {
|
||||||
|
t.Errorf("unexpected malformed guard: %d %q", rec.Code, rec.Body.String())
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
@@ -234,7 +234,7 @@ func TestArticlePublishingHttp(t *testing.T) {
|
|||||||
t.Fatalf("expected status 200, got %d", listRec.Code)
|
t.Fatalf("expected status 200, got %d", listRec.Code)
|
||||||
}
|
}
|
||||||
var articles []domainArticle.Article
|
var articles []domainArticle.Article
|
||||||
if err := json.Unmarshal(listRec.Body.Bytes(), &articles); err != nil {
|
if err := json.Unmarshal(articleItemsJSON(listRec.Body.Bytes()), &articles); err != nil {
|
||||||
t.Fatalf("failed to decode response: %v", err)
|
t.Fatalf("failed to decode response: %v", err)
|
||||||
}
|
}
|
||||||
found := false
|
found := false
|
||||||
@@ -304,7 +304,7 @@ func TestArticlePublishingHttp(t *testing.T) {
|
|||||||
t.Fatalf("expected status 200, got %d", listRec.Code)
|
t.Fatalf("expected status 200, got %d", listRec.Code)
|
||||||
}
|
}
|
||||||
var articles []domainArticle.Article
|
var articles []domainArticle.Article
|
||||||
if err := json.Unmarshal(listRec.Body.Bytes(), &articles); err != nil {
|
if err := json.Unmarshal(articleItemsJSON(listRec.Body.Bytes()), &articles); err != nil {
|
||||||
t.Fatalf("failed to decode response: %v", err)
|
t.Fatalf("failed to decode response: %v", err)
|
||||||
}
|
}
|
||||||
foundStillOnline := false
|
foundStillOnline := false
|
||||||
|
|||||||
@@ -7,6 +7,11 @@ import (
|
|||||||
"sort"
|
"sort"
|
||||||
"strings"
|
"strings"
|
||||||
"testing"
|
"testing"
|
||||||
|
"unicode"
|
||||||
|
|
||||||
|
"golang.org/x/text/runes"
|
||||||
|
"golang.org/x/text/transform"
|
||||||
|
"golang.org/x/text/unicode/norm"
|
||||||
)
|
)
|
||||||
|
|
||||||
type mockArticleRepo struct {
|
type mockArticleRepo struct {
|
||||||
@@ -47,6 +52,85 @@ func (m *mockArticleRepo) FindByFilters(filters article.Filters) ([]article.Arti
|
|||||||
return result, nil
|
return result, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (m *mockArticleRepo) FindPage(filters article.Filters) (article.PageResult, error) {
|
||||||
|
if err := m.fail.trigger("FindPage"); err != nil {
|
||||||
|
return article.PageResult{}, err
|
||||||
|
}
|
||||||
|
matching := make([]article.Article, 0)
|
||||||
|
for _, a := range m.articles {
|
||||||
|
if filters.IsOnline != nil && a.IsOnline != *filters.IsOnline {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if filters.Status == article.StatusOnline && !a.IsOnline {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if filters.Status == article.StatusDraft && a.IsOnline {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if filters.Q != "" && !strings.Contains(foldArticleSearch(a.Title), foldArticleSearch(filters.Q)) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
matching = append(matching, a)
|
||||||
|
}
|
||||||
|
sort.Slice(matching, func(i, j int) bool { return articleSortsBefore(matching[i], matching[j], filters.Sort) })
|
||||||
|
start := min((filters.Page-1)*filters.Size, len(matching))
|
||||||
|
end := min(start+filters.Size, len(matching))
|
||||||
|
return article.PageResult{Items: matching[start:end], Total: len(matching)}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *mockArticleRepo) CountByVisibility(onlineOnly bool) (article.Counts, error) {
|
||||||
|
if err := m.fail.trigger("CountByVisibility"); err != nil {
|
||||||
|
return article.Counts{}, err
|
||||||
|
}
|
||||||
|
counts := article.Counts{}
|
||||||
|
for _, a := range m.articles {
|
||||||
|
if a.IsOnline {
|
||||||
|
counts.Online++
|
||||||
|
} else if !onlineOnly {
|
||||||
|
counts.Draft++
|
||||||
|
}
|
||||||
|
}
|
||||||
|
counts.All = counts.Online + counts.Draft
|
||||||
|
return counts, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func articleSortsBefore(left, right article.Article, order article.Sort) bool {
|
||||||
|
if order.Field == "" {
|
||||||
|
order = article.DefaultSort()
|
||||||
|
}
|
||||||
|
var comparison int
|
||||||
|
switch order.Field {
|
||||||
|
case article.SortByTitle:
|
||||||
|
comparison = strings.Compare(strings.ToLower(left.Title), strings.ToLower(right.Title))
|
||||||
|
case article.SortByStatus:
|
||||||
|
if left.IsOnline != right.IsOnline {
|
||||||
|
comparison = 1
|
||||||
|
if !left.IsOnline {
|
||||||
|
comparison = -1
|
||||||
|
}
|
||||||
|
}
|
||||||
|
case article.SortByCreatedAt:
|
||||||
|
comparison = left.CreatedAt.Compare(right.CreatedAt)
|
||||||
|
default:
|
||||||
|
comparison = left.UpdatedAt.Compare(right.UpdatedAt)
|
||||||
|
}
|
||||||
|
if order.Direction == article.SortDesc {
|
||||||
|
comparison = -comparison
|
||||||
|
}
|
||||||
|
if comparison != 0 {
|
||||||
|
return comparison < 0
|
||||||
|
}
|
||||||
|
return left.ID > right.ID
|
||||||
|
}
|
||||||
|
|
||||||
|
func foldArticleSearch(value string) string {
|
||||||
|
folded, _, err := transform.String(transform.Chain(norm.NFD, runes.Remove(runes.In(unicode.Mn)), norm.NFC), value)
|
||||||
|
if err != nil {
|
||||||
|
return strings.ToLower(value)
|
||||||
|
}
|
||||||
|
return strings.ToLower(folded)
|
||||||
|
}
|
||||||
|
|
||||||
func (m *mockArticleRepo) Get(id uint32) (article.Article, error) {
|
func (m *mockArticleRepo) Get(id uint32) (article.Article, error) {
|
||||||
if err := m.fail.trigger("Get"); err != nil {
|
if err := m.fail.trigger("Get"); err != nil {
|
||||||
return article.Article{}, err
|
return article.Article{}, err
|
||||||
|
|||||||
@@ -57,7 +57,7 @@ func TestArticlesListHttp(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
var got []map[string]any
|
var got []map[string]any
|
||||||
if err := json.Unmarshal(rec.Body.Bytes(), &got); err != nil {
|
if err := json.Unmarshal(articleItemsJSON(rec.Body.Bytes()), &got); err != nil {
|
||||||
t.Fatalf("failed to decode response: %v", err)
|
t.Fatalf("failed to decode response: %v", err)
|
||||||
}
|
}
|
||||||
if len(got) != 1 {
|
if len(got) != 1 {
|
||||||
|
|||||||
@@ -0,0 +1,613 @@
|
|||||||
|
package test
|
||||||
|
|
||||||
|
import (
|
||||||
|
domainArticle "RenewCMS/internal/domain/article"
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"net/url"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
persistence "RenewCMS/internal/infrastructure/persistence/repositories"
|
||||||
|
"RenewCMS/internal/infrastructure/useCases"
|
||||||
|
"errors"
|
||||||
|
|
||||||
|
"github.com/go-chi/jwtauth/v5"
|
||||||
|
|
||||||
|
validator "RenewCMS/api/pkg/validator"
|
||||||
|
)
|
||||||
|
|
||||||
|
const paginationBodyMismatch = "The request cannot be processed due to a mismatch in the format of the body."
|
||||||
|
|
||||||
|
type paginationEnvelope struct {
|
||||||
|
Items []map[string]any `json:"items"`
|
||||||
|
Total int `json:"total"`
|
||||||
|
Page int `json:"page"`
|
||||||
|
Size int `json:"size"`
|
||||||
|
Counts map[string]int `json:"counts"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func articleItemsJSON(body []byte) []byte {
|
||||||
|
var envelope struct {
|
||||||
|
Items json.RawMessage `json:"items"`
|
||||||
|
}
|
||||||
|
if err := json.Unmarshal(body, &envelope); err != nil || envelope.Items == nil {
|
||||||
|
return body
|
||||||
|
}
|
||||||
|
return envelope.Items
|
||||||
|
}
|
||||||
|
|
||||||
|
func seedPaginationArticles(repo *mockArticleRepo, online int, draft int) {
|
||||||
|
base := time.Date(2026, 9, 1, 0, 0, 0, 0, time.UTC)
|
||||||
|
add := func(isOnline bool, title string) {
|
||||||
|
id := uint32(len(repo.articles) + 1)
|
||||||
|
repo.articles[id] = domainArticle.Article{ID: id, Title: title, IsOnline: isOnline, UpdatedAt: base.Add(time.Duration(id) * time.Hour)}
|
||||||
|
}
|
||||||
|
for i := 0; i < online; i++ {
|
||||||
|
add(true, fmt.Sprintf("Online article %d", i))
|
||||||
|
}
|
||||||
|
for i := 0; i < draft; i++ {
|
||||||
|
add(false, fmt.Sprintf("Draft article %d", i))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func seedSortArticles(repo *mockArticleRepo) {
|
||||||
|
day := func(month, d int) time.Time { return time.Date(2026, time.Month(month), d, 0, 0, 0, 0, time.UTC) }
|
||||||
|
repo.articles[1] = domainArticle.Article{ID: 1, Title: "Banana", IsOnline: true, CreatedAt: day(1, 1), UpdatedAt: day(9, 3)}
|
||||||
|
repo.articles[2] = domainArticle.Article{ID: 2, Title: "apple", IsOnline: false, CreatedAt: day(1, 3), UpdatedAt: day(9, 1)}
|
||||||
|
repo.articles[3] = domainArticle.Article{ID: 3, Title: "Cherry", IsOnline: true, CreatedAt: day(1, 2), UpdatedAt: day(9, 2)}
|
||||||
|
}
|
||||||
|
|
||||||
|
func itemIds(envelope paginationEnvelope) []int {
|
||||||
|
ids := []int{}
|
||||||
|
for _, item := range envelope.Items {
|
||||||
|
ids = append(ids, int(item["id"].(float64)))
|
||||||
|
}
|
||||||
|
return ids
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestArticlesPaginationApiHttp(t *testing.T) {
|
||||||
|
validator.InitValidator()
|
||||||
|
token := jwtauth.New("HS256", []byte("test-secret"), nil)
|
||||||
|
|
||||||
|
get := func(t *testing.T, repo *mockArticleRepo, query string, verified bool) (*httptest.ResponseRecorder, paginationEnvelope) {
|
||||||
|
t.Helper()
|
||||||
|
router := newArticlesListRouter(repo, token)
|
||||||
|
req := httptest.NewRequest(http.MethodGet, "/v1/article/"+query, nil)
|
||||||
|
if verified {
|
||||||
|
setJwtCookie(t, req, token, 1)
|
||||||
|
}
|
||||||
|
rec := httptest.NewRecorder()
|
||||||
|
router.ServeHTTP(rec, req)
|
||||||
|
var envelope paginationEnvelope
|
||||||
|
if rec.Code == http.StatusOK {
|
||||||
|
if err := json.Unmarshal(rec.Body.Bytes(), &envelope); err != nil {
|
||||||
|
t.Fatalf("failed to decode envelope: %v", err)
|
||||||
|
}
|
||||||
|
if envelope.Items == nil {
|
||||||
|
t.Fatalf("items must be [] rather than null: %s", rec.Body.String())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return rec, envelope
|
||||||
|
}
|
||||||
|
|
||||||
|
assertCounts := func(t *testing.T, envelope paginationEnvelope, all, online, draft int) {
|
||||||
|
t.Helper()
|
||||||
|
if envelope.Counts["all"] != all || envelope.Counts["online"] != online || envelope.Counts["draft"] != draft {
|
||||||
|
t.Fatalf("unexpected counts %v", envelope.Counts)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
t.Run("A bare request answers the envelope with the defaults", func(t *testing.T) {
|
||||||
|
repo := newMockArticleRepo()
|
||||||
|
seedPaginationArticles(repo, 30, 0)
|
||||||
|
rec, envelope := get(t, repo, "", false)
|
||||||
|
if rec.Code != http.StatusOK || envelope.Page != 1 || envelope.Size != 25 || envelope.Total != 30 || len(envelope.Items) != 25 {
|
||||||
|
t.Fatalf("unexpected response %d %+v", rec.Code, envelope)
|
||||||
|
}
|
||||||
|
assertCounts(t, envelope, 30, 30, 0)
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("Defaults when only one parameter is given", func(t *testing.T) {
|
||||||
|
cases := []struct {
|
||||||
|
query string
|
||||||
|
page, size, itemCount int
|
||||||
|
}{
|
||||||
|
{"?page=2", 2, 25, 25},
|
||||||
|
{"?page=3", 3, 25, 10},
|
||||||
|
{"?size=5", 1, 5, 5},
|
||||||
|
{"?size=50", 1, 50, 50},
|
||||||
|
}
|
||||||
|
for _, c := range cases {
|
||||||
|
repo := newMockArticleRepo()
|
||||||
|
seedPaginationArticles(repo, 60, 0)
|
||||||
|
_, envelope := get(t, repo, c.query, false)
|
||||||
|
if envelope.Page != c.page || envelope.Size != c.size || envelope.Total != 60 || len(envelope.Items) != c.itemCount {
|
||||||
|
t.Fatalf("%s: unexpected %+v", c.query, envelope)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("Items are ordered by last update, newest first, then id descending", func(t *testing.T) {
|
||||||
|
repo := newMockArticleRepo()
|
||||||
|
sept1 := time.Date(2026, 9, 1, 0, 0, 0, 0, time.UTC)
|
||||||
|
sept3 := time.Date(2026, 9, 3, 0, 0, 0, 0, time.UTC)
|
||||||
|
repo.articles[1] = domainArticle.Article{ID: 1, Title: "First article", IsOnline: true, UpdatedAt: sept1}
|
||||||
|
repo.articles[2] = domainArticle.Article{ID: 2, Title: "Second article", IsOnline: true, UpdatedAt: sept3}
|
||||||
|
repo.articles[3] = domainArticle.Article{ID: 3, Title: "Third article", IsOnline: true, UpdatedAt: sept3}
|
||||||
|
_, envelope := get(t, repo, "?size=5", false)
|
||||||
|
ids := itemIds(envelope)
|
||||||
|
if len(ids) != 3 || ids[0] != 3 || ids[1] != 2 || ids[2] != 1 {
|
||||||
|
t.Fatalf("unexpected order %v", ids)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("Pages partition the list with no overlap", func(t *testing.T) {
|
||||||
|
repo := newMockArticleRepo()
|
||||||
|
seedPaginationArticles(repo, 12, 0)
|
||||||
|
seen := map[int]bool{}
|
||||||
|
for page, want := range map[int]int{1: 5, 2: 5, 3: 2} {
|
||||||
|
_, envelope := get(t, repo, fmt.Sprintf("?page=%d&size=5", page), false)
|
||||||
|
if len(envelope.Items) != want || envelope.Total != 12 {
|
||||||
|
t.Fatalf("page %d unexpected %+v", page, envelope)
|
||||||
|
}
|
||||||
|
for _, id := range itemIds(envelope) {
|
||||||
|
if seen[id] {
|
||||||
|
t.Fatalf("id %d repeated", id)
|
||||||
|
}
|
||||||
|
seen[id] = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("A public caller's total and counts cover online articles only", func(t *testing.T) {
|
||||||
|
repo := newMockArticleRepo()
|
||||||
|
seedPaginationArticles(repo, 5, 3)
|
||||||
|
_, envelope := get(t, repo, "?size=5", false)
|
||||||
|
if envelope.Total != 5 {
|
||||||
|
t.Fatalf("unexpected total %d", envelope.Total)
|
||||||
|
}
|
||||||
|
assertCounts(t, envelope, 5, 5, 0)
|
||||||
|
for _, item := range envelope.Items {
|
||||||
|
if item["is_online"] == false {
|
||||||
|
t.Fatalf("offline item leaked")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("A verified caller sees offline articles in the page, the total and the counts", func(t *testing.T) {
|
||||||
|
repo := newMockArticleRepo()
|
||||||
|
seedPaginationArticles(repo, 5, 3)
|
||||||
|
_, envelope := get(t, repo, "?size=5", true)
|
||||||
|
if envelope.Total != 8 {
|
||||||
|
t.Fatalf("unexpected total %d", envelope.Total)
|
||||||
|
}
|
||||||
|
assertCounts(t, envelope, 8, 5, 3)
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("An unverified or invalid session is treated as public", func(t *testing.T) {
|
||||||
|
repo := newMockArticleRepo()
|
||||||
|
seedPaginationArticles(repo, 5, 3)
|
||||||
|
for _, cookie := range []string{"not-a-jwt", ""} {
|
||||||
|
router := newArticlesListRouter(repo, token)
|
||||||
|
req := httptest.NewRequest(http.MethodGet, "/v1/article/?size=5", nil)
|
||||||
|
if cookie != "" {
|
||||||
|
req.AddCookie(&http.Cookie{Name: "jwt", Value: cookie})
|
||||||
|
} else {
|
||||||
|
setJwtCookie(t, req, token, 99)
|
||||||
|
}
|
||||||
|
rec := httptest.NewRecorder()
|
||||||
|
router.ServeHTTP(rec, req)
|
||||||
|
var envelope paginationEnvelope
|
||||||
|
if err := json.Unmarshal(rec.Body.Bytes(), &envelope); err != nil || envelope.Total != 5 {
|
||||||
|
t.Fatalf("expected public total 5, got %s", rec.Body.String())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("A page beyond the last is empty with the real total", func(t *testing.T) {
|
||||||
|
repo := newMockArticleRepo()
|
||||||
|
seedPaginationArticles(repo, 12, 0)
|
||||||
|
rec, envelope := get(t, repo, "?page=99&size=5", false)
|
||||||
|
if rec.Code != http.StatusOK || len(envelope.Items) != 0 || envelope.Total != 12 || envelope.Page != 99 || envelope.Size != 5 || envelope.Counts["all"] != 12 {
|
||||||
|
t.Fatalf("unexpected %d %+v", rec.Code, envelope)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("No articles at all", func(t *testing.T) {
|
||||||
|
rec, envelope := get(t, newMockArticleRepo(), "", false)
|
||||||
|
if rec.Code != http.StatusOK || len(envelope.Items) != 0 || envelope.Total != 0 {
|
||||||
|
t.Fatalf("unexpected %d %+v", rec.Code, envelope)
|
||||||
|
}
|
||||||
|
assertCounts(t, envelope, 0, 0, 0)
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("Status filter", func(t *testing.T) {
|
||||||
|
for status, total := range map[string]int{"online": 4, "draft": 2} {
|
||||||
|
repo := newMockArticleRepo()
|
||||||
|
seedPaginationArticles(repo, 4, 2)
|
||||||
|
_, envelope := get(t, repo, "?status="+status, true)
|
||||||
|
if envelope.Total != total || len(envelope.Items) != total {
|
||||||
|
t.Fatalf("%s: unexpected %+v", status, envelope)
|
||||||
|
}
|
||||||
|
assertCounts(t, envelope, 6, 4, 2)
|
||||||
|
for _, item := range envelope.Items {
|
||||||
|
if item["is_online"] != (status == "online") {
|
||||||
|
t.Fatalf("%s: item does not match", status)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("A public caller asking for drafts gets nothing", func(t *testing.T) {
|
||||||
|
repo := newMockArticleRepo()
|
||||||
|
seedPaginationArticles(repo, 4, 2)
|
||||||
|
_, envelope := get(t, repo, "?status=draft", false)
|
||||||
|
if len(envelope.Items) != 0 || envelope.Total != 0 {
|
||||||
|
t.Fatalf("unexpected %+v", envelope)
|
||||||
|
}
|
||||||
|
assertCounts(t, envelope, 4, 4, 0)
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("Search narrows the page and the total but not the counts", func(t *testing.T) {
|
||||||
|
repo := newMockArticleRepo()
|
||||||
|
repo.articles[1] = domainArticle.Article{ID: 1, Title: "Choosing lime plaster for old stone walls", IsOnline: true}
|
||||||
|
repo.articles[2] = domainArticle.Article{ID: 2, Title: "How we price a bathroom renovation", IsOnline: true}
|
||||||
|
_, envelope := get(t, repo, "?q="+url.QueryEscape("PLÂSTER"), false)
|
||||||
|
ids := itemIds(envelope)
|
||||||
|
if envelope.Total != 1 || len(ids) != 1 || ids[0] != 1 {
|
||||||
|
t.Fatalf("unexpected %+v", envelope)
|
||||||
|
}
|
||||||
|
assertCounts(t, envelope, 2, 2, 0)
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("Search and status combine with paging", func(t *testing.T) {
|
||||||
|
repo := newMockArticleRepo()
|
||||||
|
for i := 0; i < 7; i++ {
|
||||||
|
id := uint32(i + 1)
|
||||||
|
repo.articles[id] = domainArticle.Article{ID: id, Title: fmt.Sprintf("Tile guide %d", i), IsOnline: false}
|
||||||
|
}
|
||||||
|
for i := 0; i < 3; i++ {
|
||||||
|
id := uint32(i + 8)
|
||||||
|
repo.articles[id] = domainArticle.Article{ID: id, Title: fmt.Sprintf("Tile story %d", i), IsOnline: true}
|
||||||
|
}
|
||||||
|
_, envelope := get(t, repo, "?q=tile&status=draft&size=5&page=2", true)
|
||||||
|
if envelope.Total != 7 || len(envelope.Items) != 2 || envelope.Counts["draft"] != 7 {
|
||||||
|
t.Fatalf("unexpected %+v", envelope)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("Search that matches nothing", func(t *testing.T) {
|
||||||
|
repo := newMockArticleRepo()
|
||||||
|
seedPaginationArticles(repo, 3, 0)
|
||||||
|
_, envelope := get(t, repo, "?q=zzzz", false)
|
||||||
|
if len(envelope.Items) != 0 || envelope.Total != 0 {
|
||||||
|
t.Fatalf("unexpected %+v", envelope)
|
||||||
|
}
|
||||||
|
assertCounts(t, envelope, 3, 3, 0)
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("Invalid parameters answer 400 like Activity", func(t *testing.T) {
|
||||||
|
queries := []string{
|
||||||
|
"page=0", "page=-1", "page=abc", "page=", "page=1.5", "size=0", "size=10", "size=200", "size=abc",
|
||||||
|
"status=archived", "status=", "q=" + strings.Repeat("a", 201), "page=0&size=5", "page=1&size=1000",
|
||||||
|
}
|
||||||
|
for _, query := range queries {
|
||||||
|
repo := newMockArticleRepo()
|
||||||
|
seedPaginationArticles(repo, 3, 0)
|
||||||
|
repo.fail.failNext("FindPage")
|
||||||
|
rec, _ := get(t, repo, "?"+query, false)
|
||||||
|
if rec.Code != http.StatusBadRequest || strings.TrimSpace(rec.Body.String()) != paginationBodyMismatch {
|
||||||
|
t.Fatalf("%q: unexpected %d %q", query, rec.Code, rec.Body.String())
|
||||||
|
}
|
||||||
|
if err := repo.fail.trigger("FindPage"); err == nil {
|
||||||
|
t.Fatalf("%q: the repository was called", query)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("Invalid format is reported first", func(t *testing.T) {
|
||||||
|
rec, _ := get(t, newMockArticleRepo(), "?page=0&format=pdf", false)
|
||||||
|
if rec.Code != http.StatusBadRequest || !strings.Contains(rec.Body.String(), "The format must be one of: markdown, html, json.") {
|
||||||
|
t.Fatalf("unexpected %d %q", rec.Code, rec.Body.String())
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("format and paging combine", func(t *testing.T) {
|
||||||
|
repo := newMockArticleRepo()
|
||||||
|
seedPaginationArticles(repo, 3, 0)
|
||||||
|
_, envelope := get(t, repo, "?size=5&format=html", false)
|
||||||
|
if envelope.Total != 3 || len(envelope.Items) != 3 {
|
||||||
|
t.Fatalf("unexpected %+v", envelope)
|
||||||
|
}
|
||||||
|
for _, item := range envelope.Items {
|
||||||
|
if item["body_format"] != "html" {
|
||||||
|
t.Fatalf("unexpected body_format %v", item["body_format"])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("Repository failure answers 500", func(t *testing.T) {
|
||||||
|
repo := newMockArticleRepo()
|
||||||
|
repo.fail.failNext("FindPage")
|
||||||
|
rec, _ := get(t, repo, "", false)
|
||||||
|
if rec.Code != http.StatusInternalServerError || strings.TrimSpace(rec.Body.String()) != "Failed to retrieve articles" {
|
||||||
|
t.Fatalf("unexpected %d %q", rec.Code, rec.Body.String())
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("Sort orders the whole list, not just the page", func(t *testing.T) {
|
||||||
|
cases := map[string][]int{
|
||||||
|
"updated_at:desc": {1, 3, 2},
|
||||||
|
"updated_at:asc": {2, 3, 1},
|
||||||
|
"created_at:desc": {2, 3, 1},
|
||||||
|
"created_at:asc": {1, 3, 2},
|
||||||
|
"title:asc": {2, 1, 3},
|
||||||
|
"title:desc": {3, 1, 2},
|
||||||
|
"status:asc": {2, 3, 1},
|
||||||
|
"status:desc": {3, 1, 2},
|
||||||
|
}
|
||||||
|
for sortValue, want := range cases {
|
||||||
|
repo := newMockArticleRepo()
|
||||||
|
seedSortArticles(repo)
|
||||||
|
_, envelope := get(t, repo, "?sort="+url.QueryEscape(sortValue), true)
|
||||||
|
if got := itemIds(envelope); fmt.Sprint(got) != fmt.Sprint(want) {
|
||||||
|
t.Fatalf("%s: got %v want %v", sortValue, got, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("No sort parameter keeps the default order", func(t *testing.T) {
|
||||||
|
repo := newMockArticleRepo()
|
||||||
|
seedSortArticles(repo)
|
||||||
|
_, envelope := get(t, repo, "", true)
|
||||||
|
if got := itemIds(envelope); fmt.Sprint(got) != "[1 3 2]" {
|
||||||
|
t.Fatalf("unexpected order %v", got)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("Equal sort keys fall back to id descending", func(t *testing.T) {
|
||||||
|
repo := newMockArticleRepo()
|
||||||
|
for id := uint32(1); id <= 3; id++ {
|
||||||
|
repo.articles[id] = domainArticle.Article{ID: id, Title: "Same", IsOnline: true}
|
||||||
|
}
|
||||||
|
_, envelope := get(t, repo, "?sort=title:asc", false)
|
||||||
|
if got := itemIds(envelope); fmt.Sprint(got) != "[3 2 1]" {
|
||||||
|
t.Fatalf("unexpected order %v", got)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("Sort is applied before paging", func(t *testing.T) {
|
||||||
|
repo := newMockArticleRepo()
|
||||||
|
for id := uint32(1); id <= 12; id++ {
|
||||||
|
repo.articles[id] = domainArticle.Article{ID: id, Title: fmt.Sprintf("Title %02d", id), IsOnline: true}
|
||||||
|
}
|
||||||
|
want := map[int]string{1: "[12 11 10 9 8]", 2: "[7 6 5 4 3]", 3: "[2 1]"}
|
||||||
|
for page, ids := range want {
|
||||||
|
_, envelope := get(t, repo, fmt.Sprintf("?sort=title:desc&size=5&page=%d", page), false)
|
||||||
|
if got := fmt.Sprint(itemIds(envelope)); got != ids {
|
||||||
|
t.Fatalf("page %d: got %s want %s", page, got, ids)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("Sort combines with search and status", func(t *testing.T) {
|
||||||
|
repo := newMockArticleRepo()
|
||||||
|
repo.articles[1] = domainArticle.Article{ID: 1, Title: "Tile A", IsOnline: false}
|
||||||
|
repo.articles[2] = domainArticle.Article{ID: 2, Title: "Tile C", IsOnline: false}
|
||||||
|
repo.articles[3] = domainArticle.Article{ID: 3, Title: "Tile B", IsOnline: false}
|
||||||
|
repo.articles[4] = domainArticle.Article{ID: 4, Title: "Tile D", IsOnline: true}
|
||||||
|
_, envelope := get(t, repo, "?q=tile&status=draft&sort=title:asc", true)
|
||||||
|
if got := fmt.Sprint(itemIds(envelope)); got != "[1 3 2]" || envelope.Total != 3 {
|
||||||
|
t.Fatalf("unexpected %s %+v", got, envelope)
|
||||||
|
}
|
||||||
|
assertCounts(t, envelope, 4, 1, 3)
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("Invalid sort answers 400", func(t *testing.T) {
|
||||||
|
for _, value := range []string{"title", "title:up", "body:asc", "", "updated_at", "title:asc;DROP TABLE", "TITLE:ASC"} {
|
||||||
|
repo := newMockArticleRepo()
|
||||||
|
repo.fail.failNext("FindPage")
|
||||||
|
rec, _ := get(t, repo, "?sort="+url.QueryEscape(value), false)
|
||||||
|
if rec.Code != http.StatusBadRequest || strings.TrimSpace(rec.Body.String()) != paginationBodyMismatch {
|
||||||
|
t.Fatalf("%q: unexpected %d %q", value, rec.Code, rec.Body.String())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("The SQLite repository pages, counts, searches and sorts", func(t *testing.T) {
|
||||||
|
db := openActivityDatabase(t)
|
||||||
|
repo := persistence.NewArticleRepository(db)
|
||||||
|
titles := []struct {
|
||||||
|
title string
|
||||||
|
online bool
|
||||||
|
}{{"Banana", true}, {"apple", false}, {"Cherry", true}, {"Plâtre fin", true}}
|
||||||
|
for _, entry := range titles {
|
||||||
|
if _, err := repo.Create(domainArticle.Article{Title: entry.title, IsOnline: entry.online}); err != nil {
|
||||||
|
t.Fatalf("seed failed: %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if _, err := repo.UpdateIsOnline(2, false); err != nil {
|
||||||
|
t.Fatalf("seed failed: %v", err)
|
||||||
|
}
|
||||||
|
idsOf := func(page domainArticle.PageResult) string {
|
||||||
|
ids := []uint32{}
|
||||||
|
for _, item := range page.Items {
|
||||||
|
ids = append(ids, item.ID)
|
||||||
|
}
|
||||||
|
return fmt.Sprint(ids)
|
||||||
|
}
|
||||||
|
sorted, err := repo.FindPage(domainArticle.Filters{Page: 1, Size: 5, Sort: domainArticle.Sort{Field: domainArticle.SortByTitle, Direction: domainArticle.SortAsc}})
|
||||||
|
if err != nil || idsOf(sorted) != "[2 1 3 4]" || sorted.Total != 4 {
|
||||||
|
t.Fatalf("title asc: %v %v %+v", err, idsOf(sorted), sorted)
|
||||||
|
}
|
||||||
|
byStatus, err := repo.FindPage(domainArticle.Filters{Page: 1, Size: 5, Sort: domainArticle.Sort{Field: domainArticle.SortByStatus, Direction: domainArticle.SortAsc}})
|
||||||
|
if err != nil || idsOf(byStatus) != "[2 4 3 1]" {
|
||||||
|
t.Fatalf("status asc: %v %v", err, idsOf(byStatus))
|
||||||
|
}
|
||||||
|
paged, err := repo.FindPage(domainArticle.Filters{Page: 2, Size: 2, Sort: domainArticle.Sort{Field: domainArticle.SortByTitle, Direction: domainArticle.SortDesc}})
|
||||||
|
if err != nil || idsOf(paged) != "[1 2]" || paged.Total != 4 {
|
||||||
|
t.Fatalf("paged: %v %v %+v", err, idsOf(paged), paged)
|
||||||
|
}
|
||||||
|
searched, err := repo.FindPage(domainArticle.Filters{Page: 1, Size: 5, Q: "PLATRE", Sort: domainArticle.Sort{Field: domainArticle.SortByTitle, Direction: domainArticle.SortAsc}})
|
||||||
|
if err != nil || idsOf(searched) != "[4]" || searched.Total != 1 {
|
||||||
|
t.Fatalf("search: %v %v %+v", err, idsOf(searched), searched)
|
||||||
|
}
|
||||||
|
multi, err := repo.FindPage(domainArticle.Filters{Page: 1, Size: 5, Q: "a", Sort: domainArticle.Sort{Field: domainArticle.SortByTitle, Direction: domainArticle.SortDesc}})
|
||||||
|
if err != nil || idsOf(multi) != "[4 1 2]" {
|
||||||
|
t.Fatalf("search sort: %v %v", err, idsOf(multi))
|
||||||
|
}
|
||||||
|
online := true
|
||||||
|
publicDraft, err := repo.FindPage(domainArticle.Filters{Page: 1, Size: 5, IsOnline: &online, Status: domainArticle.StatusDraft})
|
||||||
|
if err != nil || publicDraft.Total != 0 {
|
||||||
|
t.Fatalf("draft: %v %+v", err, publicDraft)
|
||||||
|
}
|
||||||
|
counts, err := repo.CountByVisibility(false)
|
||||||
|
if err != nil || counts != (domainArticle.Counts{All: 4, Online: 3, Draft: 1}) {
|
||||||
|
t.Fatalf("counts: %v %+v", err, counts)
|
||||||
|
}
|
||||||
|
publicCounts, err := repo.CountByVisibility(true)
|
||||||
|
if err != nil || publicCounts != (domainArticle.Counts{All: 3, Online: 3, Draft: 0}) {
|
||||||
|
t.Fatalf("public counts: %v %+v", err, publicCounts)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
t.Run("The SQLite repository pages search results and filters by visibility", func(t *testing.T) {
|
||||||
|
db := openActivityDatabase(t)
|
||||||
|
repo := persistence.NewArticleRepository(db)
|
||||||
|
for _, entry := range []struct {
|
||||||
|
title string
|
||||||
|
online bool
|
||||||
|
}{{"Alpha", true}, {"Bravo", false}, {"Charlie", true}, {"Delta", false}} {
|
||||||
|
if _, err := repo.Create(domainArticle.Article{Title: entry.title, IsOnline: entry.online}); err != nil {
|
||||||
|
t.Fatalf("seed failed: %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if _, err := repo.UpdateIsOnline(2, false); err != nil {
|
||||||
|
t.Fatalf("seed failed: %v", err)
|
||||||
|
}
|
||||||
|
titleAsc := domainArticle.Sort{Field: domainArticle.SortByTitle, Direction: domainArticle.SortAsc}
|
||||||
|
second, err := repo.FindPage(domainArticle.Filters{Page: 2, Size: 2, Q: "a", Sort: titleAsc})
|
||||||
|
if err != nil || second.Total != 4 || len(second.Items) != 2 || second.Items[0].Title != "Charlie" || second.Items[1].Title != "Delta" {
|
||||||
|
t.Fatalf("search page 2: %v %+v", err, second)
|
||||||
|
}
|
||||||
|
beyond, err := repo.FindPage(domainArticle.Filters{Page: 9, Size: 2, Q: "a", Sort: titleAsc})
|
||||||
|
if err != nil || beyond.Total != 4 || len(beyond.Items) != 0 {
|
||||||
|
t.Fatalf("search beyond: %v %+v", err, beyond)
|
||||||
|
}
|
||||||
|
online := true
|
||||||
|
onlyOnline, err := repo.FindByFilters(domainArticle.Filters{IsOnline: &online})
|
||||||
|
if err != nil || len(onlyOnline) != 2 {
|
||||||
|
t.Fatalf("online filter: %v %d", err, len(onlyOnline))
|
||||||
|
}
|
||||||
|
everything, err := repo.FindByFilters(domainArticle.Filters{})
|
||||||
|
if err != nil || len(everything) != 4 {
|
||||||
|
t.Fatalf("no filter: %v %d", err, len(everything))
|
||||||
|
}
|
||||||
|
drafts, err := repo.FindPage(domainArticle.Filters{Page: 1, Size: 5, Status: domainArticle.StatusDraft, Sort: titleAsc})
|
||||||
|
if err != nil || drafts.Total != 2 || len(drafts.Items) != 2 {
|
||||||
|
t.Fatalf("drafts: %v %+v", err, drafts)
|
||||||
|
}
|
||||||
|
onlineStatus, err := repo.FindPage(domainArticle.Filters{Page: 1, Size: 5, Status: domainArticle.StatusOnline, Sort: titleAsc})
|
||||||
|
if err != nil || onlineStatus.Total != 2 {
|
||||||
|
t.Fatalf("online status: %v %+v", err, onlineStatus)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("The SQLite repository surfaces database failures", func(t *testing.T) {
|
||||||
|
db := openActivityDatabase(t)
|
||||||
|
repo := persistence.NewArticleRepository(db)
|
||||||
|
sqlDb, err := db.DB()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("sql handle: %v", err)
|
||||||
|
}
|
||||||
|
if err := sqlDb.Close(); err != nil {
|
||||||
|
t.Fatalf("close: %v", err)
|
||||||
|
}
|
||||||
|
sort := domainArticle.Sort{Field: domainArticle.SortByTitle, Direction: domainArticle.SortAsc}
|
||||||
|
if _, err := repo.FindPage(domainArticle.Filters{Page: 1, Size: 5, Sort: sort}); err == nil {
|
||||||
|
t.Fatal("plain page should fail")
|
||||||
|
}
|
||||||
|
if _, err := repo.FindPage(domainArticle.Filters{Page: 1, Size: 5, Q: "a", Sort: sort}); err == nil {
|
||||||
|
t.Fatal("search page should fail")
|
||||||
|
}
|
||||||
|
if _, err := repo.CountByVisibility(false); err == nil {
|
||||||
|
t.Fatal("counts should fail")
|
||||||
|
}
|
||||||
|
if _, err := repo.CountByVisibility(true); err == nil {
|
||||||
|
t.Fatal("public counts should fail")
|
||||||
|
}
|
||||||
|
if _, err := repo.FindByFilters(domainArticle.Filters{}); err == nil {
|
||||||
|
t.Fatal("find by filters should fail")
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("The SQLite repository clamps invalid paging, trims the search and skips vanished rows", func(t *testing.T) {
|
||||||
|
db := openActivityDatabase(t)
|
||||||
|
repo := persistence.NewArticleRepository(db)
|
||||||
|
for _, title := range []string{"Alpha", "Beta", "Gamma"} {
|
||||||
|
if _, err := repo.Create(domainArticle.Article{Title: title, IsOnline: true}); err != nil {
|
||||||
|
t.Fatalf("seed failed: %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
titleAsc := domainArticle.Sort{Field: domainArticle.SortByTitle, Direction: domainArticle.SortAsc}
|
||||||
|
for _, page := range []int{0, -3} {
|
||||||
|
searched, err := repo.FindPage(domainArticle.Filters{Page: page, Size: 2, Q: "a", Sort: titleAsc})
|
||||||
|
if err != nil || searched.Total != 3 || len(searched.Items) != 2 || searched.Items[0].Title != "Alpha" {
|
||||||
|
t.Fatalf("search page %d: %v %+v", page, err, searched)
|
||||||
|
}
|
||||||
|
plain, err := repo.FindPage(domainArticle.Filters{Page: page, Size: 2, Sort: titleAsc})
|
||||||
|
if err != nil || plain.Total != 3 || len(plain.Items) != 2 || plain.Items[0].Title != "Alpha" {
|
||||||
|
t.Fatalf("plain page %d: %v %+v", page, err, plain)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
trimmed, err := repo.FindPage(domainArticle.Filters{Page: 1, Size: 5, Q: " mm ", Sort: titleAsc})
|
||||||
|
if err != nil || trimmed.Total != 1 || trimmed.Items[0].Title != "Gamma" {
|
||||||
|
t.Fatalf("trimmed search: %v %+v", err, trimmed)
|
||||||
|
}
|
||||||
|
spaced, err := repo.FindPage(domainArticle.Filters{Page: 1, Size: 5, Q: " a", Sort: titleAsc})
|
||||||
|
if err != nil || spaced.Total != 3 {
|
||||||
|
t.Fatalf("leading space search: %v %+v", err, spaced)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestArticlesPaginationUseCase(t *testing.T) {
|
||||||
|
t.Run("The typed sort reaches the repository and an absent sort keeps updated_at descending", func(t *testing.T) {
|
||||||
|
repo := newMockArticleRepo()
|
||||||
|
seedSortArticles(repo)
|
||||||
|
uc := useCases.NewListArticlesUseCase(repo, &fakeBodyRenderer{})
|
||||||
|
sorted, err := uc.ListArticlesPage(useCases.ListArticlesCommand{Format: domainArticle.BodyFormatHTML, Verified: true, Page: 1, Size: 25, Sort: domainArticle.Sort{Field: domainArticle.SortByTitle, Direction: domainArticle.SortAsc}})
|
||||||
|
if err != nil || sorted.Total != 3 || sorted.Counts.All != 3 {
|
||||||
|
t.Fatalf("unexpected %v %+v", err, sorted)
|
||||||
|
}
|
||||||
|
if sorted.Items[0].ID != 2 || sorted.Items[2].ID != 3 {
|
||||||
|
t.Fatalf("title ascending expected apple first, Cherry last: %v", sorted.Items)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("A repository error is propagated from both queries", func(t *testing.T) {
|
||||||
|
sentinel := errors.New("boom")
|
||||||
|
for _, method := range []string{"FindPage", "CountByVisibility"} {
|
||||||
|
repo := newMockArticleRepo()
|
||||||
|
seedPaginationArticles(repo, 3, 0)
|
||||||
|
repo.fail.failNextWith(method, sentinel)
|
||||||
|
uc := useCases.NewListArticlesUseCase(repo, &fakeBodyRenderer{})
|
||||||
|
_, err := uc.ListArticlesPage(useCases.ListArticlesCommand{Format: domainArticle.BodyFormatHTML, Verified: true, Page: 1, Size: 25})
|
||||||
|
if !errors.Is(err, sentinel) {
|
||||||
|
t.Fatalf("%s: expected sentinel, got %v", method, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("The unpaged Filters call still returns every article", func(t *testing.T) {
|
||||||
|
repo := newMockArticleRepo()
|
||||||
|
seedPaginationArticles(repo, 30, 5)
|
||||||
|
all, err := repo.FindByFilters(domainArticle.Filters{})
|
||||||
|
if err != nil || len(all) != 35 {
|
||||||
|
t.Fatalf("unexpected %d %v", len(all), err)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
@@ -164,31 +164,6 @@ func TestEditArticleBodyHttp(t *testing.T) {
|
|||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
validationCases := []struct {
|
|
||||||
name string
|
|
||||||
payload string
|
|
||||||
}{
|
|
||||||
{"empty body", `{"body": ""}`},
|
|
||||||
{"body over 10000 characters", `{"body": "` + strings.Repeat("a", 10001) + `"}`},
|
|
||||||
}
|
|
||||||
for _, tc := range validationCases {
|
|
||||||
t.Run("A body value that fails validation answers 400: "+tc.name, func(t *testing.T) {
|
|
||||||
repo := newEditArticleBodyTestRepo()
|
|
||||||
router := newEditArticleBodyRouter(repo, token)
|
|
||||||
req := newEditArticleBodyRequest(http.MethodPatch, "/v1/article/1", tc.payload)
|
|
||||||
setEditArticleBodyJwtCookie(t, req, token)
|
|
||||||
rec := httptest.NewRecorder()
|
|
||||||
router.ServeHTTP(rec, req)
|
|
||||||
|
|
||||||
if rec.Code != http.StatusBadRequest {
|
|
||||||
t.Fatalf("expected status 400, got %d", rec.Code)
|
|
||||||
}
|
|
||||||
if repo.articles[1].Body != "Old body text" {
|
|
||||||
t.Errorf("expected stored body to be unchanged, got %q", repo.articles[1].Body)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
t.Run("A response write failure is logged", func(t *testing.T) {
|
t.Run("A response write failure is logged", func(t *testing.T) {
|
||||||
repo := newEditArticleBodyTestRepo()
|
repo := newEditArticleBodyTestRepo()
|
||||||
router := newEditArticleBodyRouter(repo, token)
|
router := newEditArticleBodyRouter(repo, token)
|
||||||
|
|||||||
@@ -0,0 +1,67 @@
|
|||||||
|
package test
|
||||||
|
|
||||||
|
import (
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"RenewCMS/internal/domain/image"
|
||||||
|
)
|
||||||
|
|
||||||
|
func sortedIDs(order image.Sort, imgs []image.Image) []uint32 {
|
||||||
|
image.SortImages(imgs, order)
|
||||||
|
ids := make([]uint32, len(imgs))
|
||||||
|
for i, img := range imgs {
|
||||||
|
ids[i] = img.ID
|
||||||
|
}
|
||||||
|
return ids
|
||||||
|
}
|
||||||
|
|
||||||
|
func equalIDs(a, b []uint32) bool {
|
||||||
|
if len(a) != len(b) {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
for i := range a {
|
||||||
|
if a[i] != b[i] {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestImageSortTieBreaks(t *testing.T) {
|
||||||
|
now := time.Now()
|
||||||
|
build := func() []image.Image {
|
||||||
|
return []image.Image{
|
||||||
|
{ID: 2, Filename: "a.png", Size: 10, CreatedAt: now},
|
||||||
|
{ID: 1, Filename: "a.png", Size: 10, CreatedAt: now},
|
||||||
|
{ID: 3, Filename: "b.png", Size: 20, CreatedAt: now.Add(time.Hour)},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
cases := []struct {
|
||||||
|
order image.Sort
|
||||||
|
want []uint32
|
||||||
|
}{
|
||||||
|
{image.SortOldest, []uint32{1, 2, 3}},
|
||||||
|
{image.SortNewest, []uint32{3, 2, 1}},
|
||||||
|
{image.SortName, []uint32{1, 2, 3}},
|
||||||
|
{image.SortLargest, []uint32{3, 1, 2}},
|
||||||
|
}
|
||||||
|
for _, c := range cases {
|
||||||
|
if got := sortedIDs(c.order, build()); !equalIDs(got, c.want) {
|
||||||
|
t.Errorf("%s: got %v want %v", c.order, got, c.want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestImageSortByTotalSizeTieBreak(t *testing.T) {
|
||||||
|
imgs := []image.Image{
|
||||||
|
{ID: 2, Path: "/u/x.png", Size: 10},
|
||||||
|
{ID: 1, Path: "/u/y.png", Size: 10},
|
||||||
|
{ID: 3, Path: "/u/z.png", Size: 11},
|
||||||
|
}
|
||||||
|
image.SortImagesByTotalSize(imgs, nil)
|
||||||
|
got := []uint32{imgs[0].ID, imgs[1].ID, imgs[2].ID}
|
||||||
|
if !equalIDs(got, []uint32{3, 1, 2}) {
|
||||||
|
t.Fatalf("got %v", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -75,6 +75,7 @@ type mockImageRepo struct {
|
|||||||
images map[uint32]imageDomain.Image
|
images map[uint32]imageDomain.Image
|
||||||
nextID uint32
|
nextID uint32
|
||||||
fail failSwitch
|
fail failSwitch
|
||||||
|
listCalls int
|
||||||
failDeleteFor map[uint32]error
|
failDeleteFor map[uint32]error
|
||||||
deleteCalls []uint32
|
deleteCalls []uint32
|
||||||
createCalls int
|
createCalls int
|
||||||
@@ -169,6 +170,7 @@ func (m *mockImageRepo) Delete(id uint32) error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (m *mockImageRepo) List(query imageDomain.SearchQuery) ([]imageDomain.Image, error) {
|
func (m *mockImageRepo) List(query imageDomain.SearchQuery) ([]imageDomain.Image, error) {
|
||||||
|
m.listCalls++
|
||||||
if err := m.fail.trigger("List"); err != nil {
|
if err := m.fail.trigger("List"); err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,9 +3,6 @@ package test
|
|||||||
import (
|
import (
|
||||||
domainArticle "RenewCMS/internal/domain/article"
|
domainArticle "RenewCMS/internal/domain/article"
|
||||||
"RenewCMS/internal/infrastructure/useCases"
|
"RenewCMS/internal/infrastructure/useCases"
|
||||||
"encoding/base64"
|
|
||||||
"net/http"
|
|
||||||
"net/url"
|
|
||||||
"reflect"
|
"reflect"
|
||||||
"testing"
|
"testing"
|
||||||
)
|
)
|
||||||
@@ -20,38 +17,6 @@ func (r *mediaOrderRecordingArticleRepo) UpdateBody(id uint32, body string) (dom
|
|||||||
return r.mockArticleRepo.UpdateBody(id, body)
|
return r.mockArticleRepo.UpdateBody(id, body)
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestMediaCursorBoundaries(t *testing.T) {
|
|
||||||
seed := func(env *mediaEnv) {
|
|
||||||
env.seedImage(1, "a.jpg", 10, "image/jpeg", 3, 2, hashA, 1)
|
|
||||||
env.seedImage(2, "b.jpg", 20, "image/jpeg", 3, 2, hashB, 1)
|
|
||||||
}
|
|
||||||
encode := func(raw string) string {
|
|
||||||
return url.QueryEscape(base64.RawURLEncoding.EncodeToString([]byte(raw)))
|
|
||||||
}
|
|
||||||
|
|
||||||
t.Run("A cursor at offset zero is accepted and starts from the first item", func(t *testing.T) {
|
|
||||||
env := newMediaEnv(t)
|
|
||||||
seed(env)
|
|
||||||
|
|
||||||
rec := env.send(t, http.MethodGet, "/v1/media/?cursor="+encode("offset:0"), "", mediaVerifiedUserId)
|
|
||||||
|
|
||||||
if rec.Code != http.StatusOK {
|
|
||||||
t.Fatalf("expected status 200, got %d", rec.Code)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
|
|
||||||
t.Run("A negative cursor offset is refused", func(t *testing.T) {
|
|
||||||
env := newMediaEnv(t)
|
|
||||||
seed(env)
|
|
||||||
|
|
||||||
rec := env.send(t, http.MethodGet, "/v1/media/?cursor="+encode("offset:-1"), "", mediaVerifiedUserId)
|
|
||||||
|
|
||||||
if rec.Code != http.StatusBadRequest {
|
|
||||||
t.Fatalf("expected status 400, got %d", rec.Code)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestMediaMergeRewritesArticlesInIdOrder(t *testing.T) {
|
func TestMediaMergeRewritesArticlesInIdOrder(t *testing.T) {
|
||||||
env := newMediaEnv(t)
|
env := newMediaEnv(t)
|
||||||
env.seedImage(2, "floorboards.jpg", 20, "image/jpeg", 3, 2, hashB, 1)
|
env.seedImage(2, "floorboards.jpg", 20, "image/jpeg", 3, 2, hashB, 1)
|
||||||
|
|||||||
@@ -32,6 +32,7 @@ const (
|
|||||||
type mediaEnv struct {
|
type mediaEnv struct {
|
||||||
articles *mockArticleRepo
|
articles *mockArticleRepo
|
||||||
images *mockImageRepo
|
images *mockImageRepo
|
||||||
|
variants *mockVariantFileRepo
|
||||||
storage *mockImageStorage
|
storage *mockImageStorage
|
||||||
users *mockUserRepo
|
users *mockUserRepo
|
||||||
purgeSettings *mockPurgeSettingsRepo
|
purgeSettings *mockPurgeSettingsRepo
|
||||||
@@ -48,6 +49,7 @@ func newMediaEnv(t *testing.T) *mediaEnv {
|
|||||||
env := &mediaEnv{
|
env := &mediaEnv{
|
||||||
articles: newMockArticleRepo(),
|
articles: newMockArticleRepo(),
|
||||||
images: newMockImageRepo(),
|
images: newMockImageRepo(),
|
||||||
|
variants: newMockVariantFileRepo(),
|
||||||
storage: newMockImageStorage(),
|
storage: newMockImageStorage(),
|
||||||
users: newMockUserRepo(),
|
users: newMockUserRepo(),
|
||||||
token: jwtauth.New("HS256", []byte("test-secret"), nil),
|
token: jwtauth.New("HS256", []byte("test-secret"), nil),
|
||||||
@@ -72,7 +74,7 @@ func newMediaEnv(t *testing.T) *mediaEnv {
|
|||||||
GetUserUseCase: useCases.NewGetUserUseCase(env.users),
|
GetUserUseCase: useCases.NewGetUserUseCase(env.users),
|
||||||
CreateImageUseCase: useCases.NewCreateImageUseCase(env.images, env.storage, discardRecorder),
|
CreateImageUseCase: useCases.NewCreateImageUseCase(env.images, env.storage, discardRecorder),
|
||||||
GenerateVariantsOnUploadUseCase: newInertGenerateOnUploadUseCase(),
|
GenerateVariantsOnUploadUseCase: newInertGenerateOnUploadUseCase(),
|
||||||
ListMediaUseCase: useCases.NewListMediaUseCase(env.images, env.articles, env.users, newMockVariantFileRepo()),
|
ListMediaUseCase: useCases.NewListMediaUseCase(env.images, env.articles, env.users, env.variants),
|
||||||
RenameMediaUseCase: useCases.NewRenameMediaUseCase(env.images, discardRecorder),
|
RenameMediaUseCase: useCases.NewRenameMediaUseCase(env.images, discardRecorder),
|
||||||
DeleteMediaUseCase: useCases.NewDeleteMediaUseCase(env.images, env.storage, newMockVariantFileRepo(), discardRecorder),
|
DeleteMediaUseCase: useCases.NewDeleteMediaUseCase(env.images, env.storage, newMockVariantFileRepo(), discardRecorder),
|
||||||
MergeMediaUseCase: merge,
|
MergeMediaUseCase: merge,
|
||||||
|
|||||||
@@ -7,7 +7,6 @@ import (
|
|||||||
"encoding/json"
|
"encoding/json"
|
||||||
"errors"
|
"errors"
|
||||||
"net/http"
|
"net/http"
|
||||||
"net/url"
|
|
||||||
"os/exec"
|
"os/exec"
|
||||||
"reflect"
|
"reflect"
|
||||||
"regexp"
|
"regexp"
|
||||||
@@ -35,9 +34,11 @@ func seedListingLibrary(env *mediaEnv) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type listBody struct {
|
type listBody struct {
|
||||||
Items []map[string]any `json:"items"`
|
Items []map[string]any `json:"items"`
|
||||||
NextCursor *string `json:"next_cursor"`
|
Total int `json:"total"`
|
||||||
Counts map[string]int `json:"counts"`
|
Page int `json:"page"`
|
||||||
|
Size int `json:"size"`
|
||||||
|
Counts map[string]int `json:"counts"`
|
||||||
}
|
}
|
||||||
|
|
||||||
func (e *mediaEnv) list(t *testing.T, query string) (listBody, string) {
|
func (e *mediaEnv) list(t *testing.T, query string) (listBody, string) {
|
||||||
@@ -155,11 +156,11 @@ func TestMediaListing(t *testing.T) {
|
|||||||
if !strings.Contains(raw, `"width":null`) || !strings.Contains(raw, `"height":null`) {
|
if !strings.Contains(raw, `"width":null`) || !strings.Contains(raw, `"height":null`) {
|
||||||
t.Errorf("expected null width and height in the raw body, got %s", raw)
|
t.Errorf("expected null width and height in the raw body, got %s", raw)
|
||||||
}
|
}
|
||||||
if got.NextCursor != nil {
|
if strings.Contains(raw, "next_cursor") {
|
||||||
t.Errorf("expected next_cursor null, got %v", *got.NextCursor)
|
t.Errorf("expected no next_cursor in the raw body")
|
||||||
}
|
}
|
||||||
if !strings.Contains(raw, `"next_cursor":null`) {
|
if got.Total != 5 || got.Page != 1 || got.Size != 25 {
|
||||||
t.Errorf("expected next_cursor null in the raw body")
|
t.Errorf("unexpected paging %d %d %d", got.Total, got.Page, got.Size)
|
||||||
}
|
}
|
||||||
if !reflect.DeepEqual(got.Counts, map[string]int{"all": 5, "unused": 3, "duplicates": 1}) {
|
if !reflect.DeepEqual(got.Counts, map[string]int{"all": 5, "unused": 3, "duplicates": 1}) {
|
||||||
t.Errorf("unexpected counts %v", got.Counts)
|
t.Errorf("unexpected counts %v", got.Counts)
|
||||||
@@ -293,31 +294,26 @@ func TestMediaListing(t *testing.T) {
|
|||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
t.Run("limit and cursor page through the list", func(t *testing.T) {
|
t.Run("page and size page through the list", func(t *testing.T) {
|
||||||
env := newMediaEnv(t)
|
env := newMediaEnv(t)
|
||||||
seedListingLibrary(env)
|
for id := uint32(1); id <= 12; id++ {
|
||||||
|
env.seedImage(id, "image.jpg", 10, "image/jpeg", 3, 2, hashA, 1)
|
||||||
first, _ := env.list(t, "?limit=2")
|
|
||||||
expectIds(t, idsOf(first.Items), []uint32{5, 4})
|
|
||||||
if first.NextCursor == nil || *first.NextCursor == "" {
|
|
||||||
t.Fatalf("expected a next_cursor on page 1")
|
|
||||||
}
|
}
|
||||||
|
|
||||||
second, _ := env.list(t, "?limit=2&cursor="+url.QueryEscape(*first.NextCursor))
|
first, _ := env.list(t, "?size=5&page=1")
|
||||||
expectIds(t, idsOf(second.Items), []uint32{3, 2})
|
second, _ := env.list(t, "?size=5&page=2")
|
||||||
if second.NextCursor == nil || *second.NextCursor == "" {
|
third, _ := env.list(t, "?size=5&page=3")
|
||||||
t.Fatalf("expected a next_cursor on page 2")
|
|
||||||
}
|
|
||||||
|
|
||||||
third, _ := env.list(t, "?limit=2&cursor="+url.QueryEscape(*second.NextCursor))
|
expectIds(t, idsOf(first.Items), []uint32{12, 11, 10, 9, 8})
|
||||||
expectIds(t, idsOf(third.Items), []uint32{1})
|
expectIds(t, idsOf(second.Items), []uint32{7, 6, 5, 4, 3})
|
||||||
if third.NextCursor != nil {
|
expectIds(t, idsOf(third.Items), []uint32{2, 1})
|
||||||
t.Errorf("expected next_cursor null on the last page, got %v", *third.NextCursor)
|
if third.Total != 12 || third.Page != 3 || third.Size != 5 {
|
||||||
|
t.Errorf("unexpected paging %d %d %d", third.Total, third.Page, third.Size)
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
t.Run("A malformed query answers 400", func(t *testing.T) {
|
t.Run("A malformed query answers 400", func(t *testing.T) {
|
||||||
for _, query := range []string{"filter=bogus", "sort=bogus", "limit=0", "limit=101", "limit=abc", "cursor=%%%", "cursor=bogus", "hash=notahash"} {
|
for _, query := range []string{"filter=bogus", "sort=bogus", "page=0", "page=abc", "size=10", "size=200", "size=", "hash=notahash"} {
|
||||||
t.Run(query, func(t *testing.T) {
|
t.Run(query, func(t *testing.T) {
|
||||||
env := newMediaEnv(t)
|
env := newMediaEnv(t)
|
||||||
seedListingLibrary(env)
|
seedListingLibrary(env)
|
||||||
|
|||||||
@@ -0,0 +1,349 @@
|
|||||||
|
package test
|
||||||
|
|
||||||
|
import (
|
||||||
|
"RenewCMS/api/pkg/apperr"
|
||||||
|
domainImage "RenewCMS/internal/domain/image"
|
||||||
|
"RenewCMS/internal/infrastructure/useCases"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"net/http"
|
||||||
|
"net/url"
|
||||||
|
"reflect"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
func seedBulkImages(env *mediaEnv, count int) {
|
||||||
|
for id := uint32(1); id <= uint32(count); id++ {
|
||||||
|
env.seedImage(id, fmt.Sprintf("image-%02d.jpg", id), int64(id)*10, "image/jpeg", 3, 2, hashA, 1)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestMediaPaginationEnvelope(t *testing.T) {
|
||||||
|
t.Run("A bare request answers the envelope with the defaults", func(t *testing.T) {
|
||||||
|
env := newMediaEnv(t)
|
||||||
|
seedBulkImages(env, 30)
|
||||||
|
|
||||||
|
got, raw := env.list(t, "")
|
||||||
|
|
||||||
|
if got.Page != 1 || got.Size != 25 || got.Total != 30 || len(got.Items) != 25 {
|
||||||
|
t.Errorf("unexpected envelope %d %d %d %d", got.Page, got.Size, got.Total, len(got.Items))
|
||||||
|
}
|
||||||
|
if got.Counts["all"] != 30 {
|
||||||
|
t.Errorf("unexpected counts %v", got.Counts)
|
||||||
|
}
|
||||||
|
if strings.Contains(raw, "next_cursor") {
|
||||||
|
t.Errorf("unexpected next_cursor in %s", raw)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("Defaults when only one parameter is given", func(t *testing.T) {
|
||||||
|
examples := []struct {
|
||||||
|
query string
|
||||||
|
page int
|
||||||
|
size int
|
||||||
|
count int
|
||||||
|
}{
|
||||||
|
{"?page=2", 2, 25, 25},
|
||||||
|
{"?page=3", 3, 25, 10},
|
||||||
|
{"?size=5", 1, 5, 5},
|
||||||
|
{"?size=50", 1, 50, 50},
|
||||||
|
{"?size=100", 1, 100, 60},
|
||||||
|
}
|
||||||
|
for _, example := range examples {
|
||||||
|
t.Run(example.query, func(t *testing.T) {
|
||||||
|
env := newMediaEnv(t)
|
||||||
|
seedBulkImages(env, 60)
|
||||||
|
|
||||||
|
got, _ := env.list(t, example.query)
|
||||||
|
|
||||||
|
if got.Page != example.page || got.Size != example.size || got.Total != 60 || len(got.Items) != example.count {
|
||||||
|
t.Errorf("unexpected envelope %d %d %d %d", got.Page, got.Size, got.Total, len(got.Items))
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("Pages partition the list with no overlap", func(t *testing.T) {
|
||||||
|
env := newMediaEnv(t)
|
||||||
|
seedBulkImages(env, 12)
|
||||||
|
seen := map[uint32]bool{}
|
||||||
|
|
||||||
|
for page, want := range map[int]int{1: 5, 2: 5, 3: 2} {
|
||||||
|
got, _ := env.list(t, fmt.Sprintf("?page=%d&size=5", page))
|
||||||
|
if len(got.Items) != want || got.Total != 12 {
|
||||||
|
t.Errorf("page %d holds %d of %d", page, len(got.Items), got.Total)
|
||||||
|
}
|
||||||
|
for _, id := range idsOf(got.Items) {
|
||||||
|
if seen[id] {
|
||||||
|
t.Errorf("id %d repeats", id)
|
||||||
|
}
|
||||||
|
seen[id] = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if len(seen) != 12 {
|
||||||
|
t.Errorf("expected 12 distinct ids, got %d", len(seen))
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("Newest first with the id tie-break", func(t *testing.T) {
|
||||||
|
env := newMediaEnv(t)
|
||||||
|
for id := uint32(1); id <= 3; id++ {
|
||||||
|
env.seedImage(id, "a.jpg", 10, "image/jpeg", 3, 2, hashA, 1)
|
||||||
|
}
|
||||||
|
sameDay := time.Date(2026, time.September, 3, 0, 0, 0, 0, time.UTC)
|
||||||
|
for _, id := range []uint32{2, 3} {
|
||||||
|
img := env.images.images[id]
|
||||||
|
img.CreatedAt = sameDay
|
||||||
|
env.images.images[id] = img
|
||||||
|
}
|
||||||
|
first := env.images.images[1]
|
||||||
|
first.CreatedAt = sameDay.AddDate(0, 0, -2)
|
||||||
|
env.images.images[1] = first
|
||||||
|
|
||||||
|
got, _ := env.list(t, "?size=5")
|
||||||
|
|
||||||
|
expectIds(t, idsOf(got.Items), []uint32{3, 2, 1})
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("Sort orders the whole library before paging", func(t *testing.T) {
|
||||||
|
names := []string{"mango", "Apple", "cherry", "banana", "Zucchini", "date", "fig", "Grape", "kiwi", "lemon", "olive", "pear"}
|
||||||
|
sizes := []int64{50, 120, 10, 90, 30, 110, 70, 20, 100, 60, 40, 80}
|
||||||
|
examples := map[string][]uint32{
|
||||||
|
"newest": {12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1},
|
||||||
|
"oldest": {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12},
|
||||||
|
"largest": {2, 6, 9, 4, 12, 7, 10, 1, 11, 5, 8, 3},
|
||||||
|
"name": {2, 4, 3, 6, 7, 8, 9, 10, 1, 11, 12, 5},
|
||||||
|
"total_size": {3, 8, 2, 6, 9, 4, 12, 7, 10, 1, 11, 5},
|
||||||
|
}
|
||||||
|
for sortName, want := range examples {
|
||||||
|
t.Run(sortName, func(t *testing.T) {
|
||||||
|
env := newMediaEnv(t)
|
||||||
|
for index, name := range names {
|
||||||
|
env.seedImage(uint32(index+1), name+".jpg", sizes[index], "image/jpeg", 3, 2, hashA, 1)
|
||||||
|
}
|
||||||
|
for id, bytes := range map[uint32]int64{3: 500, 8: 200} {
|
||||||
|
_, _ = env.variants.Save(domainImage.VariantFile{VariantName: "hero", SourceName: domainImage.StoredName(env.images.images[id].Path), CachedName: fmt.Sprintf("c%d", id), ContentType: "image/jpeg", Size: bytes, Fingerprint: "f"})
|
||||||
|
}
|
||||||
|
var all []uint32
|
||||||
|
for page := 1; page <= 3; page++ {
|
||||||
|
got, _ := env.list(t, fmt.Sprintf("?sort=%s&size=5&page=%d", sortName, page))
|
||||||
|
all = append(all, idsOf(got.Items)...)
|
||||||
|
}
|
||||||
|
expectIds(t, all, want)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("Filter and search narrow total and items but not the counts", func(t *testing.T) {
|
||||||
|
env := newMediaEnv(t)
|
||||||
|
seedBulkImages(env, 40)
|
||||||
|
for id := uint32(1); id <= 34; id++ {
|
||||||
|
env.seedArticle(id, "Article", true, env.urlOf(id))
|
||||||
|
}
|
||||||
|
|
||||||
|
unused, _ := env.list(t, "?filter=unused&size=5")
|
||||||
|
search, _ := env.list(t, "?q=image-1&size=5&page=2")
|
||||||
|
|
||||||
|
if unused.Total != 6 || len(unused.Items) != 5 || unused.Counts["all"] != 40 || unused.Counts["unused"] != 6 {
|
||||||
|
t.Errorf("unexpected unused page %d %d %v", unused.Total, len(unused.Items), unused.Counts)
|
||||||
|
}
|
||||||
|
if search.Total != 10 || len(search.Items) != 5 || search.Counts["all"] != 40 {
|
||||||
|
t.Errorf("unexpected search page %d %d %v", search.Total, len(search.Items), search.Counts)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("Hash lookup returns every copy in one page", func(t *testing.T) {
|
||||||
|
env := newMediaEnv(t)
|
||||||
|
seedListingLibrary(env)
|
||||||
|
env.seedImage(6, "floorboards-2.jpg", 10, "image/jpeg", 3, 2, hashB, 1)
|
||||||
|
|
||||||
|
explicit, _ := env.list(t, "?hash="+hashB+"&page=1&size=100")
|
||||||
|
bare, _ := env.list(t, "?hash="+hashB)
|
||||||
|
|
||||||
|
if explicit.Total != 3 || len(explicit.Items) != 3 {
|
||||||
|
t.Errorf("unexpected explicit lookup %d %d", explicit.Total, len(explicit.Items))
|
||||||
|
}
|
||||||
|
if bare.Page != 1 || bare.Size != 25 || bare.Total != 3 || len(bare.Items) != 3 {
|
||||||
|
t.Errorf("unexpected bare lookup %d %d %d %d", bare.Page, bare.Size, bare.Total, len(bare.Items))
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("A page beyond the last is empty with the real total", func(t *testing.T) {
|
||||||
|
env := newMediaEnv(t)
|
||||||
|
seedBulkImages(env, 12)
|
||||||
|
|
||||||
|
got, raw := env.list(t, "?page=99&size=5")
|
||||||
|
|
||||||
|
if len(got.Items) != 0 || got.Total != 12 || got.Page != 99 || got.Size != 5 || got.Counts["all"] != 12 {
|
||||||
|
t.Errorf("unexpected envelope %+v", got)
|
||||||
|
}
|
||||||
|
if !strings.Contains(raw, `"items":[]`) {
|
||||||
|
t.Errorf("expected an empty array in %s", raw)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("An empty library", func(t *testing.T) {
|
||||||
|
env := newMediaEnv(t)
|
||||||
|
|
||||||
|
got, raw := env.list(t, "")
|
||||||
|
|
||||||
|
if len(got.Items) != 0 || got.Total != 0 || !reflect.DeepEqual(got.Counts, map[string]int{"all": 0, "unused": 0, "duplicates": 0}) {
|
||||||
|
t.Errorf("unexpected envelope %+v", got)
|
||||||
|
}
|
||||||
|
if !strings.Contains(raw, `"items":[]`) {
|
||||||
|
t.Errorf("expected an empty array in %s", raw)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("counts ignores every filter and the page", func(t *testing.T) {
|
||||||
|
env := newMediaEnv(t)
|
||||||
|
seedBulkImages(env, 30)
|
||||||
|
|
||||||
|
got, _ := env.list(t, "?q=zzzz&page=3&size=5")
|
||||||
|
|
||||||
|
if len(got.Items) != 0 || got.Total != 0 || got.Counts["all"] != 30 {
|
||||||
|
t.Errorf("unexpected envelope %+v", got)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("cursor and limit are ignored", func(t *testing.T) {
|
||||||
|
for _, query := range []string{"cursor=abc", "limit=5", "limit=0", "limit=abc", "cursor=b2Zmc2V0OjU"} {
|
||||||
|
t.Run(query, func(t *testing.T) {
|
||||||
|
env := newMediaEnv(t)
|
||||||
|
seedBulkImages(env, 30)
|
||||||
|
|
||||||
|
got, _ := env.list(t, "?"+query)
|
||||||
|
bare, _ := env.list(t, "")
|
||||||
|
|
||||||
|
if got.Page != 1 || got.Size != 25 || len(got.Items) != 25 {
|
||||||
|
t.Errorf("unexpected envelope %d %d %d", got.Page, got.Size, len(got.Items))
|
||||||
|
}
|
||||||
|
expectIds(t, idsOf(got.Items), idsOf(bare.Items))
|
||||||
|
})
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("Invalid parameters answer 400", func(t *testing.T) {
|
||||||
|
queries := []string{"page=0", "page=-1", "page=abc", "page=", "page=1.5", "size=0", "size=10", "size=200", "size=abc", "size=", "page=0&size=5", "page=1&size=1000", "filter=archived", "sort=biggest", "variants=", "variants=other", "hash=notahash"}
|
||||||
|
for _, query := range queries {
|
||||||
|
t.Run(query, func(t *testing.T) {
|
||||||
|
env := newMediaEnv(t)
|
||||||
|
seedBulkImages(env, 3)
|
||||||
|
|
||||||
|
rec := env.send(t, http.MethodGet, "/v1/media/?"+url.PathEscape(query), "", mediaVerifiedUserId)
|
||||||
|
|
||||||
|
if rec.Code != http.StatusBadRequest || rec.Body.String() != apperr.MediaQueryErrorMessage+"\n" {
|
||||||
|
t.Errorf("unexpected response %d %q", rec.Code, rec.Body.String())
|
||||||
|
}
|
||||||
|
if env.images.listCalls != 0 {
|
||||||
|
t.Errorf("expected the repository not to be called")
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("Repository failure answers 500", func(t *testing.T) {
|
||||||
|
env := newMediaEnv(t)
|
||||||
|
env.images.fail.failNext("List")
|
||||||
|
|
||||||
|
rec := env.send(t, http.MethodGet, "/v1/media/", "", mediaVerifiedUserId)
|
||||||
|
|
||||||
|
if rec.Code != http.StatusInternalServerError || rec.Body.String() != "Internal server error\n" {
|
||||||
|
t.Errorf("unexpected response %d %q", rec.Code, rec.Body.String())
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("An unauthenticated caller is refused as before", func(t *testing.T) {
|
||||||
|
env := newMediaEnv(t)
|
||||||
|
|
||||||
|
rec := env.send(t, http.MethodGet, "/v1/media/?page=1&size=5", "", 0)
|
||||||
|
|
||||||
|
if rec.Code != http.StatusUnauthorized || env.images.listCalls != 0 {
|
||||||
|
t.Errorf("unexpected response %d with %d calls", rec.Code, env.images.listCalls)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestListMediaUseCasePaging(t *testing.T) {
|
||||||
|
build := func() (*mockImageRepo, *mockVariantFileRepo, *useCases.ListMediaUseCase) {
|
||||||
|
images := newMockImageRepo()
|
||||||
|
variants := newMockVariantFileRepo()
|
||||||
|
return images, variants, useCases.NewListMediaUseCase(images, newMockArticleRepo(), newMockUserRepo(), variants)
|
||||||
|
}
|
||||||
|
seed := func(images *mockImageRepo, count int) {
|
||||||
|
for id := uint32(1); id <= uint32(count); id++ {
|
||||||
|
images.images[id] = domainImage.Image{ID: id, Path: fmt.Sprintf("/static/uploadedImages/img-%d.jpg", id), Filename: "a.jpg", Size: int64(id), CreatedAt: mockImageEpoch.Add(time.Duration(id) * time.Minute)}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
t.Run("List returns the items, total, page, size and counts", func(t *testing.T) {
|
||||||
|
images, _, useCase := build()
|
||||||
|
seed(images, 12)
|
||||||
|
query := domainImage.NewListQuery()
|
||||||
|
query.Page, query.Size = 3, 5
|
||||||
|
|
||||||
|
page, err := useCase.List(query)
|
||||||
|
|
||||||
|
if err != nil || len(page.Items) != 2 || page.Total != 12 || page.Page != 3 || page.Size != 5 || page.Counts.All != 12 {
|
||||||
|
t.Errorf("unexpected page %+v err %v", page, err)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("The variants filter and total_size sort apply before slicing", func(t *testing.T) {
|
||||||
|
images, variants, useCase := build()
|
||||||
|
seed(images, 12)
|
||||||
|
for _, id := range []uint32{3, 7, 9} {
|
||||||
|
_, _ = variants.Save(domainImage.VariantFile{VariantName: "hero", SourceName: domainImage.StoredName(images.images[id].Path), CachedName: fmt.Sprintf("c%d", id), ContentType: "image/jpeg", Size: int64(id) * 1000, Fingerprint: "f"})
|
||||||
|
}
|
||||||
|
with := domainImage.NewListQuery()
|
||||||
|
with.Variants, with.Sort, with.Size = domainImage.VariantsWith, domainImage.SortTotalSize, 5
|
||||||
|
|
||||||
|
page, err := useCase.List(with)
|
||||||
|
|
||||||
|
if err != nil || page.Total != 3 || len(page.Items) != 3 || page.Items[0].Image.ID != 9 || page.Counts.All != 12 {
|
||||||
|
t.Errorf("unexpected page %+v err %v", page, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
all := domainImage.NewListQuery()
|
||||||
|
all.Sort, all.Size = domainImage.SortTotalSize, 5
|
||||||
|
first, _ := useCase.List(all)
|
||||||
|
if first.Items[0].Image.ID != 9 || first.Items[1].Image.ID != 7 || first.Items[2].Image.ID != 3 {
|
||||||
|
t.Errorf("unexpected total_size order %v", first.Items)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("A repository error is propagated", func(t *testing.T) {
|
||||||
|
images, _, useCase := build()
|
||||||
|
images.fail.failNextWith("List", errRepositoryFailure)
|
||||||
|
|
||||||
|
_, err := useCase.List(domainImage.NewListQuery())
|
||||||
|
|
||||||
|
if !errors.Is(err, errRepositoryFailure) {
|
||||||
|
t.Errorf("err = %v", err)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("ListQuery.Validate rejects a bad page or size", func(t *testing.T) {
|
||||||
|
for _, mutate := range []func(*domainImage.ListQuery){
|
||||||
|
func(q *domainImage.ListQuery) { q.Page = 0 },
|
||||||
|
func(q *domainImage.ListQuery) { q.Size = 0 },
|
||||||
|
func(q *domainImage.ListQuery) { q.Size = 10 },
|
||||||
|
func(q *domainImage.ListQuery) { q.Size = 101 },
|
||||||
|
} {
|
||||||
|
query := domainImage.NewListQuery()
|
||||||
|
mutate(&query)
|
||||||
|
if err := query.Validate(); !errors.Is(err, domainImage.ErrInvalidQuery) {
|
||||||
|
t.Errorf("err = %v for %+v", err, query)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, size := range []int{5, 25, 50, 100} {
|
||||||
|
query := domainImage.NewListQuery()
|
||||||
|
query.Size = size
|
||||||
|
if err := query.Validate(); err != nil {
|
||||||
|
t.Errorf("size %d: err = %v", size, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
@@ -5,7 +5,6 @@ import (
|
|||||||
"RenewCMS/internal/domain/article"
|
"RenewCMS/internal/domain/article"
|
||||||
domain "RenewCMS/internal/domain/image"
|
domain "RenewCMS/internal/domain/image"
|
||||||
"net/http"
|
"net/http"
|
||||||
"net/url"
|
|
||||||
"slices"
|
"slices"
|
||||||
"strings"
|
"strings"
|
||||||
"testing"
|
"testing"
|
||||||
@@ -184,16 +183,15 @@ func TestMediaListVariantsFilterAndSort(t *testing.T) {
|
|||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
t.Run("variants=with and sort=total_size page through the list", func(t *testing.T) {
|
t.Run("variants=with and sort=total_size answer the ordered page with its total", func(t *testing.T) {
|
||||||
env := newVariantEnv(t)
|
env := newVariantEnv(t)
|
||||||
env.seedLibrary()
|
env.seedLibrary()
|
||||||
|
|
||||||
first, firstBody := env.listIds("?variants=with&sort=total_size&limit=2")
|
ids, body := env.listIds("?variants=with&sort=total_size&size=5&page=1")
|
||||||
cursor, _ := firstBody["next_cursor"].(string)
|
beyond, _ := env.listIds("?variants=with&sort=total_size&size=5&page=2")
|
||||||
second, secondBody := env.listIds("?variants=with&sort=total_size&limit=2&cursor=" + url.QueryEscape(cursor))
|
|
||||||
|
|
||||||
if !slices.Equal(first, []float64{1, 4}) || cursor == "" || !slices.Equal(second, []float64{2}) || secondBody["next_cursor"] != nil {
|
if !slices.Equal(ids, []float64{1, 4, 2}) || body["total"] != float64(3) || len(beyond) != 0 {
|
||||||
t.Errorf("first = %v (%q), second = %v (%v)", first, cursor, second, secondBody["next_cursor"])
|
t.Errorf("ids = %v, total = %v, beyond = %v", ids, body["total"], beyond)
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
|
|||||||
@@ -90,7 +90,7 @@ func TestPublicArticleListingHttp(t *testing.T) {
|
|||||||
t.Fatalf("expected status 200, got %d", rec.Code)
|
t.Fatalf("expected status 200, got %d", rec.Code)
|
||||||
}
|
}
|
||||||
var got []domainArticle.Article
|
var got []domainArticle.Article
|
||||||
if err := json.Unmarshal(rec.Body.Bytes(), &got); err != nil {
|
if err := json.Unmarshal(articleItemsJSON(rec.Body.Bytes()), &got); err != nil {
|
||||||
t.Fatalf("failed to decode response: %v", err)
|
t.Fatalf("failed to decode response: %v", err)
|
||||||
}
|
}
|
||||||
if len(got) != 1 {
|
if len(got) != 1 {
|
||||||
@@ -112,7 +112,7 @@ func TestPublicArticleListingHttp(t *testing.T) {
|
|||||||
t.Fatalf("expected status 200, got %d", rec.Code)
|
t.Fatalf("expected status 200, got %d", rec.Code)
|
||||||
}
|
}
|
||||||
var got []domainArticle.Article
|
var got []domainArticle.Article
|
||||||
if err := json.Unmarshal(rec.Body.Bytes(), &got); err != nil {
|
if err := json.Unmarshal(articleItemsJSON(rec.Body.Bytes()), &got); err != nil {
|
||||||
t.Fatalf("failed to decode response: %v", err)
|
t.Fatalf("failed to decode response: %v", err)
|
||||||
}
|
}
|
||||||
if len(got) != 2 {
|
if len(got) != 2 {
|
||||||
@@ -138,7 +138,7 @@ func TestPublicArticleListingHttp(t *testing.T) {
|
|||||||
t.Fatalf("expected status 200, got %d", rec.Code)
|
t.Fatalf("expected status 200, got %d", rec.Code)
|
||||||
}
|
}
|
||||||
var got []domainArticle.Article
|
var got []domainArticle.Article
|
||||||
if err := json.Unmarshal(rec.Body.Bytes(), &got); err != nil {
|
if err := json.Unmarshal(articleItemsJSON(rec.Body.Bytes()), &got); err != nil {
|
||||||
t.Fatalf("failed to decode response: %v", err)
|
t.Fatalf("failed to decode response: %v", err)
|
||||||
}
|
}
|
||||||
if len(got) != 1 {
|
if len(got) != 1 {
|
||||||
@@ -194,7 +194,7 @@ func TestPublicArticleListingHttp(t *testing.T) {
|
|||||||
|
|
||||||
t.Run("A repository failure still answers 500 regardless of auth state", func(t *testing.T) {
|
t.Run("A repository failure still answers 500 regardless of auth state", func(t *testing.T) {
|
||||||
repo := seedPublicArticleListingRepo()
|
repo := seedPublicArticleListingRepo()
|
||||||
repo.fail.failNext("FindByFilters")
|
repo.fail.failNext("FindPage")
|
||||||
router := newPublicArticleListingRouter(repo, token)
|
router := newPublicArticleListingRouter(repo, token)
|
||||||
req := httptest.NewRequest(http.MethodGet, "/v1/article/", nil)
|
req := httptest.NewRequest(http.MethodGet, "/v1/article/", nil)
|
||||||
rec := httptest.NewRecorder()
|
rec := httptest.NewRecorder()
|
||||||
|
|||||||
@@ -196,35 +196,36 @@ func TestListArticlesFiltersByIsOnline(t *testing.T) {
|
|||||||
return repo
|
return repo
|
||||||
}
|
}
|
||||||
|
|
||||||
t.Run("ListOnlineArticles", func(t *testing.T) {
|
t.Run("ListArticlesPage unverified", func(t *testing.T) {
|
||||||
repo := newRepo()
|
repo := newRepo()
|
||||||
uc := useCases.NewListArticlesUseCase(repo, &fakeBodyRenderer{})
|
uc := useCases.NewListArticlesUseCase(repo, &fakeBodyRenderer{})
|
||||||
result, err := uc.ListOnlineArticles(article.BodyFormatHTML)
|
result, err := uc.ListArticlesPage(useCases.ListArticlesCommand{Format: article.BodyFormatHTML, Page: 1, Size: 25, Sort: article.Sort{Field: article.SortByTitle, Direction: article.SortAsc}})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("expected no error, got %v", err)
|
t.Fatalf("expected no error, got %v", err)
|
||||||
}
|
}
|
||||||
assertArticleIds(t, result, []uint32{1, 3})
|
assertArticleIds(t, result.Items, []uint32{1, 3})
|
||||||
})
|
})
|
||||||
|
|
||||||
t.Run("ListAllArticles", func(t *testing.T) {
|
t.Run("ListArticlesPage verified", func(t *testing.T) {
|
||||||
repo := newRepo()
|
repo := newRepo()
|
||||||
uc := useCases.NewListArticlesUseCase(repo, &fakeBodyRenderer{})
|
uc := useCases.NewListArticlesUseCase(repo, &fakeBodyRenderer{})
|
||||||
result, err := uc.ListAllArticles(article.BodyFormatHTML)
|
result, err := uc.ListArticlesPage(useCases.ListArticlesCommand{Format: article.BodyFormatHTML, Verified: true, Page: 1, Size: 25, Sort: article.Sort{Field: article.SortByTitle, Direction: article.SortAsc}})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("expected no error, got %v", err)
|
t.Fatalf("expected no error, got %v", err)
|
||||||
}
|
}
|
||||||
assertArticleIds(t, result, []uint32{1, 2, 3})
|
assertArticleIds(t, result.Items, []uint32{1, 2, 3})
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestListOnlineArticlesEmptyRepositoryReturnsEmptySlice(t *testing.T) {
|
func TestListArticlesPageEmptyRepositoryReturnsEmptySlice(t *testing.T) {
|
||||||
repo := newMockArticleRepo()
|
repo := newMockArticleRepo()
|
||||||
uc := useCases.NewListArticlesUseCase(repo, &fakeBodyRenderer{})
|
uc := useCases.NewListArticlesUseCase(repo, &fakeBodyRenderer{})
|
||||||
|
|
||||||
result, err := uc.ListOnlineArticles(article.BodyFormatHTML)
|
page, err := uc.ListArticlesPage(useCases.ListArticlesCommand{Format: article.BodyFormatHTML, Verified: true, Page: 1, Size: 25})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("expected no error, got %v", err)
|
t.Fatalf("expected no error, got %v", err)
|
||||||
}
|
}
|
||||||
|
result := page.Items
|
||||||
if result == nil {
|
if result == nil {
|
||||||
t.Errorf("expected an empty slice, got nil")
|
t.Errorf("expected an empty slice, got nil")
|
||||||
}
|
}
|
||||||
|
|||||||
Loaded 100 of 246 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user