Compare commits

..
9 Commits
154 changed files with 13009 additions and 1246 deletions

No files matched your search

+5 -5
View File
@@ -23,7 +23,7 @@ docker compose pull
docker compose up -d # http://localhost:8080
```
Upgrade with `docker compose pull && docker compose up -d`. The image `git.floriansylvain.fr/fsylvain/renewcms` is published by the maintainer with `task docker:publish` (no CI). Tags: `vX.Y.Z`, `X.Y.Z`, `X.Y` and `latest` for a stable release; `vX.Y.Z-<pre>`, `X.Y.Z-<pre>` and the moving `beta` or `rc` for a pre-release (`latest` never moves for those, so the default is `beta` for now). To build from source use the override described in **[docs/docker.md](docs/docker.md)**.
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
@@ -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/configuration.md](docs/configuration.md) | Every environment variable |
| [docs/architecture.md](docs/architecture.md) | Backend layering and how the SPA is embedded |
## API Usage
TODO
| [docs/api.md](docs/api.md) | API reference: authentication, API keys, routes and the activity log |
| [docs/api/articles.md](docs/api/articles.md) | Reading articles: pagination, search, `format` and body schemas |
| [docs/image-variants.md](docs/image-variants.md) | Image variants and their cache |
| [docs/release-notes.md](docs/release-notes.md) | Release notes format, the published releases and how to publish one |
## TODOs
+1 -1
View File
@@ -32,7 +32,7 @@ type filterQuery struct {
Category string `validate:"omitempty,oneof=articles media users api_keys auth system"`
Outcome string `validate:"omitempty,oneof=all success failed"`
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"`
To string `validate:"max=10"`
}
+74 -9
View File
@@ -11,7 +11,9 @@ import (
"fmt"
"log"
"net/http"
"net/url"
"strconv"
"strings"
"time"
"github.com/go-chi/chi/v5"
@@ -268,26 +270,89 @@ func (h *Handler) callerIsVerified(r *http.Request) bool {
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) {
format, ok := parseBodyFormat(w, r)
if !ok {
return
}
var articles []domain.Article
var err error
if h.callerIsVerified(r) {
articles, err = h.ListUseCase.ListAllArticles(format)
} else {
articles, err = h.ListUseCase.ListOnlineArticles(format)
query, err := readListQuery(r.URL.Query())
if err != nil || validator.Validate.Struct(query) != nil {
http.Error(w, apperr.BodyErrorMessage, http.StatusBadRequest)
return
}
page, err := h.ListUseCase.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 {
http.Error(w, "Failed to retrieve articles", http.StatusInternalServerError)
return
}
responses := make([]articleResponse, 0, len(articles))
for _, article := range articles {
responses := make([]articleResponse, 0, len(page.Items))
for _, article := range page.Items {
response, err := toArticleResponse(article, format)
if err != nil {
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)
}
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 {
http.Error(w, "Failed to encode response", http.StatusInternalServerError)
return
+3 -2
View File
@@ -2,7 +2,8 @@
The full, searchable reference is the Integration page of the running app (`/integration`). It
renders `web/src/data/apiCatalogue.ts`, which is the single source for this page. This file is for
readers without the UI.
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
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`,
`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
are UTC. The list answers `{ items, total, page, size }`, newest first (`created_at`, then `id`).
+31
View File
@@ -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`.
## 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
| Value | `body` | `body_format` |
+4 -4
View File
@@ -21,7 +21,7 @@ Requirements: Docker with Compose v2. [task](https://taskfile.dev) is optional f
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.0-beta`.
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 |
|---|---|
| `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.0-beta`, `v3.2.0-rc.1`) | `vX.Y.Z-<pre>`, `X.Y.Z-<pre>`, and the moving tag `<pre-name>` (`beta`, `rc`) |
A pre-release never moves `latest`. Images are published for `linux/amd64` and `linux/arm64`. `renewcms --version` in the image prints the exact release tag. Images are not signed; the Ed25519 key signs the release binaries only.
@@ -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:
```sh
git tag v2.9.0-beta
git tag v3.2.0-beta
```
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
task docker:publish -- --dry-run
task docker:publish VERSION=v2.9.0-rc.1 -- --dry-run
task docker:publish VERSION=v3.2.0-rc.1 -- --dry-run
```
The dry run builds for the host platform only, loads the image into the local Docker, pushes nothing and needs no login. It prints the tags a real run would push. A `VERSION` override is accepted only with `--dry-run`, and a dirty tree is allowed there. Remove the loaded images afterwards with `docker rmi`.
+19 -16
View File
@@ -17,21 +17,24 @@ Rules: bullets are full sentences ending with a period; user-facing wording, no
## 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 |
| `v2.1.0-beta` | v2.1.0-beta - Image upload in the editor |
| `v2.2.0-beta` | v2.2.0-beta - Image crop, image removal & reset screens |
| `v2.3.0-beta` | v2.3.0-beta - Multi-user invitations, display names & profile page |
| `v2.4.0-beta` | v2.4.0-beta - Owner role, invite management & Settings page |
| `v2.5.0-beta` | v2.5.0-beta - Media library & image picker |
| `v2.6.0-beta` | v2.6.0-beta - Signed updates and browser restart |
| `v2.6.2-beta` | v2.6.2-beta - English and French interface |
| `v2.7.0-beta` | v2.7.0-beta - Markdown and block article bodies |
| `v2.8.0-beta` | v2.8.0-beta - API keys and API reference |
| `v2.8.1-beta` | v2.8.1-beta - Docker deployment |
| `v2.8.2-beta` | 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 |
| `v3.1.0-beta` | v3.1.0-beta - Image variants |
| `2.0.0-beta` (legacy tag without the `v`, kept as is) | Vue 3 SPA and domain-driven backend |
| `v2.1.0-beta` | Image upload in the editor |
| `v2.2.0-beta` | Image crop, image removal & reset screens |
| `v2.3.0-beta` | Multi-user invitations, display names & profile page |
| `v2.4.0-beta` | Owner role, invite management & Settings page |
| `v2.5.0-beta` | Media library & image picker |
| `v2.6.0-beta` | Signed updates and browser restart |
| `v2.6.2-beta` | English and French interface |
| `v2.7.0-beta` | Markdown and block article bodies |
| `v2.8.0-beta` | API keys and API reference |
| `v2.8.1-beta` | Docker deployment |
| `v2.8.2-beta` | Security headers and clearer log in errors |
| `v2.8.3-beta` | Security policy fixes for the web app |
| `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 |
+46
View File
@@ -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.
+7
View File
@@ -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=7d | events of the last 7 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 |
| page=2&size=50 | the second page of 50 |
| 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
Given events 2 days old and 10 days old
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.
+10 -33
View File
@@ -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
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
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 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
@@ -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"
button, and "You can't view this activity" (no trailing period) uses icon lock and the
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 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
@@ -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"
When the user navigates to /activity
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
keys"; "6" "0.5% of all actions"; "11" "11 flagged"
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
Given GET /v1/activity and GET /v1/activity/summary have not resolved
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 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"
@@ -377,7 +377,7 @@ Feature: Activity screen, details slide-over and My activity
"0" "Nothing to flag"
And an empty panel with icon history shows "No activity yet" and "Actions on articles,
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
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"
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"
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"
Then every filter is reset, GET /v1/activity is sent with range=7d, page=1, size=25 only and
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
And an error alert shows "Couldn't load activity" and "Check your connection and 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"
Then the Loading state shows for the list and GET /v1/activity is sent again with the same
query
@@ -426,7 +426,7 @@ Feature: Activity screen, details slide-over and My activity
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
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 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
@@ -529,29 +529,6 @@ Feature: Activity screen, details slide-over and My activity
When the user activates "Show 6 results"
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
Given the Default state has loaded
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
Then the title reads "My activity", the subtitle "Everything you've done on this site." and
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 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
@@ -683,7 +660,7 @@ Feature: Activity screen, details slide-over and My activity
Scenario: The French interface composes sentences and chrome in French
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
"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"
And the Security sub-line reads "11 signalés"
And every new English string of this screen has a French entry in messages.ts
+9 -15
View File
@@ -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,
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".
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
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
@@ -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",
"vs previous 30 days" and "vs previous period".
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.
11. **Empty, filters match nothing** — type "sitemap", choose Category "Media" and Outcome
"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
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.
23. **Export success** — click "Export CSV" with filters applied; assert one request to
`/v1/activity/export` with the list filters and no `page` or `size`, "Preparing file…" and
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.
23. **Export** — superseded by activity_filter_cards_and_export.qa.md (menu, dialog, toasts).
24. **Export failure** — superseded by activity_filter_cards_and_export.qa.md.
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
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
state copy; details "Event 1 of 41" with previous disabled.
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
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
@@ -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
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.
- [ ] 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
`items: [], total: 0`, summary Default.
- [ ] 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
(`role: 'user'`), so no "Export CSV".
(`role: 'user'`), so no "Export".
- [ ] My activity, Empty: `activityEditorSession`, list `items: [], total: 0`.
- [ ] 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.
@@ -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
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
(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
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.
@@ -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
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.
- **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,
neutralised cells that start with `=`, `+`, `-` or `@`; confirm the browser download prompt and
the two toasts.
+2 -3
View File
@@ -155,7 +155,7 @@ Feature: API keys screen
"\"Nightly media import\" is ready. Copy the key and store it somewhere safe."
And a warning alert (UAlert, color warning, triangle-alert icon) reads "You won't be able to
see this key again."
And the full key from the response is shown in a monospace box with a "Copy" button (icon copy)
And the 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 only button is a primary "Done"
@@ -181,8 +181,7 @@ Feature: API keys screen
Given the key reveal is open
When the user activates "Copy"
Then the full key is written to the clipboard
And the button shows icon check and text "Copied" in the success color, announced to assistive
technology
And the button shows icon check and text "Copied" in the success color, announced politely
When 2 seconds elapse
Then the button reverts to icon copy and text "Copy"
+3 -3
View File
@@ -68,8 +68,8 @@ layout cases at desktop and below-md (mock `matchMedia`).
errors clear when fixed.
9. **Create key: name too long** - 75 characters; counter, error class and text, no request.
10. **Create key: success** - one POST with `{"name":"Nightly media import"}` and no expires_at
key; the reveal: title, text, warning alert, key equal to the mocked `key`, "Copy", note, only
"Done".
key; the reveal: title, text, warning alert, key equal to the mocked `key` inside a CodeSnippet with
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
with the local offset. Examples today (sent), yesterday (blocked), tomorrow (sent); build the
dates from `new Date()` in the test.
@@ -137,7 +137,7 @@ States:
- [ ] Create key
- [ ] Create key: validation
- [ ] 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)
- [ ] Revoke: confirm
- [ ] Revoked (list with the revoked row and the toast)
+191
View File
@@ -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"
+44
View File
@@ -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.
+187
View File
@@ -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
+42
View File
@@ -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.
+109
View File
@@ -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
+23
View File
@@ -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.
+226
View File
@@ -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 | java&#115;cript: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) |
+60
View File
@@ -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.
+2 -3
View 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 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
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 footer is 72 px high with "Cancel" and "Add variant" sharing the width
Scenario: Edit opens with the stored values
When the user chooses "Edit" on the row "hero"
+2 -2
View File
@@ -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.
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.
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
via Cancel/x/back/Escape opens "Discard changes?" with the right text, Keep editing / Discard
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
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
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
status toasts, the 422 mapping, the clipboard states "Copied" (add only if the board draws it: it
does not, so Vitest only), singular footer.
+14 -12
View File
@@ -7,7 +7,7 @@ Feature: Integration screen (API reference)
Background:
Given /integration is a verified route (meta.auth "verified") rendered as IntegrationPage
inside DashboardShell, per docs/design/routes.md
And the screen makes no /v1 calls; api: none (static)
And the 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
"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
@@ -37,7 +37,7 @@ Feature: Integration screen (API reference)
Scenario: Default, every card collapsed
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."
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 the sticky section index lists the sections on desktop and a "Jump to" select lists them on mobile
@@ -70,7 +70,7 @@ Feature: Integration screen (API reference)
| Name | Type | Required | Rule |
| title | string | Yes | 3 to 200 characters. Can't be changed later. |
| 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
Scenario: Query parameters table, new UI beyond the board, user-approved
@@ -114,7 +114,7 @@ Feature: Integration screen (API reference)
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}
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 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."
@@ -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. |
| 429 | Too many requests. Please try again later. |
| 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
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}"
When the user activates the Base URL "Copy" button
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
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
When the user activates that CodeBlock's "Copy JavaScript example" button
Then that card'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
When the user activates that CodeSnippet's "Copy code" button
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 CodeSnippets are unaffected
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
@@ -189,5 +189,7 @@ Feature: Integration screen (API reference)
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
Scenario: The page stays static
Then no /v1 request is made while the page renders or while any card is expanded
Scenario: Only the image variants calls
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
+7 -6
View File
@@ -4,7 +4,7 @@
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
`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.
Catalogue spec (pure data, no mount, imports web/src/data/apiCatalogue.ts):
@@ -44,12 +44,12 @@ Component specs, one per design state:
invite rows show "Owner only".
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
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";
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.
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.
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
@@ -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
Authorization header only on non-public routes. Not visually checked.
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)
@@ -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)
- [ ] Group scrolled, one card expanded (exception: Query parameters table)
- [ ] Copied: base URL (must pass 10 %)
- [ ] Copied: CodeBlock (must pass 10 %)
- [ ] Copied: CodeSnippet (must pass 10 %)
- [ ] Authentication (must pass 10 %; Note 1 text changed)
- [ ] Session only (exception: banner, 13th row, captions, Public auth flow block)
- [ ] Errors (exception: 409 row)
@@ -88,7 +89,7 @@ None of these states is clock-sensitive, so none is skipped.
## Manual
- 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.
- Find-in-page and a deep link to an `#ep-...` anchor.
- Real origin in a production build and under `task dev`.
+305
View File
@@ -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"
+114
View File
@@ -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".
+3 -3
View File
@@ -8,8 +8,8 @@ Feature: Public and authenticated article listing
Background:
Given internal/domain/article.Article has a json "is_online" field
And ListArticlesUseCase.ListOnlineArticles filters article.Filters{IsOnline: true} and
ListArticlesUseCase.ListAllArticles applies no filter, both already implemented
And ListArticlesUseCase.ListArticlesPage filters article.Filters{IsOnline: true} for an unverified
caller and applies no visibility filter for a verified one
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},
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
same Verifier-only group as GET /v1/article/, so the 401 Examples table below is updated
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
jwtauth.Verifier (header and cookie sources) placed in the request context, rather than
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.
+3 -3
View File
@@ -66,12 +66,12 @@ Feature: Use case baseline characterization
Examples:
| method | ids |
| ListOnlineArticles | 1,3 |
| ListAllArticles | 1,2,3 |
| ListArticlesPage unverified | 1,3 |
| ListArticlesPage verified | 1,2,3 |
Scenario: Listing articles on an empty repository returns an empty slice, not an error
Given an empty article repository fake
When ListOnlineArticles is called
When ListArticlesPage is called
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
@@ -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.
+1 -1
View File
@@ -23,6 +23,7 @@ require (
golang.org/x/image v0.46.0
golang.org/x/net v0.59.0
golang.org/x/sync v0.23.0
golang.org/x/text v0.42.0
gopkg.in/gomail.v2 v2.0.0-20160411212932-81ebce5c23df
gorm.io/driver/mysql v1.6.0
gorm.io/driver/postgres v1.6.3
@@ -73,7 +74,6 @@ require (
github.com/segmentio/asm v1.2.1 // indirect
golang.org/x/exp v0.0.0-20251113190631-e25ba8c21ef6 // 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
modernc.org/libc v1.67.0 // indirect
modernc.org/mathutil v1.7.1 // indirect
@@ -1,11 +1,57 @@
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 {
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 {
FindByFilters(filters Filters) ([]Article, error)
FindPage(filters Filters) (PageResult, error)
CountByVisibility(onlineOnly bool) (Counts, error)
Get(id uint32) (Article, error)
GetByName(name string) (Article, error)
GetAll() []Article
@@ -5,6 +5,12 @@ import (
"RenewCMS/internal/infrastructure/persistence/mappers"
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"
)
@@ -26,12 +32,128 @@ func (a *ArticleRepository) FindByFilters(filters domain.Filters) ([]domain.Arti
var entityArticles []entity.Article
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))
for _, entityArticle := range entityArticles {
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) {
@@ -131,11 +253,7 @@ func (a *ArticleRepository) FindByBodyContaining(filename string) ([]domain.Arti
return nil, err
}
domainArticles := make([]domain.Article, 0, len(entityArticles))
for _, entityArticle := range entityArticles {
domainArticles = append(domainArticles, mappers.ArticleToDomain(entityArticle))
}
return domainArticles, nil
return toDomainArticles(entityArticles), nil
}
var _ domain.Repository = &ArticleRepository{}
@@ -11,21 +11,51 @@ func NewListArticlesUseCase(articleRepository article.Repository, bodyRenderer a
return &ListArticlesUseCase{articleRepository, bodyRenderer}
}
func (u *ListArticlesUseCase) ListOnlineArticles(format article.BodyFormat) ([]article.Article, error) {
online := true
articles, err := u.articleRepository.FindByFilters(article.Filters{
IsOnline: &online,
})
if err != nil {
return nil, err
}
return renderArticles(u.bodyRenderer, articles, format)
type ListArticlesCommand struct {
Format article.BodyFormat
Verified bool
Page int
Size int
Q string
Status string
Sort article.Sort
}
func (u *ListArticlesUseCase) ListAllArticles(format article.BodyFormat) ([]article.Article, error) {
articles, err := u.articleRepository.FindByFilters(article.Filters{})
type ArticlePage struct {
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 {
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
}
@@ -9,6 +9,7 @@ const (
activityRangeToday = "today"
activityRange7Days = "7d"
activityRange30Days = "30d"
activityRangeAll = "all"
activityRangeCustom = "custom"
activityDateLayout = "2006-01-02"
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
case activityRangeToday:
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:
return resolveCustomWindow(query)
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)
})
}
+8 -2
View File
@@ -514,7 +514,13 @@ func TestAPIKeysHttp(t *testing.T) {
raw, _ := env.issueKey(apiKeyDevId, "ci")
ids := func(rec *httptest.ResponseRecorder) []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))
}
return result
@@ -522,7 +528,7 @@ func TestAPIKeysHttp(t *testing.T) {
withKey := env.withKey(t, http.MethodGet, "/v1/article", "", raw)
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)
}
anonymous := env.anonymous(t, http.MethodGet, "/v1/article", "")
+2 -2
View File
@@ -188,7 +188,7 @@ func TestArticleBodyFormatHttp(t *testing.T) {
for _, expectation := range expectations {
rec := serveBodyFormat(router, http.MethodGet, "/v1/article/"+expectation.query, "", nil)
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)
}
if len(items) != 2 {
@@ -318,7 +318,7 @@ func TestArticleBodyFormatHttp(t *testing.T) {
router, _ := realRouter()
rec := serveBodyFormat(router, http.MethodGet, "/v1/article/?format=json", "", verifiedCookie)
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)
}
seen := map[uint32]bool{}
+2 -2
View File
@@ -234,7 +234,7 @@ func TestArticlePublishingHttp(t *testing.T) {
t.Fatalf("expected status 200, got %d", listRec.Code)
}
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)
}
found := false
@@ -304,7 +304,7 @@ func TestArticlePublishingHttp(t *testing.T) {
t.Fatalf("expected status 200, got %d", listRec.Code)
}
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)
}
foundStillOnline := false
+84
View File
@@ -7,6 +7,11 @@ import (
"sort"
"strings"
"testing"
"unicode"
"golang.org/x/text/runes"
"golang.org/x/text/transform"
"golang.org/x/text/unicode/norm"
)
type mockArticleRepo struct {
@@ -47,6 +52,85 @@ func (m *mockArticleRepo) FindByFilters(filters article.Filters) ([]article.Arti
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) {
if err := m.fail.trigger("Get"); err != nil {
return article.Article{}, err
+1 -1
View File
@@ -57,7 +57,7 @@ func TestArticlesListHttp(t *testing.T) {
}
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)
}
if len(got) != 1 {
+613
View File
@@ -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)
}
})
}
+4 -4
View File
@@ -90,7 +90,7 @@ func TestPublicArticleListingHttp(t *testing.T) {
t.Fatalf("expected status 200, got %d", rec.Code)
}
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)
}
if len(got) != 1 {
@@ -112,7 +112,7 @@ func TestPublicArticleListingHttp(t *testing.T) {
t.Fatalf("expected status 200, got %d", rec.Code)
}
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)
}
if len(got) != 2 {
@@ -138,7 +138,7 @@ func TestPublicArticleListingHttp(t *testing.T) {
t.Fatalf("expected status 200, got %d", rec.Code)
}
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)
}
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) {
repo := seedPublicArticleListingRepo()
repo.fail.failNext("FindByFilters")
repo.fail.failNext("FindPage")
router := newPublicArticleListingRouter(repo, token)
req := httptest.NewRequest(http.MethodGet, "/v1/article/", nil)
rec := httptest.NewRecorder()
+9 -8
View File
@@ -196,35 +196,36 @@ func TestListArticlesFiltersByIsOnline(t *testing.T) {
return repo
}
t.Run("ListOnlineArticles", func(t *testing.T) {
t.Run("ListArticlesPage unverified", func(t *testing.T) {
repo := newRepo()
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 {
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()
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 {
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()
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 {
t.Fatalf("expected no error, got %v", err)
}
result := page.Items
if result == nil {
t.Errorf("expected an empty slice, got nil")
}
+3 -3
View File
@@ -131,7 +131,7 @@ func TestVerifiedAccountRequiredHttp(t *testing.T) {
t.Fatalf("expected status 201, got %d, body %q", rec.Code, rec.Body.String())
}
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)
}
if got.Title != "Valid Title" || got.Body != "Some content" {
@@ -248,7 +248,7 @@ func TestVerifiedAccountRequiredHttp(t *testing.T) {
t.Fatalf("expected status 200, got %d, body %q", rec.Code, rec.Body.String())
}
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)
}
if len(got) != 1 || got[0].ID != 1 {
@@ -283,7 +283,7 @@ func TestVerifiedAccountRequiredHttp(t *testing.T) {
t.Fatalf("expected status 200, got %d, body %q", rec.Code, rec.Body.String())
}
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)
}
ids := map[uint32]bool{}
-91
View File
@@ -16,7 +16,6 @@
"@tiptap/vue-3": "3.31.3",
"@vueuse/core": "14.4.0",
"pinia": "^3.0.4",
"shiki": "^4.4.3",
"tailwindcss": "^4.1.18",
"vue": "^3.5.25",
"vue-router": "^4.6.3",
@@ -307,22 +306,6 @@
"@rollup/rollup-win32-x64-msvc": ["@rollup/rollup-win32-x64-msvc@4.54.0", "", { "os": "win32", "cpu": "x64" }, "sha512-hYT5d3YNdSh3mbCU1gwQyPgQd3T2ne0A3KG8KSBdav5TiBg6eInVmV+TeR5uHufiIgSFg0XsOWGW5/RhNcSvPg=="],
"@shikijs/core": ["@shikijs/core@4.4.3", "", { "dependencies": { "@shikijs/primitive": "4.4.3", "@shikijs/types": "4.4.3", "@shikijs/vscode-textmate": "^10.0.2", "@types/hast": "^3.0.5", "hast-util-to-html": "^9.0.5" } }, "sha512-QCR4q2ZO/ILJEuwiBMel4wdcTDb1JGwfjKTxPDF6x8ixOaluPrVqIn06C99AcRPhmYlBR56d/Fb+GN58GzExpg=="],
"@shikijs/engine-javascript": ["@shikijs/engine-javascript@4.4.3", "", { "dependencies": { "@shikijs/types": "4.4.3", "@shikijs/vscode-textmate": "^10.0.2", "oniguruma-to-es": "^4.3.6" } }, "sha512-FbOjFJp9VLdo1Wevs10BBtVxiTWwNLqZh5Gkhjgda/ioL15YOgeSl9n+6XMa3qRlPQzfhFNe641SrynFHYG0nQ=="],
"@shikijs/engine-oniguruma": ["@shikijs/engine-oniguruma@4.4.3", "", { "dependencies": { "@shikijs/types": "4.4.3", "@shikijs/vscode-textmate": "^10.0.2" } }, "sha512-EcOQkxdxGQrc1Row/cC2c96/v1dbZqGnEVu1qTuT/MJmp6+cXCvQussowVmCv5Tqr3KuY3c7IbM6HTW3LJ1k9w=="],
"@shikijs/langs": ["@shikijs/langs@4.4.3", "", { "dependencies": { "@shikijs/types": "4.4.3" } }, "sha512-ePic0yfAJGOF83D5wBHK/00EjK65oahBYxFk5epgq33WRv7X9UuxLEV8PtR0szC0z8dl7INIpIodB99JRFlR+A=="],
"@shikijs/primitive": ["@shikijs/primitive@4.4.3", "", { "dependencies": { "@shikijs/types": "4.4.3", "@shikijs/vscode-textmate": "^10.0.2", "@types/hast": "^3.0.5" } }, "sha512-m0wBeLDQDeIxRdUmrCPdQqfuUamDwRL5isCfYbguKD6NiaKpVbsv+3J81DyIKgNW5h4WAIIr8T4EkgQrBBxvaQ=="],
"@shikijs/themes": ["@shikijs/themes@4.4.3", "", { "dependencies": { "@shikijs/types": "4.4.3" } }, "sha512-w8UHjeUnIR965KMWJHUPXOc2mNJUnK3vpVLYLvw5IYU2mnTTJ89E24OrJDBNiJDQ0qzb0tc4l7mrIXx5cFeIyw=="],
"@shikijs/types": ["@shikijs/types@4.4.3", "", { "dependencies": { "@shikijs/vscode-textmate": "^10.0.2", "@types/hast": "^3.0.5" } }, "sha512-UEJxmRR++MAGR6hugn0vgVS2W/6lWAts84FFSrnlH9sP0LNol7E5+NQ792pH8liWUhyMyjhTgSUH3k7iD7tc5g=="],
"@shikijs/vscode-textmate": ["@shikijs/vscode-textmate@10.0.2", "", {}, "sha512-83yeghZ2xxin3Nj8z1NMd/NCuca+gsYXswywDy5bHvwlWL8tpTQmzGeUuHd9FC3E/SBEMvzJRwWEOz5gGes9Qg=="],
"@standard-schema/spec": ["@standard-schema/spec@1.1.0", "", {}, "sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w=="],
"@swc/helpers": ["@swc/helpers@0.5.23", "", { "dependencies": { "tslib": "^2.8.0" } }, "sha512-5lSsMOTXURePglDfvuAQUqkGek9Hg2kksOYay2m0+XR++b2NWYL/4sWyuvVBIs8oKnJaxkdi9whaL/sqN13afw=="],
@@ -453,16 +436,10 @@
"@types/estree": ["@types/estree@1.0.8", "", {}, "sha512-dWHzHa2WqEXI/O1E9OjrocMTKJl2mSrEolh1Iomrv6U+JuNwaHXsXx9bLu5gG7BUWFIN0skIQJQ/L1rIex4X6w=="],
"@types/hast": ["@types/hast@3.0.5", "", { "dependencies": { "@types/unist": "*" } }, "sha512-rp/ezSWaD1m44dPKICGhiskI13nVr7qTloFwDa/IYkhhf5nzwP+zIQcIJh3WIFSBOy/H1PzB40jPjMDksN4F+g=="],
"@types/json-schema": ["@types/json-schema@7.0.15", "", {}, "sha512-5+fP8P8MFNC+AyZCDxrB2pkZFPGzqQWUzpSeuuVLvm8VMcorNYavBqoFcxK8bQz4Qsbn4oUEEem4wDLfcysGHA=="],
"@types/mdast": ["@types/mdast@4.0.4", "", { "dependencies": { "@types/unist": "*" } }, "sha512-kGaNbPh1k7AFzgpud/gMdvIm5xuECykRR+JnWKQno9TAXVa6WIVCGTPvYGekIDL4uwCZQSYbUxNBSb1aUo79oA=="],
"@types/node": ["@types/node@24.10.4", "", { "dependencies": { "undici-types": "~7.16.0" } }, "sha512-vnDVpYPMzs4wunl27jHrfmwojOGKya0xyM3sH+UE5iv5uPS6vX7UIoh6m+vQc5LGBq52HBKPIn/zcSZVzeDEZg=="],
"@types/unist": ["@types/unist@3.0.3", "", {}, "sha512-ko/gIFJRv177XgZsZcBwnqJN5x/Gien8qNOn0D5bQU/zAzVf9Zt3BlcUiLqhV9y4ARk0GbT3tnUiPNgnTXzc/Q=="],
"@types/web-bluetooth": ["@types/web-bluetooth@0.0.21", "", {}, "sha512-oIQLCGWtcFZy2JW77j9k8nHzAOpqMHLQejDA48XXMWH6tjCQHz5RCFz1bzsmROyL6PUm+LLnUiI4BCn221inxA=="],
"@typescript-eslint/eslint-plugin": ["@typescript-eslint/eslint-plugin@8.50.0", "", { "dependencies": { "@eslint-community/regexpp": "^4.10.0", "@typescript-eslint/scope-manager": "8.50.0", "@typescript-eslint/type-utils": "8.50.0", "@typescript-eslint/utils": "8.50.0", "@typescript-eslint/visitor-keys": "8.50.0", "ignore": "^7.0.0", "natural-compare": "^1.4.0", "ts-api-utils": "^2.1.0" }, "peerDependencies": { "@typescript-eslint/parser": "^8.50.0", "eslint": "^8.57.0 || ^9.0.0", "typescript": ">=4.8.4 <6.0.0" } }, "sha512-O7QnmOXYKVtPrfYzMolrCTfkezCJS9+ljLdKW/+DCvRsc3UAz+sbH6Xcsv7p30+0OwUbeWfUDAQE0vpabZ3QLg=="],
@@ -485,8 +462,6 @@
"@typescript-eslint/visitor-keys": ["@typescript-eslint/visitor-keys@8.50.0", "", { "dependencies": { "@typescript-eslint/types": "8.50.0", "eslint-visitor-keys": "^4.2.1" } }, "sha512-Xzmnb58+Db78gT/CCj/PVCvK+zxbnsw6F+O1oheYszJbBSdEjVhQi3C/Xttzxgi/GLmpvOggRs1RFpiJ8+c34Q=="],
"@ungap/structured-clone": ["@ungap/structured-clone@1.4.0", "", {}, "sha512-1mEZtMKPM09vDmQt5y7YvmN2+DFTP7Tg0EWXdic8/C6VRnpb33e4ghisCIE3WZjsE2N8mf+QV1Zqh7ZFYLWInQ=="],
"@unhead/bundler": ["@unhead/bundler@3.4.1", "", { "dependencies": { "magic-string": "^1.3.1", "oxc-walker": "^1.1.1", "unplugin": "^3.3.0" }, "peerDependencies": { "@unhead/cli": "^3.4.1", "@vitejs/devtools-kit": "^0.4.1", "esbuild": ">=0.17.0", "lightningcss": ">=1.20.0", "oxc-parser": ">=0.98.0", "rolldown": ">=1.0.0", "unhead": "^3.4.1", "vite": ">=6.4.2", "webpack": ">=5.0.0" }, "optionalPeers": ["@unhead/cli", "@vitejs/devtools-kit", "esbuild", "lightningcss", "oxc-parser", "rolldown", "vite", "webpack"] }, "sha512-1RLNvuZYCt6K+oIK7v0mKlbmFbTuNZRgAMrf+GdmiO5xfml2pl/ViZmBrCOxoBtLxCboDZ70hs+F9+z2YWHLuQ=="],
"@unhead/vue": ["@unhead/vue@3.4.1", "", { "dependencies": { "@unhead/bundler": "3.4.1", "hookable": "^6.1.1", "unhead": "3.4.1", "unplugin": "^3.3.0" }, "peerDependencies": { "vite": ">=6.4.2", "vue": ">=3.5.18", "webpack": ">=5.0.0" }, "optionalPeers": ["vite", "webpack"] }, "sha512-FQLTdsX1+m+a7Z5SzkQde8TR/4QK6p0+NQ6BuO9zbtc5xps2fRy7W+wQ90qn177C2X88aZAPzw29mg6T4VFSdA=="],
@@ -603,16 +578,10 @@
"caniuse-lite": ["caniuse-lite@1.0.30001761", "", {}, "sha512-JF9ptu1vP2coz98+5051jZ4PwQgd2ni8A+gYSN7EA7dPKIMf0pDlSUxhdmVOaV3/fYK5uWBkgSXJaRLr4+3A6g=="],
"ccount": ["ccount@2.0.1", "", {}, "sha512-eyrF0jiFpY+3drT6383f1qhkbGsLSifNAjA61IUjZjmLCWjItY6LB9ft9YhoDgwfmclB2zhu51Lc7+95b8NRAg=="],
"chai": ["chai@6.2.2", "", {}, "sha512-NUPRluOfOiTKBKvWPtSD4PhFvWCqOi0BGStNWs57X9js7XGTprSmFoz5F0tWhR4WPjNeR9jXqdC7/UpSJTnlRg=="],
"chalk": ["chalk@4.1.2", "", { "dependencies": { "ansi-styles": "^4.1.0", "supports-color": "^7.1.0" } }, "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA=="],
"character-entities-html4": ["character-entities-html4@2.1.0", "", {}, "sha512-1v7fgQRj6hnSwFpq1Eu0ynr/CDEw0rXo2B61qXrLNdHZmPKgb7fqS1a2JwF0rISo9q77jDI8VMEHoApn8qDoZA=="],
"character-entities-legacy": ["character-entities-legacy@3.0.0", "", {}, "sha512-RpPp0asT/6ufRm//AJVwpViZbGM/MkjQFxJccQRHmISF/22NBtsHqAWmL+/pmkPWoIUJdWyeVleTl1wydHATVQ=="],
"chokidar": ["chokidar@5.0.0", "", { "dependencies": { "readdirp": "^5.0.0" } }, "sha512-TQMmc3w+5AxjpL8iIiwebF73dRDF4fBIieAqGn9RGCWaEVwQ6Fb2cGe31Yns0RRIzii5goJ1Y7xbMwo1TxMplw=="],
"citty": ["citty@0.1.6", "", { "dependencies": { "consola": "^3.2.3" } }, "sha512-tskPPKEs8D2KPafUypv2gxwJP8h/OaJmC82QQGGDQcHvXX43xF2VDACcJVmZ0EuSxkpO9Kc4MlrA3q0+FG58AQ=="],
@@ -625,8 +594,6 @@
"combined-stream": ["combined-stream@1.0.8", "", { "dependencies": { "delayed-stream": "~1.0.0" } }, "sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg=="],
"comma-separated-tokens": ["comma-separated-tokens@2.0.3", "", {}, "sha512-Fu4hJdvzeylCfQPp9SGWidpzrMs7tTrlu6Vb8XGaRGck8QSNZJJp538Wrb60Lax4fPwR64ViY468OIUTbRlGZg=="],
"commander": ["commander@14.0.3", "", {}, "sha512-H+y0Jo/T1RZ9qPP4Eh1pkcQcLRglraJaSLoyOtHxu6AapkjWVCy2Sit1QQ4x3Dng8qDlSsZEet7g5Pq06MvTgw=="],
"concat-map": ["concat-map@0.0.1", "", {}, "sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg=="],
@@ -673,14 +640,10 @@
"delayed-stream": ["delayed-stream@1.0.0", "", {}, "sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ=="],
"dequal": ["dequal@2.0.3", "", {}, "sha512-0je+qPKHEMohvfRTCEo3CrPG6cAzAYgmzKyxRiYSSDkS6eGJdyVJm7WaYA5ECaAD9wLB2T4EEeymA5aFVcYXCA=="],
"destr": ["destr@2.0.5", "", {}, "sha512-ugFTXCtDZunbzasqBxrK93Ik/DRYsO6S/fedkWEMKqt04xZ4csmnmwGDBAb07QWNaGMAmnTIemsYZCksjATwsA=="],
"detect-libc": ["detect-libc@2.1.2", "", {}, "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ=="],
"devlop": ["devlop@1.1.0", "", { "dependencies": { "dequal": "^2.0.0" } }, "sha512-RWmIqhcFf1lRYBvNmr7qTNuyCt/7/ns2jbpp1+PalgE/rDQcBT0fioSMUpJ93irlUhC5hrg4cYqe6U+0ImW0rA=="],
"dotenv": ["dotenv@17.4.2", "", {}, "sha512-nI4U3TottKAcAD9LLud4Cb7b2QztQMUEfHbvhTH09bqXTxnSie8WnjPALV/WMCrJZ6UV/qHJ6L03OqO3LcdYZw=="],
"dunder-proto": ["dunder-proto@1.0.1", "", { "dependencies": { "call-bind-apply-helpers": "^1.0.1", "es-errors": "^1.3.0", "gopd": "^1.2.0" } }, "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A=="],
@@ -831,18 +794,12 @@
"hasown": ["hasown@2.0.4", "", { "dependencies": { "function-bind": "^1.1.2" } }, "sha512-T2UbfbBEF32wiepXIsMlTW9+dDYC6wMh/t/vYA4tuOMKqWz/n3vr1NFSxQiyP+zk2mXsoMA/i/7qV6LKut1t1A=="],
"hast-util-to-html": ["hast-util-to-html@9.0.5", "", { "dependencies": { "@types/hast": "^3.0.0", "@types/unist": "^3.0.0", "ccount": "^2.0.0", "comma-separated-tokens": "^2.0.0", "hast-util-whitespace": "^3.0.0", "html-void-elements": "^3.0.0", "mdast-util-to-hast": "^13.0.0", "property-information": "^7.0.0", "space-separated-tokens": "^2.0.0", "stringify-entities": "^4.0.0", "zwitch": "^2.0.4" } }, "sha512-OguPdidb+fbHQSU4Q4ZiLKnzWo8Wwsf5bZfbvu7//a9oTYoqD/fWpe96NuHkoS9h0ccGOTe0C4NGXdtS0iObOw=="],
"hast-util-whitespace": ["hast-util-whitespace@3.0.0", "", { "dependencies": { "@types/hast": "^3.0.0" } }, "sha512-88JUN06ipLwsnv+dVn+OIYOvAuvBMy/Qoi6O7mQHxdPXpjy+Cd6xRkWwux7DKO+4sYILtLBRIKgsdpS2gQc7qw=="],
"hey-listen": ["hey-listen@1.0.8", "", {}, "sha512-COpmrF2NOg4TBWUJ5UVyaCU2A88wEMkUPK4hNqyCkqHbxT92BbvfjoSozkAIIm6XhicGlJHhFdullInrdhwU8Q=="],
"hookable": ["hookable@6.1.2", "", {}, "sha512-+abwxtiEA52GCVIsQqut3S/uKTbUwYIp4Pe/vv+6py5XiXBCqMZHg6pA6Y5qhgLSEys0/cYuPbO0z1QFj5ZCmg=="],
"html-encoding-sniffer": ["html-encoding-sniffer@4.0.0", "", { "dependencies": { "whatwg-encoding": "^3.1.1" } }, "sha512-Y22oTqIU4uuPgEemfz7NDJz6OeKf12Lsu+QC+s3BVpda64lTiMYCyGwg5ki4vFxkMwQdeZDl2adZoqUgdFuTgQ=="],
"html-void-elements": ["html-void-elements@3.0.0", "", {}, "sha512-bEqo66MRXsUGxWHV5IP0PUiAWwoEjba4VCzg0LjFJBpchPaTfyfCKTG6bc5F8ucKec3q5y6qOdGyYTSBEvhCrg=="],
"http-proxy-agent": ["http-proxy-agent@7.0.2", "", { "dependencies": { "agent-base": "^7.1.0", "debug": "^4.3.4" } }, "sha512-T1gkAiYYDWYx3V5Bmyu7HcfcvL7mUrTWiM6yOfa3PIphViJ/gFPbvidQ+veqSOHci/PxBcDabeUNCzpOODJZig=="],
"https-proxy-agent": ["https-proxy-agent@7.0.6", "", { "dependencies": { "agent-base": "^7.1.2", "debug": "4" } }, "sha512-vK9P5/iUfdl95AI+JVyUuIcVtd4ofvtrOr3HNtM2yxC9bnMbEdp3x01OhQNnjb8IJYi38VlTE3mBXwcfvywuSw=="],
@@ -963,8 +920,6 @@
"math-intrinsics": ["math-intrinsics@1.1.0", "", {}, "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g=="],
"mdast-util-to-hast": ["mdast-util-to-hast@13.2.1", "", { "dependencies": { "@types/hast": "^3.0.0", "@types/mdast": "^4.0.0", "@ungap/structured-clone": "^1.0.0", "devlop": "^1.0.0", "micromark-util-sanitize-uri": "^2.0.0", "trim-lines": "^3.0.0", "unist-util-position": "^5.0.0", "unist-util-visit": "^5.0.0", "vfile": "^6.0.0" } }, "sha512-cctsq2wp5vTsLIcaymblUriiTcZd0CwWtCbLvrOzYCDZoWyMNV8sZ7krj09FSnsiJi3WVsHLM4k6Dq/yaPyCXA=="],
"mdn-data": ["mdn-data@2.27.1", "", {}, "sha512-9Yubnt3e8A0OKwxYSXyhLymGW4sCufcLG6VdiDdUGVkPhpqLxlvP5vl1983gQjJl3tqbrM731mjaZaP68AgosQ=="],
"memorystream": ["memorystream@0.3.1", "", {}, "sha512-S3UwM3yj5mtUSEfP41UZmt/0SCoVYUcU1rkXv+BQ5Ig8ndL4sPoJNBUJERafdPb5jjHJGuMgytgKvKIf58XNBw=="],
@@ -973,16 +928,6 @@
"merge2": ["merge2@1.4.1", "", {}, "sha512-8q7VEgMJW4J8tcfVPy8g09NcQwZdbwFEqhe/WZkoIzjn/3TGDwtOCYtXGxA3O8tPzpczCCDgv+P2P5y00ZJOOg=="],
"micromark-util-character": ["micromark-util-character@2.1.1", "", { "dependencies": { "micromark-util-symbol": "^2.0.0", "micromark-util-types": "^2.0.0" } }, "sha512-wv8tdUTJ3thSFFFJKtpYKOYiGP2+v96Hvk4Tu8KpCAsTMs6yi+nVmGh1syvSCsaxz45J6Jbw+9DD6g97+NV67Q=="],
"micromark-util-encode": ["micromark-util-encode@2.0.1", "", {}, "sha512-c3cVx2y4KqUnwopcO9b/SCdo2O67LwJJ/UyqGfbigahfegL9myoEFoDYZgkT7f36T0bLrM9hZTAaAyH+PCAXjw=="],
"micromark-util-sanitize-uri": ["micromark-util-sanitize-uri@2.0.1", "", { "dependencies": { "micromark-util-character": "^2.0.0", "micromark-util-encode": "^2.0.0", "micromark-util-symbol": "^2.0.0" } }, "sha512-9N9IomZ/YuGGZZmQec1MbgxtlgougxTodVwDzzEouPKo3qFWvymFHWcnDi2vzV1ff6kas9ucW+o3yzJK9YB1AQ=="],
"micromark-util-symbol": ["micromark-util-symbol@2.0.1", "", {}, "sha512-vs5t8Apaud9N28kgCrRUdEed4UJ+wWNvicHLPxCa9ENlYuAY31M0ETy5y1vA33YoNPDFTghEbnh6efaE8h4x0Q=="],
"micromark-util-types": ["micromark-util-types@2.0.3", "", {}, "sha512-oxB2Ik03hI0gv+VNn9tnh1t1YEe9MDPptViAEgfdf3YQHsn0pzGTgCdlSCJXcwhqm8phaEuM7zeEu3QQzVBrPg=="],
"micromatch": ["micromatch@4.0.8", "", { "dependencies": { "braces": "^3.0.3", "picomatch": "^2.3.1" } }, "sha512-PXwfBhYu0hBCPw8Dn0E+WDYb7af3dSLVWKi3HGv84IdF4TyFoC0ysxFd0Goxw7nSv4T/PzEJQxsYsEiFCKo2BA=="],
"mime-db": ["mime-db@1.52.0", "", {}, "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg=="],
@@ -1045,10 +990,6 @@
"onetime": ["onetime@6.0.0", "", { "dependencies": { "mimic-fn": "^4.0.0" } }, "sha512-1FlR+gjXK7X+AsAHso35MnyN5KqGwJRi/31ft6x0M194ht7S+rWAvd7PHss9xSKMzE0asv1pyIHaJYq+BbacAQ=="],
"oniguruma-parser": ["oniguruma-parser@0.12.2", "", {}, "sha512-6HVa5oIrgMC6aA6WF6XyyqbhRPJrKR02L20+2+zpDtO5QAzGHAUGw5TKQvwi5vctNnRHkJYmjAhRVQF2EKdTQw=="],
"oniguruma-to-es": ["oniguruma-to-es@4.3.6", "", { "dependencies": { "oniguruma-parser": "^0.12.2", "regex": "^6.1.0", "regex-recursion": "^6.0.2" } }, "sha512-csuQ9x3Yr0cEIs/Zgx/OEt9iBw9vqIunAPQkx19R/fiMq2oGVTgcMqO/V3Ybqefr1TBvosI6jU539ksaBULJyA=="],
"open": ["open@10.2.0", "", { "dependencies": { "default-browser": "^5.2.1", "define-lazy-prop": "^3.0.0", "is-inside-container": "^1.0.0", "wsl-utils": "^0.1.0" } }, "sha512-YgBpdJHPyQ2UE5x+hlSXcnejzAvD0b22U2OuAP+8OnlJT+PjWPxtgmGqKKc+RgTM63U9gN0YzrYc71R2WT/hTA=="],
"optionator": ["optionator@0.9.4", "", { "dependencies": { "deep-is": "^0.1.3", "fast-levenshtein": "^2.0.6", "levn": "^0.4.1", "prelude-ls": "^1.2.1", "type-check": "^0.4.0", "word-wrap": "^1.2.5" } }, "sha512-6IpQ7mKUxRcZNLIObR0hz7lxsapSSIYNZJwXPGeF0mTVqGKFIXj1DQcMoT22S3ROcLyY/rz0PWaWZ9ayWmad9g=="],
@@ -1103,8 +1044,6 @@
"prettier-linter-helpers": ["prettier-linter-helpers@1.0.0", "", { "dependencies": { "fast-diff": "^1.1.2" } }, "sha512-GbK2cP9nraSSUF9N2XwUwqfzlAFlMNYYl+ShE/V+H8a9uNl/oUqB1w2EL54Jh0OlyRSd8RfWYJ3coVS4TROP2w=="],
"property-information": ["property-information@7.2.0", "", {}, "sha512-IAtzIB6sUiWaJYrX9smp3V46pBGbBeLFRGdh25kg1334VcBlD8HzhPeNIWQH9zhGmo2itIe25EHt9dQP7G5hmg=="],
"prosemirror-changeset": ["prosemirror-changeset@2.4.3", "", { "dependencies": { "prosemirror-transform": "^1.0.0" } }, "sha512-J8jqUZ1xybXKY44v3K0c8m8ZTIqJPVT34t2UVyxv4VEWoNd5C9t5Y52GNuMriRJ3IpNxOSE2R60vN4qBrTMcyQ=="],
"prosemirror-commands": ["prosemirror-commands@1.7.2", "", { "dependencies": { "prosemirror-model": "^1.0.0", "prosemirror-state": "^1.0.0", "prosemirror-transform": "^1.10.2" } }, "sha512-q6Q6szxqdu9Xd6EcdKsqXghu5nQdZTpB4Q9yd04WRc7/jt763e/rT60Owh0L1GYY+T46o5rD+9lEN36dZS43tw=="],
@@ -1147,12 +1086,6 @@
"readdirp": ["readdirp@5.1.1", "", {}, "sha512-Kko+Y5XQ6fM+Ce3dq3m9YGxnacYZYl9cA1wZjaF3Vbry2L3i1qVg8+CAgNPsXRArPMUMCaOR7oa9Nqntc43JKA=="],
"regex": ["regex@6.1.0", "", { "dependencies": { "regex-utilities": "^2.3.0" } }, "sha512-6VwtthbV4o/7+OaAF9I5L5V3llLEsoPyq9P1JVXkedTP33c7MfCG0/5NOPcSJn0TzXcG9YUrR0gQSWioew3LDg=="],
"regex-recursion": ["regex-recursion@6.0.2", "", { "dependencies": { "regex-utilities": "^2.3.0" } }, "sha512-0YCaSCq2VRIebiaUviZNs0cBz1kg5kVS2UKUfNIx8YVs1cN3AV7NTctO5FOKBA+UT2BPJIWZauYHPqJODG50cg=="],
"regex-utilities": ["regex-utilities@2.3.0", "", {}, "sha512-8VhliFJAWRaUiVvREIiW2NXXTmHs4vMNnSzuJVhscgmGav3g9VDxLrQndI3dZZVVdp0ZO/5v0xmX516/7M9cng=="],
"regexp-tree": ["regexp-tree@0.1.27", "", { "bin": { "regexp-tree": "bin/regexp-tree" } }, "sha512-iETxpjK6YoRWJG5o6hXLwvjYAoW+FEZn9os0PD/b6AP6xQwsa/Y7lCVgIixBbUPMfhu+i2LtdeAqVTgGlQarfA=="],
"reka-ui": ["reka-ui@2.10.4", "", { "dependencies": { "@floating-ui/dom": "^1.6.13", "@floating-ui/vue": "^1.1.6", "@internationalized/date": "^3.5.0", "@internationalized/number": "^3.5.0", "@tanstack/vue-virtual": "^3.12.0", "@vueuse/core": "^14.1.0", "@vueuse/shared": "^14.1.0", "aria-hidden": "^1.2.4", "defu": "^6.1.5", "ohash": "^2.0.11" }, "peerDependencies": { "vue": ">= 3.4.0" } }, "sha512-kbS5GAbkHkYj0EVKAg5ZPEPndhBjeUFSa1Aq5m5ftQwyHnB1v5tw8X6fcwfKH/ry3StPXblMWM1DW82MVS71cw=="],
@@ -1187,22 +1120,16 @@
"shell-quote": ["shell-quote@1.8.3", "", {}, "sha512-ObmnIF4hXNg1BqhnHmgbDETF8dLPCggZWBjkQfhZpbszZnYur5DUljTcCHii5LC3J5E0yeO/1LIMyH+UvHQgyw=="],
"shiki": ["shiki@4.4.3", "", { "dependencies": { "@shikijs/core": "4.4.3", "@shikijs/engine-javascript": "4.4.3", "@shikijs/engine-oniguruma": "4.4.3", "@shikijs/langs": "4.4.3", "@shikijs/themes": "4.4.3", "@shikijs/types": "4.4.3", "@shikijs/vscode-textmate": "^10.0.2", "@types/hast": "^3.0.5" } }, "sha512-Mb/GvXPHBAXdgGIcnfU5L3ldpn1XcxrGkPHwqgRx17/I2XRfqlFKk2vGkHWINn1kdXvzJZeuO3is6I9KLPFm0g=="],
"signal-exit": ["signal-exit@4.1.0", "", {}, "sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw=="],
"sirv": ["sirv@3.0.2", "", { "dependencies": { "@polka/url": "^1.0.0-next.24", "mrmime": "^2.0.0", "totalist": "^3.0.0" } }, "sha512-2wcC/oGxHis/BoHkkPwldgiPSYcpZK3JU28WoMVv55yHJgcZ8rlXvuG9iZggz+sU1d4bRgIGASwyWqjxu3FM0g=="],
"source-map-js": ["source-map-js@1.2.1", "", {}, "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA=="],
"space-separated-tokens": ["space-separated-tokens@2.0.2", "", {}, "sha512-PEGlAwrG8yXGXRjW32fGbg66JAlOAwbObuqVoJpv/mRgoWDQfgH1wDPvtzWyUSNAXBGSk8h755YDbbcEy3SH2Q=="],
"speakingurl": ["speakingurl@14.0.1", "", {}, "sha512-1POYv7uv2gXoyGFpBCmpDVSNV74IfsWlDW216UPjbWufNf+bSU6GdbDsxdcxtfwb4xlI3yxzOTKClUosxARYrQ=="],
"std-env": ["std-env@4.2.0", "", {}, "sha512-oCUKSupKTHX53EyjDtuZQ64pjLJ6yYCtpmEw0goYxtjG9KpbRe8KAsl2tBUGU9DyMcJ0RwJ8GqJAFzMXcXW1Rw=="],
"stringify-entities": ["stringify-entities@4.0.4", "", { "dependencies": { "character-entities-html4": "^2.0.0", "character-entities-legacy": "^3.0.0" } }, "sha512-IwfBptatlO+QCJUo19AqvrPNqlVMpW9YEL2LIVY+Rpv2qsjCGxaDLNRgeGsQWJhfItebuJhsGSLjaBbNSQ+ieg=="],
"strip-final-newline": ["strip-final-newline@3.0.0", "", {}, "sha512-dOESqjYr96iWYylGObzd39EuNTa5VJxyvVAEm5Jnh7KGo75V43Hk1odPQkNDyXNmUR6k+gEiDVXnjB8HJ3crXw=="],
"strip-json-comments": ["strip-json-comments@3.1.1", "", {}, "sha512-6fPc+R4ihwqP6N/aIv2f1gMH8lOVtWQHoqC4yK6oSDVVocumAsfCqjkXnqiYMhmMwS/mEHLp7Vehlt3ql6lEig=="],
@@ -1245,8 +1172,6 @@
"tr46": ["tr46@5.1.1", "", { "dependencies": { "punycode": "^2.3.1" } }, "sha512-hdF5ZgjTqgAntKkklYw0R03MG2x/bSzTtkxmIRw/sTNV8YXsCJ1tfLAX23lhxhHJlEf3CRCOCGGWw3vI3GaSPw=="],
"trim-lines": ["trim-lines@3.0.1", "", {}, "sha512-kRj8B+YHZCc9kQYdWfJB2/oUl9rA99qbowYYBtr4ui4mZyAQ2JpvVBd/6U2YloATfqBhBTSMhTpgBHtU0Mf3Rg=="],
"ts-api-utils": ["ts-api-utils@2.1.0", "", { "peerDependencies": { "typescript": ">=4.8.4" } }, "sha512-CUgTZL1irw8u29bzrOD/nH85jqyc74D6SshFgujOIA7osm2Rz7dYH77agkx7H4FBNxDq7Cjf+IjaX/8zwFW+ZQ=="],
"tslib": ["tslib@2.8.1", "", {}, "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w=="],
@@ -1275,16 +1200,6 @@
"unimport": ["unimport@6.5.0", "", { "dependencies": { "acorn": "^8.18.0", "escape-string-regexp": "^5.0.0", "estree-walker": "^3.0.3", "local-pkg": "^1.2.1", "magic-string": "^1.2.3", "mlly": "^1.8.2", "pathe": "^2.0.3", "picomatch": "^4.0.7", "pkg-types": "^2.3.3", "scule": "^1.3.0", "strip-literal": "^4.0.0", "tinyglobby": "^0.2.17", "unplugin": "^3.3.0", "unplugin-utils": "^0.3.2" }, "peerDependencies": { "oxc-parser": "*", "rolldown": "^1.0.0" }, "optionalPeers": ["oxc-parser", "rolldown"] }, "sha512-t0KLJLRbebz3f7NrQe+vy2ObeugVeM1XqI2oeYnauddmHSglYj3U6bxOJ65IbXmOFkcAGFJK2OyGH7aqHPM6Ug=="],
"unist-util-is": ["unist-util-is@6.0.1", "", { "dependencies": { "@types/unist": "^3.0.0" } }, "sha512-LsiILbtBETkDz8I9p1dQ0uyRUWuaQzd/cuEeS1hoRSyW5E5XGmTzlwY1OrNzzakGowI9Dr/I8HVaw4hTtnxy8g=="],
"unist-util-position": ["unist-util-position@5.0.0", "", { "dependencies": { "@types/unist": "^3.0.0" } }, "sha512-fucsC7HjXvkB5R3kTCO7kUjRdrS0BJt3M/FPxmHMBOm8JQi2BsHAHFsy27E0EolP8rp0NzXsJ+jNPyDWvOJZPA=="],
"unist-util-stringify-position": ["unist-util-stringify-position@4.0.0", "", { "dependencies": { "@types/unist": "^3.0.0" } }, "sha512-0ASV06AAoKCDkS2+xw5RXJywruurpbC4JZSm7nr7MOt1ojAzvyyaO+UxZf18j8FCF6kmzCZKcAgN/yu2gm2XgQ=="],
"unist-util-visit": ["unist-util-visit@5.1.0", "", { "dependencies": { "@types/unist": "^3.0.0", "unist-util-is": "^6.0.0", "unist-util-visit-parents": "^6.0.0" } }, "sha512-m+vIdyeCOpdr/QeQCu2EzxX/ohgS8KbnPDgFni4dQsfSCtpz8UqDyY5GjRru8PDKuYn7Fq19j1CQ+nJSsGKOzg=="],
"unist-util-visit-parents": ["unist-util-visit-parents@6.0.2", "", { "dependencies": { "@types/unist": "^3.0.0", "unist-util-is": "^6.0.0" } }, "sha512-goh1s1TBrqSqukSc8wrjwWhL0hiJxgA8m4kFxGlQ+8FYQ3C/m11FcTs4YYem7V664AhHVvgoQLk890Ssdsr2IQ=="],
"unplugin": ["unplugin@3.4.0", "", { "dependencies": { "@jridgewell/remapping": "^2.3.5", "picomatch": "^4.0.7", "webpack-virtual-modules": "^0.6.2" }, "peerDependencies": { "@farmfe/core": "*", "@rsbuild/core": "*", "@rspack/core": "*", "bun-types-no-globals": "*", "esbuild": "*", "rolldown": "*", "rollup": "*", "unloader": "*", "vite": "*", "webpack": "*" }, "optionalPeers": ["@farmfe/core", "@rsbuild/core", "@rspack/core", "bun-types-no-globals", "esbuild", "rolldown", "rollup", "unloader", "vite", "webpack"] }, "sha512-9skdIFlCsPdFV7wUfZxNsFInlW+7nJmGu2gkTu0OUhF56aXGsHab9x52/QhdJ4lC7ZDPWTxbiC4ANqVlsuaW3w=="],
"unplugin-auto-import": ["unplugin-auto-import@21.1.0", "", { "dependencies": { "local-pkg": "^1.2.1", "magic-string": "^1.1.0", "picomatch": "^4.0.5", "unimport": "^6.4.0", "unplugin": "^3.3.0", "unplugin-utils": "^0.3.2" }, "peerDependencies": { "@nuxt/kit": "^4.0.0", "@vueuse/core": "*" }, "optionalPeers": ["@nuxt/kit", "@vueuse/core"] }, "sha512-EzrSqWIBulEqCuP7idADXH+tVKYrbwKlR5+r/lOWik0o+Ksny1kitmtryHGNSv7puzzORlcIwT/x2JStiszlHA=="],
@@ -1307,10 +1222,6 @@
"verkit": ["verkit@0.3.2", "", {}, "sha512-zj/ob3UsvJGN0whEAKFp53REA5X66hvffVqoCtVQAakJKnKlH+/PcOfMoFwIG/o4rElqLv/ycAFlx8ZlXUorCg=="],
"vfile": ["vfile@6.0.3", "", { "dependencies": { "@types/unist": "^3.0.0", "vfile-message": "^4.0.0" } }, "sha512-KzIbH/9tXat2u30jf+smMwFCsno4wHVdNmzFyL+T/L3UGqqk6JKfVqOFOZEpZSHADH1k40ab6NUIXZq422ov3Q=="],
"vfile-message": ["vfile-message@4.0.3", "", { "dependencies": { "@types/unist": "^3.0.0", "unist-util-stringify-position": "^4.0.0" } }, "sha512-QTHzsGd1EhbZs4AsQ20JX1rC3cOlt/IWJruk893DfLRr57lcnOeMaWG4K0JrRta4mIJZKth2Au3mM3u03/JWKw=="],
"vite": ["vite@7.3.0", "", { "dependencies": { "esbuild": "^0.27.0", "fdir": "^6.5.0", "picomatch": "^4.0.3", "postcss": "^8.5.6", "rollup": "^4.43.0", "tinyglobby": "^0.2.15" }, "optionalDependencies": { "fsevents": "~2.3.3" }, "peerDependencies": { "@types/node": "^20.19.0 || >=22.12.0", "jiti": ">=1.21.0", "less": "^4.0.0", "lightningcss": "^1.21.0", "sass": "^1.70.0", "sass-embedded": "^1.70.0", "stylus": ">=0.54.8", "sugarss": "^5.0.0", "terser": "^5.16.0", "tsx": "^4.8.1", "yaml": "^2.4.2" }, "optionalPeers": ["@types/node", "jiti", "less", "lightningcss", "sass", "sass-embedded", "stylus", "sugarss", "terser", "tsx", "yaml"], "bin": { "vite": "bin/vite.js" } }, "sha512-dZwN5L1VlUBewiP6H9s2+B3e3Jg96D0vzN+Ry73sOefebhYr9f94wwkMNN/9ouoU8pV1BqA1d1zGk8928cx0rg=="],
"vite-dev-rpc": ["vite-dev-rpc@1.1.0", "", { "dependencies": { "birpc": "^2.4.0", "vite-hot-client": "^2.1.0" }, "peerDependencies": { "vite": "^2.9.0 || ^3.0.0-0 || ^4.0.0-0 || ^5.0.0-0 || ^6.0.1 || ^7.0.0-0" } }, "sha512-pKXZlgoXGoE8sEKiKJSng4hI1sQ4wi5YT24FCrwrLt6opmkjlqPPVmiPWWJn8M8byMxRGzp1CrFuqQs4M/Z39A=="],
@@ -1377,8 +1288,6 @@
"yocto-queue": ["yocto-queue@0.1.0", "", {}, "sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q=="],
"zwitch": ["zwitch@2.0.4", "", {}, "sha512-bXE4cR/kVZhKZX/RjPEflHaKVhUVl85noU3v6b8apfQEc1x4A+zBxjZ4lN8LqGd6WZ3dl98pY4o717VFmoPp+A=="],
"@babel/core/semver": ["semver@6.3.1", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA=="],
"@babel/helper-compilation-targets/lru-cache": ["lru-cache@5.1.1", "", { "dependencies": { "yallist": "^3.0.2" } }, "sha512-KpNARQA3Iwv+jTA0utUVVbrh+Jlrr1Fv0e56GGzAFOXN7dk/FviaDW8LHmK52DlcH4WP2n6gI8vN1aesBFgo9w=="],
-1
View File
@@ -27,7 +27,6 @@
"@tiptap/vue-3": "3.31.3",
"@vueuse/core": "14.4.0",
"pinia": "^3.0.4",
"shiki": "^4.4.3",
"tailwindcss": "^4.1.18",
"vue": "^3.5.25",
"vue-router": "^4.6.3"
+27 -19
View File
@@ -170,11 +170,15 @@
--ui-info: var(--ui-color-info-700);
--ui-warning: var(--ui-color-warning-700);
--ui-error: var(--ui-color-error-700);
--rc-success-soft: #eaefeb;
--rc-sand: #e8dfd1;
--rc-on-sand: #111111;
--rc-success-soft: #eaefea;
--rc-info-soft: #ebeef0;
--rc-warning-soft: #f0ede6;
--rc-error-soft: #f3eae9;
--rc-overlay: rgb(10 10 10 / 0.4);
--rc-shadow-pop: var(--shadow-popover);
--rc-shadow-modal: var(--shadow-modal);
}
.dark {
@@ -199,10 +203,12 @@
--ui-info: var(--ui-color-info-300);
--ui-warning: var(--ui-color-warning-300);
--ui-error: var(--ui-color-error-300);
--rc-success-soft: #202420;
--rc-info-soft: #202325;
--rc-warning-soft: #26221c;
--rc-error-soft: #28201e;
--rc-sand: #d4c5b0;
--rc-on-sand: #111111;
--rc-success-soft: #1f241f;
--rc-info-soft: #202428;
--rc-warning-soft: #2a251e;
--rc-error-soft: #2c201f;
--rc-overlay: rgb(0 0 0 / 0.6);
--shadow-popover: 0 4px 16px rgb(0 0 0 / 0.5);
--shadow-modal: 0 16px 48px rgb(0 0 0 / 0.6);
@@ -309,6 +315,16 @@ body {
.article-content a:hover {
text-decoration-thickness: 2px;
}
.article-content a:focus-visible,
.article-content .article-link-focus {
outline: 2px solid var(--ui-primary);
outline-offset: 2px;
}
.article-content a::selection,
.article-content a *::selection {
background: var(--rc-sand);
color: var(--rc-on-sand);
}
.article-content img {
display: block;
max-width: 100%;
@@ -373,18 +389,10 @@ body {
}
}
.shiki-block :where(pre.shiki) {
margin: 0;
padding: 0;
background-color: transparent !important;
}
.shiki-block :where(pre.shiki),
.shiki-block :where(pre.shiki span) {
color: var(--shiki-light);
}
.dark .shiki-block :where(pre.shiki),
.dark .shiki-block :where(pre.shiki span) {
color: var(--shiki-dark);
.image-placeholder {
background: repeating-linear-gradient(
135deg,
var(--ui-bg-elevated) 0 8px,
var(--ui-bg-accented) 8px 16px
);
}
+2 -2
View File
@@ -36,7 +36,7 @@ const emit = defineEmits<{
variant="ghost"
icon="i-lucide-x"
:aria-label="t('Remove filter {0}', [chip.label])"
class="size-5 justify-center p-0 text-muted"
class="size-5 justify-center p-0 text-muted hover:bg-accented hover:text-highlighted focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary"
:ui="{ leadingIcon: 'size-3' }"
@click="emit('remove', chip.key)"
/>
@@ -45,7 +45,7 @@ const emit = defineEmits<{
<UButton
color="neutral"
variant="link"
class="h-11 px-1.5 text-xs font-medium text-highlighted underline underline-offset-3 md:h-6"
class="h-11 px-1.5 text-xs font-medium text-highlighted underline underline-offset-3 hover:bg-elevated focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary md:h-6"
@click="emit('clear')"
>
{{ t('Clear all') }}
+248
View File
@@ -0,0 +1,248 @@
<script setup lang="ts">
import { t } from '@/i18n'
import { computed } from 'vue'
import type { ExportStage } from '@/composables/useActivityExport'
import { EXPORT_RANGE_KEYS, exportRangeLabel, type ExportRange } from '@/lib/activity'
const props = defineProps<{
stage: ExportStage
canSubmit: boolean
fileName: string
}>()
const emit = defineEmits<{
submit: []
close: []
}>()
const open = defineModel<boolean>('open', { default: false })
const range = defineModel<ExportRange>('range', { default: 'all' })
const from = defineModel<string>('from', { default: '' })
const to = defineModel<string>('to', { default: '' })
const MODAL_CONTENT =
'divide-y-0 shadow-(--shadow-modal) ring-0 sm:max-w-md md:top-35 md:translate-y-0 max-md:!inset-x-0 max-md:!top-auto max-md:!bottom-0 max-md:!left-0 max-md:!w-auto max-md:!max-w-none max-md:!translate-x-0 max-md:!translate-y-0 max-md:before:absolute max-md:before:top-2 max-md:before:left-1/2 max-md:before:h-1 max-md:before:w-9 max-md:before:-translate-x-1/2 max-md:before:bg-(--ui-border-accented) max-md:pt-3'
const BUTTON_CLASS = 'h-11 justify-center px-3 text-sm md:h-8'
const OUTLINE_CLASS = `${BUTTON_CLASS} border border-accented bg-default text-highlighted ring-0`
const FIELD_LABEL_CLASS = 'font-medium text-highlighted'
const CLOSE_BUTTON = {
color: 'neutral',
variant: 'ghost',
class: 'size-11 justify-center p-0 text-muted md:size-7',
} as const
const preparing = computed(() => props.stage === 'preparing')
const rangeItems = computed(() =>
EXPORT_RANGE_KEYS.map((key) => ({ value: key, label: exportRangeLabel(key) })),
)
const showCustomFields = computed(() => range.value === 'custom')
function onOpenChange(value: boolean) {
if (!value) emit('close')
}
</script>
<template>
<UModal
:open="open"
:title="t('Export all activity')"
:description="t('Downloads every event as a CSV file. Filters on the page are ignored.')"
:dismissible="!preparing"
:close="preparing ? false : CLOSE_BUTTON"
:ui="{
content: MODAL_CONTENT,
close: 'end-6 top-8 md:top-5',
header: 'min-h-0 items-start px-6 pt-5 pb-0 sm:px-6',
title: 'pe-14 text-lg/6 font-semibold md:pe-10',
description: 'mt-1 pe-14 text-sm text-muted text-pretty md:pe-10',
body: 'px-6 pt-5 pb-0 sm:px-6 sm:pt-5 sm:pb-0',
footer: 'px-6 py-5 sm:px-6',
}"
@update:open="onOpenChange"
>
<template #body>
<div class="flex flex-col gap-4">
<template v-if="stage === 'configure'">
<UFormField :label="t('Format')" :ui="{ label: FIELD_LABEL_CLASS }">
<UInput
model-value="CSV"
readonly
:aria-label="t('Format')"
class="w-full"
:ui="{
base: 'h-8 rounded-none border border-accented bg-default text-sm text-highlighted ring-0',
}"
/>
</UFormField>
<UFormField
:label="t('Date range')"
:help="t('Default is all time. Filters on the page are ignored.')"
:ui="{ label: FIELD_LABEL_CLASS, help: 'mt-1.5 text-xs text-muted' }"
>
<USelect
v-model="range"
:items="rangeItems"
value-key="value"
icon="i-lucide-calendar"
color="neutral"
variant="outline"
:aria-label="t('Date range')"
class="w-full"
:ui="{
base: 'h-11 rounded-none border border-accented bg-default ps-8 pe-8 text-sm ring-0 md:h-8',
leadingIcon: 'size-3.5 text-muted',
trailingIcon: 'size-3.5 text-muted',
}"
/>
</UFormField>
<div v-if="showCustomFields" class="flex items-center gap-2">
<UInput
v-model="from"
type="date"
icon="i-lucide-calendar"
:aria-label="t('Start date')"
class="min-w-0 flex-1"
:ui="{ base: 'h-11 w-full min-w-0 text-lg md:h-8 md:text-sm' }"
/>
<UInput
v-model="to"
type="date"
icon="i-lucide-calendar"
:aria-label="t('End date')"
class="min-w-0 flex-1"
:ui="{ base: 'h-11 w-full min-w-0 text-lg md:h-8 md:text-sm' }"
/>
</div>
</template>
<div v-else-if="preparing" class="flex flex-col gap-3">
<span class="flex items-center gap-2 font-medium text-highlighted">
<UIcon name="i-lucide-loader-circle" class="size-4 animate-spin" />
{{ t('Preparing download…') }}
</span>
<UProgress size="xs" color="primary" />
<span class="text-muted text-pretty">
{{
t(
'The file starts downloading as soon as it is ready. Keep this window open.',
)
}}
</span>
</div>
<div v-else-if="stage === 'started'" class="flex items-start gap-3">
<UIcon
name="i-lucide-circle-check"
class="mt-0.5 size-5 shrink-0 text-success"
/>
<div class="flex flex-col gap-0.5">
<span class="text-md font-semibold text-highlighted">{{
t('Download started')
}}</span>
<span class="text-muted">{{
t(
"{0} is downloading. Check your browser's downloads if nothing appears.",
[fileName],
)
}}</span>
</div>
</div>
<UAlert
v-else-if="stage === 'failed'"
role="alert"
color="error"
variant="soft"
icon="i-lucide-circle-x"
:close="false"
:title="t('Couldn\'t prepare the download')"
:description="t('Nothing was downloaded. Try again in a moment.')"
/>
<UAlert
v-else-if="stage === 'denied'"
role="alert"
color="error"
variant="soft"
icon="i-lucide-lock"
:close="false"
:title="t('You can\'t export all activity')"
:description="
t(
'Only owners and admins can export all activity. Ask an owner if you need a copy.',
)
"
/>
<div
v-else-if="stage === 'empty'"
class="flex flex-col items-center gap-2.5 py-3 text-center"
>
<span class="flex size-11 items-center justify-center bg-elevated text-toned">
<UIcon name="i-lucide-file-x" class="size-5" />
</span>
<span class="text-md font-semibold text-highlighted">{{
t('Nothing to export')
}}</span>
<span class="max-w-75 text-muted text-pretty">{{
t('There is no activity in this date range. Choose a wider range.')
}}</span>
</div>
</div>
</template>
<template #footer>
<div class="flex w-full flex-col-reverse gap-2 md:flex-row md:justify-end">
<template v-if="stage === 'configure' || preparing || stage === 'failed'">
<UButton
color="neutral"
variant="outline"
block
:class="[OUTLINE_CLASS, 'md:w-auto']"
@click="emit('close')"
>
{{ t('Cancel') }}
</UButton>
<UButton
v-if="stage === 'configure'"
icon="i-lucide-download"
block
:class="[BUTTON_CLASS, 'md:w-auto']"
:disabled="!canSubmit"
@click="emit('submit')"
>
{{ t('Export CSV') }}
</UButton>
<UButton
v-else-if="preparing"
block
disabled
:class="[BUTTON_CLASS, 'md:w-auto']"
>
{{ t('Preparing…') }}
</UButton>
<UButton
v-else
icon="i-lucide-rotate-cw"
block
:class="[BUTTON_CLASS, 'md:w-auto']"
@click="emit('submit')"
>
{{ t('Retry') }}
</UButton>
</template>
<UButton
v-else
color="neutral"
variant="outline"
block
:class="[OUTLINE_CLASS, 'md:w-auto']"
@click="emit('close')"
>
{{ t('Close') }}
</UButton>
</div>
</template>
</UModal>
</template>
+157
View File
@@ -0,0 +1,157 @@
<script setup lang="ts">
import { formatNumber, t } from '@/i18n'
import { NOTHING_TO_EXPORT_COPY, OWNERS_ONLY_COPY } from '@/lib/activity'
import { computed, ref } from 'vue'
const props = defineProps<{
total: number
isDesktop: boolean
disabled: boolean
nothingToExport: boolean
forbidden: boolean
}>()
const emit = defineEmits<{
current: []
all: []
}>()
const open = ref(false)
const BUTTON_CLASS =
'h-11 border border-accented bg-default px-3 text-sm text-highlighted ring-0 data-[state=open]:bg-elevated md:h-8'
const ITEM_HINT_CLASS = 'text-xs/4.5 text-muted text-pretty'
const currentDisabled = computed(() => props.forbidden || props.nothingToExport)
const currentHint = computed(() => {
if (props.forbidden) return t(OWNERS_ONLY_COPY)
if (props.nothingToExport) return t(NOTHING_TO_EXPORT_COPY)
return props.total === 1
? t('CSV · 1 event matching your filters and sort, across all pages')
: t('CSV · {0} events matching your filters and sort, across all pages', [
formatNumber(props.total),
])
})
const allHint = computed(() =>
props.forbidden
? t(OWNERS_ONLY_COPY)
: t('CSV · every event, ignoring filters. Owners and admins only.'),
)
const trailingIcon = computed(() => (open.value ? 'i-lucide-chevron-up' : 'i-lucide-chevron-down'))
const entries = computed(() => [
{
action: 'current' as const,
label: t('Export current view'),
description: currentHint.value,
icon: 'i-lucide-download',
disabled: currentDisabled.value,
},
{
action: 'all' as const,
label: t('Export all activity…'),
description: allHint.value,
icon: props.forbidden ? 'i-lucide-lock' : 'i-lucide-archive',
disabled: props.forbidden,
},
])
const items = computed(() =>
entries.value.map(({ action, label, description, icon, disabled }) => [
{ label, description, icon, disabled, onSelect: () => choose(action) },
]),
)
function choose(action: 'current' | 'all') {
open.value = false
if (action === 'current') emit('current')
else emit('all')
}
</script>
<template>
<UDropdownMenu
v-if="isDesktop"
v-model:open="open"
:items="items"
:content="{ align: 'end', sideOffset: 4 }"
:ui="{
content: 'w-90 rounded-none p-1 shadow-(--rc-shadow-pop)',
group: 'p-0',
separator: 'my-0',
item: 'min-h-14 items-start gap-3 rounded-none px-3 py-2.5 text-sm data-disabled:opacity-100 data-disabled:text-muted',
itemLeadingIcon: 'mt-0.5 size-4 text-highlighted group-data-disabled:text-muted',
itemLabel: 'font-medium',
itemDescription: 'text-xs/4.5 text-muted text-pretty whitespace-normal',
}"
>
<UButton
color="neutral"
variant="outline"
icon="i-lucide-download"
:trailing-icon="trailingIcon"
:disabled="disabled"
:class="BUTTON_CLASS"
:ui="{ trailingIcon: 'size-3.5 text-muted' }"
>
{{ t('Export') }}
</UButton>
</UDropdownMenu>
<template v-else>
<UButton
color="neutral"
variant="outline"
icon="i-lucide-download"
:trailing-icon="trailingIcon"
:disabled="disabled"
:class="BUTTON_CLASS"
:ui="{ trailingIcon: 'size-3.5 text-muted' }"
@click="open = true"
>
{{ t('Export') }}
</UButton>
<USlideover
v-model:open="open"
side="bottom"
:title="t('Export')"
:description="t('Export')"
:ui="{
content:
'max-h-none before:absolute before:top-2 before:left-1/2 before:h-1 before:w-9 before:-translate-x-1/2 before:bg-(--ui-border-accented) pt-3',
header: 'h-14 min-h-14 border-b border-default px-4 py-0 sm:px-4',
title: 'text-lg font-semibold text-highlighted',
description: 'sr-only',
close: 'top-4.5 end-2 size-11 justify-center p-0',
body: 'p-0 pb-4 sm:p-0 sm:pb-4',
}"
>
<template #body>
<div role="menu" :aria-label="t('Export')" class="flex flex-col">
<template v-for="(entry, index) in entries" :key="entry.action">
<USeparator v-if="index > 0" />
<UButton
role="menuitem"
color="neutral"
variant="ghost"
block
:icon="entry.icon"
:disabled="entry.disabled"
class="min-h-16 items-start justify-start gap-3 rounded-none px-4 py-3 text-start text-sm text-highlighted disabled:text-muted disabled:opacity-100"
:ui="{ leadingIcon: 'mt-0.5 size-4' }"
@click="choose(entry.action)"
>
<span class="flex min-w-0 flex-col gap-0.5">
<span class="font-medium">{{ entry.label }}</span>
<span :class="[ITEM_HINT_CLASS, 'font-normal']">{{
entry.description
}}</span>
</span>
</UButton>
</template>
</div>
</template>
</USlideover>
</template>
</template>
+72 -10
View File
@@ -1,5 +1,7 @@
<script setup lang="ts">
import { computed } from 'vue'
import { t } from '@/i18n'
import { computed, ref } from 'vue'
import type { ActivityFilters, ActivitySummary } from '@/lib/activity'
import {
barHeights,
@@ -41,6 +43,14 @@ const VALUE_TONES: Record<StripCard['tone'], string> = {
warning: 'text-warning',
calm: 'text-highlighted',
}
const PRESSED_TEXT = 'text-(--rc-on-sand)'
const PRESSED_BAR = 'bg-(--rc-on-sand)'
const hovered = ref<StripKey | null>(null)
function isToggle(key: StripKey) {
return key === 'failed' || key === 'security'
}
function pressed(key: StripKey) {
if (key === 'failed') return props.outcome === 'failed'
@@ -49,14 +59,18 @@ function pressed(key: StripKey) {
}
function rootClass(card: StripCard) {
const fill =
card.tone === 'error'
const isPressed = pressed(card.key)
const fill = isPressed
? 'bg-(--rc-sand)'
: card.tone === 'error'
? 'bg-(--rc-error-soft)'
: card.tone === 'warning'
? 'bg-(--rc-warning-soft)'
: 'bg-default'
const edge = pressed(card.key)
const edge = isPressed
? 'border-primary ring-1 ring-primary ring-inset'
: isToggle(card.key)
? 'border-default ring-0 hover:border-accented hover:bg-elevated'
: 'border-default ring-0'
return [
'w-full cursor-pointer border text-left max-md:w-auto max-md:shrink-0 max-md:basis-39 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary',
@@ -64,6 +78,44 @@ function rootClass(card: StripCard) {
edge,
]
}
function labelClass(card: StripCard) {
return pressed(card.key) ? PRESSED_TEXT : 'text-toned'
}
function valueClass(card: StripCard) {
return pressed(card.key) ? PRESSED_TEXT : VALUE_TONES[card.tone]
}
function barClass(card: StripCard) {
return pressed(card.key) ? PRESSED_BAR : BAR_TONES[card.tone]
}
function sublineClass(card: StripCard) {
if (pressed(card.key)) return PRESSED_TEXT
return card.tone === 'calm' ? 'text-success' : 'text-muted'
}
function hint(card: StripCard) {
if (!isToggle(card.key)) return null
if (pressed(card.key)) {
return hovered.value === card.key
? { text: t('Click to clear this filter'), icon: 'i-lucide-x' }
: { text: t('Filtering. Click to clear'), icon: 'i-lucide-filter' }
}
return hovered.value === card.key
? { text: t('Click to filter the list'), icon: 'i-lucide-filter' }
: null
}
function sublineText(card: StripCard) {
return hint(card)?.text ?? card.subline
}
function sublineIcon(card: StripCard) {
const shown = hint(card)
return shown ? shown.icon : card.icon
}
</script>
<template>
@@ -102,11 +154,15 @@ function rootClass(card: StripCard) {
root: 'overflow-visible rounded-none shadow-none md:min-w-0',
body: 'p-0 sm:p-0',
}"
@mouseenter="hovered = card.key"
@mouseleave="hovered = null"
@click="emit('apply-filter', card.key)"
>
<span class="flex flex-col gap-0.5" :class="CARD_PADDING">
<span class="flex items-center justify-between gap-2">
<span class="truncate font-medium text-toned">{{ card.label }}</span>
<span class="truncate font-medium" :class="labelClass(card)">{{
card.label
}}</span>
<span
aria-hidden="true"
data-testid="activity-bars"
@@ -117,22 +173,28 @@ function rootClass(card: StripCard) {
v-for="(height, index) in barHeights(card.series, barHeight)"
:key="index"
class="block w-1"
:class="BAR_TONES[card.tone]"
:class="barClass(card)"
:style="{ height: `${height}px` }"
/>
</span>
</span>
<span
class="text-stat-sm font-semibold md:text-stat"
:class="VALUE_TONES[card.tone]"
:class="valueClass(card)"
>{{ card.value }}</span
>
<span
class="flex items-center gap-1 truncate text-xs/5"
:class="card.tone === 'calm' ? 'text-success' : 'text-muted'"
:class="sublineClass(card)"
>
<UIcon v-if="card.icon" :name="card.icon" class="size-3 shrink-0" />
<span class="truncate">{{ card.subline }}</span>
<UIcon
v-if="sublineIcon(card)"
:name="sublineIcon(card)!"
class="size-3 shrink-0"
/>
<span class="truncate" data-testid="activity-strip-subline">{{
sublineText(card)
}}</span>
</span>
</span>
</UCard>
+5 -25
View File
@@ -2,7 +2,7 @@
import { t } from '@/i18n'
import { computed, nextTick, ref, watch } from 'vue'
import { useCopyToClipboard } from '@/composables/useCopyToClipboard'
import CodeSnippet from '@/components/CodeSnippet.vue'
const props = defineProps<{
name: string
@@ -13,14 +13,12 @@ const open = defineModel<boolean>('open', { default: false })
const emit = defineEmits<{ done: [] }>()
const { copied, copy } = useCopyToClipboard()
const copyButton = ref<{ $el: HTMLElement } | null>(null)
const snippet = ref<{ focusCopy: () => void } | null>(null)
const description = computed(() =>
t('"{0}" is ready. Copy the key and store it somewhere safe.', [props.name]),
)
const copyLabel = computed(() => (copied.value ? t('Copied') : t('Copy')))
const copyIcon = computed(() => (copied.value ? 'i-lucide-check' : 'i-lucide-copy'))
const keyTabs = computed(() => [{ k: 'key', label: t('API key'), code: props.apiKey }])
watch(
open,
@@ -30,7 +28,7 @@ watch(
}
await nextTick()
await nextTick()
copyButton.value?.$el?.focus()
snippet.value?.focusCopy()
},
{ immediate: true },
)
@@ -78,25 +76,7 @@ function keepOpenOnOutsideInteraction(event: Event) {
:title="t('You won\'t be able to see this key again.')"
:ui="{ root: 'gap-2.5 px-3 py-2.5', title: 'text-sm font-medium' }"
/>
<div class="flex flex-col border border-accented bg-elevated md:flex-row">
<span
class="min-w-0 flex-1 px-3 py-2.5 font-mono text-code/5 break-all text-highlighted"
>{{ apiKey }}</span
>
<UButton
ref="copyButton"
:icon="copyIcon"
color="neutral"
variant="ghost"
aria-live="polite"
class="h-11 justify-center gap-1.5 rounded-none border-t border-accented px-3.5 font-medium md:border-t-0 md:border-l"
:class="copied ? 'text-success' : 'text-highlighted'"
:ui="{ leadingIcon: 'size-3.5' }"
@click="copy(apiKey)"
>
{{ copyLabel }}
</UButton>
</div>
<CodeSnippet ref="snippet" :tabs="keyTabs" />
<span class="text-muted">{{
t('Closing this window discards the key from the screen. Copy it first.')
}}</span>
+200
View File
@@ -0,0 +1,200 @@
<script setup lang="ts">
import { t, formatNumber } from '@/i18n'
import { computed } from 'vue'
import { useMediaQuery } from '@vueuse/core'
import { pageItems, rangeFor } from '@/lib/pagination'
import { ARTICLE_PAGE_SIZES } from '@/lib/articleListQuery'
const DESKTOP_QUERY = '(min-width: 48rem)'
const props = defineProps<{
page: number
pageCount: number
total: number
size: number
loadingPage: number | null
}>()
const emit = defineEmits<{
'update:page': [page: number]
'update:size': [size: number]
}>()
const isDesktop = useMediaQuery(DESKTOP_QUERY)
const busy = computed(() => props.loadingPage !== null)
const atStart = computed(() => busy.value || props.page <= 1)
const atEnd = computed(() => busy.value || props.page >= props.pageCount)
const showControls = computed(() => props.pageCount > 1)
const items = computed(() => pageItems(props.page, props.pageCount))
const summary = computed(() => {
if (props.loadingPage !== null) {
return t('Loading page {0}…', [formatNumber(props.loadingPage)])
}
const { from, to } = rangeFor(props.page, props.size, props.total)
return t('Showing {0}–{1} of {2}', [
formatNumber(from),
formatNumber(to),
formatNumber(props.total),
])
})
const sizeItems = computed(() =>
ARTICLE_PAGE_SIZES.map((value) => ({ label: t('{0} per page', [value]), value })),
)
const FOCUS_RING =
'focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary'
const CONTROL = `justify-center rounded-none border border-accented bg-default p-0 text-highlighted ring-0 disabled:opacity-40 aria-disabled:opacity-40 ${FOCUS_RING}`
const ICON_CONTROL = `size-11 md:size-8 ${CONTROL}`
const CURRENT_PAGE = 'border-primary bg-(--rc-sand) font-semibold text-(--rc-on-sand)'
function numberClass(number: number) {
const sizing = `h-11 min-w-11 px-1.5 md:h-8 md:min-w-8 ${CONTROL}`
return number === props.page ? `${sizing} ${CURRENT_PAGE}` : `${sizing} font-normal`
}
</script>
<template>
<div v-if="isDesktop" data-testid="paginator" class="flex items-center gap-4 pt-3">
<span aria-live="polite" data-testid="paginator-summary" class="flex-1 text-muted">{{
summary
}}</span>
<USelectMenu
:model-value="size"
:items="sizeItems"
value-key="value"
:search-input="false"
:disabled="busy"
:aria-label="t('Rows per page')"
:content="{ side: 'top', align: 'start' }"
color="neutral"
variant="outline"
class="w-30"
:ui="{
base: `h-8 rounded-none border border-accented bg-default pl-3 pr-2 text-sm ring-0 focus-visible:ring-0 ${FOCUS_RING}`,
trailingIcon: 'size-3.5 text-muted',
content: 'w-40 rounded-none',
itemTrailingIcon: 'hidden',
item: 'h-8 rounded-none data-[state=checked]:bg-(--rc-sand) data-[state=checked]:font-semibold data-[state=checked]:text-(--rc-on-sand)',
}"
@update:model-value="emit('update:size', $event as number)"
/>
<nav v-if="showControls" :aria-label="t('Pagination')" class="flex items-center gap-1">
<UButton
color="neutral"
variant="outline"
icon="i-lucide-chevrons-left"
:disabled="atStart"
:aria-label="t('First page')"
:class="ICON_CONTROL"
@click="emit('update:page', 1)"
/>
<UButton
color="neutral"
variant="outline"
icon="i-lucide-chevron-left"
:disabled="atStart"
:aria-label="t('Previous page')"
:class="ICON_CONTROL"
@click="emit('update:page', page - 1)"
/>
<template v-for="(item, index) in items" :key="`${item}-${index}`">
<span
v-if="item === 'gap'"
aria-hidden="true"
class="flex h-8 min-w-8 items-center justify-center text-muted"
>…</span
>
<UButton
v-else
color="neutral"
variant="outline"
:disabled="busy"
:aria-current="item === page ? 'page' : undefined"
:class="numberClass(item)"
@click="emit('update:page', item)"
>
{{ formatNumber(item) }}
</UButton>
</template>
<UButton
color="neutral"
variant="outline"
icon="i-lucide-chevron-right"
:disabled="atEnd"
:aria-label="t('Next page')"
:class="ICON_CONTROL"
@click="emit('update:page', page + 1)"
/>
<UButton
color="neutral"
variant="outline"
icon="i-lucide-chevrons-right"
:disabled="atEnd"
:aria-label="t('Last page')"
:class="ICON_CONTROL"
@click="emit('update:page', pageCount)"
/>
</nav>
</div>
<div v-else data-testid="paginator" class="flex flex-col gap-3 pt-3 pb-4">
<div class="flex flex-wrap items-center justify-between gap-3">
<span aria-live="polite" data-testid="paginator-summary" class="text-muted">{{
summary
}}</span>
<USelectMenu
:model-value="size"
:items="sizeItems"
value-key="value"
:search-input="false"
:disabled="busy"
:aria-label="t('Rows per page')"
:content="{ side: 'top', align: 'end' }"
color="neutral"
variant="outline"
class="w-30"
:ui="{
base: `h-11 rounded-none border border-accented bg-default pl-3 pr-2 text-sm ring-0 focus-visible:ring-0 ${FOCUS_RING}`,
trailingIcon: 'size-3.5 text-muted',
content: 'w-40 rounded-none',
itemTrailingIcon: 'hidden',
item: 'h-11 rounded-none data-[state=checked]:bg-(--rc-sand) data-[state=checked]:font-semibold data-[state=checked]:text-(--rc-on-sand)',
}"
@update:model-value="emit('update:size', $event as number)"
/>
</div>
<nav v-if="showControls" :aria-label="t('Pagination')" class="flex items-center gap-2">
<UButton
color="neutral"
variant="outline"
icon="i-lucide-chevron-left"
:disabled="atStart"
:aria-label="t('Previous page')"
:class="`h-11 flex-1 ${CONTROL}`"
@click="emit('update:page', page - 1)"
>
{{ t('Previous') }}
</UButton>
<span
aria-current="page"
class="shrink-0 px-1 font-medium whitespace-nowrap text-highlighted"
>{{ t('Page {0} of {1}', [formatNumber(page), formatNumber(pageCount)]) }}</span
>
<UButton
color="neutral"
variant="outline"
trailing-icon="i-lucide-chevron-right"
:disabled="atEnd"
:aria-label="t('Next page')"
:class="`h-11 flex-1 ${CONTROL}`"
@click="emit('update:page', page + 1)"
>
{{ t('Next') }}
</UButton>
</nav>
</div>
</template>
+7 -3
View File
@@ -6,12 +6,16 @@ import ArticleStatusBadge from '@/components/ArticleStatusBadge.vue'
import { formatRelativeDate } from '@/lib/relativeDate'
import type { Article } from '@/composables/useArticles'
const props = defineProps<{
const props = withDefaults(
defineProps<{
articles: Article[]
loading: boolean
skeletonRows?: number
busyIds: Set<number>
now?: Date
}>()
}>(),
{ skeletonRows: 5 },
)
const emit = defineEmits<{
publish: [id: number]
@@ -97,7 +101,7 @@ function onRowClick(article: Article, event: MouseEvent) {
>
<template v-if="loading">
<li
v-for="n in 5"
v-for="n in skeletonRows"
:key="n"
class="flex min-h-17 flex-col justify-center gap-2 border-t border-muted py-3 pl-4 pr-1 first:border-t-0"
>
+75 -3
View File
@@ -1,9 +1,14 @@
<script setup lang="ts">
import { t } from '@/i18n'
import { ref } from 'vue'
import { computed, ref, shallowRef } from 'vue'
import type { EditorToolbarItem } from '@nuxt/ui'
import type { Editor } from '@tiptap/core'
import LinkModal from '@/components/LinkModal.vue'
import LinkPopover from '@/components/LinkPopover.vue'
import { useArticleLink } from '@/composables/useArticleLink'
import { useScrollEdges } from '@/composables/useScrollEdges'
import { ArticleLink } from '@/lib/articleLink'
import { ArticleIndent } from '@/lib/articleIndent'
import { ArticleTextAlign } from '@/lib/articleAlign'
import { ArticleImage, findArticleImagePos } from '@/lib/articleImage'
@@ -25,10 +30,18 @@ const emit = defineEmits<{
'request-remove-image': [imageId: number]
}>()
const editorInstance = ref<Editor | null>(null)
const editorInstance = shallowRef<Editor | null>(null)
const toolbarRef = ref<{ $el: HTMLElement } | null>(null)
const toolbarElement = computed(() => toolbarRef.value?.$el ?? null)
const { hiddenBefore, hiddenAfter } = useScrollEdges(toolbarElement)
const link = useArticleLink(editorInstance, () => props.disabled)
const extensions = [
ArticleIndent,
ArticleTextAlign,
ArticleLink.configure({
onRequestDialog: () => link.openDialog(),
onRequestPopover: (target) => link.openPopover(target),
}),
ArticleImage.configure({
onRequestRemove: (imageId: number) => emit('request-remove-image', imageId),
}),
@@ -276,6 +289,7 @@ function buildItems(editor: Editor): EditorToolbarItem[][] {
},
],
[
link.toolbarItem(editor),
{
kind: 'clearFormatting',
icon: 'i-lucide-remove-formatting',
@@ -342,6 +356,7 @@ defineExpose({
v-slot="{ editor }"
:model-value="props.modelValue"
:extensions="extensions"
:starter-kit="{ link: false }"
:image="false"
content-type="html"
:editable="!props.disabled"
@@ -351,18 +366,51 @@ defineExpose({
>
<span class="hidden">{{ captureEditor(editor) }}</span>
<UEditorDragHandle :editor="editor" />
<div class="relative col-span-full row-start-1 min-w-0">
<UEditorToolbar
ref="toolbarRef"
:editor="editor"
:items="buildItems(editor)"
layout="fixed"
class="col-span-full row-start-1 min-w-0 overflow-x-auto border-b border-default bg-default px-6 py-1.5 [&>*]:shrink-0"
class="article-toolbar min-w-0 overflow-x-auto border-b border-default bg-default px-2 py-1.5 sm:px-6 [&>*]:shrink-0"
/>
<span
v-if="hiddenBefore"
data-testid="toolbar-fade-start"
aria-hidden="true"
class="pointer-events-none absolute inset-y-0 left-0 w-6 bg-linear-to-r from-default to-transparent"
/>
<span
v-if="hiddenAfter"
data-testid="toolbar-fade-end"
aria-hidden="true"
class="pointer-events-none absolute inset-y-0 right-0 w-8 bg-linear-to-l from-default to-transparent"
/>
</div>
<div class="col-start-1 row-start-3">
<slot name="footer" />
</div>
<div class="col-start-2 row-span-2 row-start-2 hidden min-h-0 lg:block">
<slot name="aside" />
</div>
<LinkModal
v-model:open="link.dialogOpen.value"
:mode="link.dialog.value.mode"
:text="link.dialog.value.text"
:href="link.dialog.value.href"
:new-tab="link.dialog.value.newTab"
@submit="link.apply"
@remove="link.removeFromDialog"
/>
<LinkPopover
v-model:open="link.popoverOpen.value"
:href="link.popover.value.href"
:text="link.popover.value.text"
:reference="link.popover.value.element"
@edit="link.editFromPopover"
@open-link="link.openFromPopover"
@remove="link.removeFromPopover"
/>
</UEditor>
</template>
@@ -380,6 +428,30 @@ defineExpose({
padding: 2.5rem 3rem;
outline: none;
}
.article-editor :deep(.ProseMirror ul),
.article-editor :deep(.ProseMirror ol) {
padding-left: 1.75rem;
}
.article-editor :deep(.ProseMirror li) {
margin: 0;
padding-left: 0;
}
.article-editor :deep(.ProseMirror h2) {
margin-top: 2rem;
}
.article-toolbar {
scrollbar-width: none;
}
.article-toolbar::-webkit-scrollbar {
display: none;
}
@media (max-width: 39.999rem) {
.article-toolbar :deep(button) {
min-width: 2.5rem;
min-height: 2.5rem;
justify-content: center;
}
}
@media (max-width: 47.999rem) {
.article-editor :deep(.ProseMirror) {
padding: 1.5rem 1rem;
+91 -30
View File
@@ -1,24 +1,31 @@
<script setup lang="ts">
import { t } from '@/i18n'
import { ref } from 'vue'
import { computed, ref, watchPostEffect } from 'vue'
import { useRouter } from 'vue-router'
import ArticleStatusBadge from '@/components/ArticleStatusBadge.vue'
import { formatAbsoluteDateFromIso, formatRelativeDate } from '@/lib/relativeDate'
import type { Article } from '@/composables/useArticles'
import { DEFAULT_ARTICLE_SORT, type ArticleSortField } from '@/lib/articleListQuery'
const props = defineProps<{
const props = withDefaults(
defineProps<{
articles: Article[]
loading: boolean
skeletonRows?: number
sort?: string
busyIds: Set<number>
now?: Date
}>()
}>(),
{ skeletonRows: 5, sort: DEFAULT_ARTICLE_SORT },
)
const emit = defineEmits<{
publish: [id: number]
unpublish: [id: number]
delete: [article: Article]
'copy-url': [id: number]
sort: [field: ArticleSortField]
}>()
const router = useRouter()
@@ -26,7 +33,42 @@ const router = useRouter()
const columnWidths =
'[&:nth-child(2)]:w-27.5 [&:nth-child(3)]:w-32.5 [&:nth-child(4)]:w-35 [&:nth-child(5)]:w-11'
const sorting = ref([{ id: 'updated_at', desc: true }])
const sorting = computed(() => {
const [id, direction] = props.sort.split(':')
return [{ id: id!, desc: direction === 'desc' }]
})
const tableRoot = ref<HTMLElement | null>(null)
const SORTABLE_COLUMNS = ['title', 'status', 'created_at', 'updated_at']
watchPostEffect(() => {
const [active, direction] = props.sort.split(':')
tableRoot.value?.querySelectorAll('thead th').forEach((header, index) => {
if (SORTABLE_COLUMNS[index] === active) {
header.setAttribute('aria-sort', direction === 'desc' ? 'descending' : 'ascending')
} else {
header.removeAttribute('aria-sort')
}
})
})
const COLUMN_NAMES = {
title: () => t('title'),
status: () => t('status'),
created_at: () => t('created'),
updated_at: () => t('updated'),
}
const caption = computed(() => {
if (props.sort === DEFAULT_ARTICLE_SORT) {
return t('Articles, sorted by last updated, newest first')
}
const [field, direction] = props.sort.split(':') as [ArticleSortField, string]
return t('Articles, sorted by {0}, {1}', [
COLUMN_NAMES[field](),
direction === 'desc' ? t('descending') : t('ascending'),
])
})
const columns = [
{
@@ -34,15 +76,16 @@ const columns = [
get header() {
return t('Title')
},
enableSorting: true,
enableSorting: false,
},
{
accessorKey: 'is_online',
id: 'status',
get header() {
return t('Status')
},
size: 110,
enableSorting: true,
enableSorting: false,
},
{
accessorKey: 'created_at',
@@ -50,7 +93,7 @@ const columns = [
return t('Created')
},
size: 130,
enableSorting: true,
enableSorting: false,
},
{
accessorKey: 'updated_at',
@@ -58,21 +101,18 @@ const columns = [
return t('Updated')
},
size: 140,
enableSorting: true,
enableSorting: false,
},
{ id: 'actions', header: '', size: 44 },
]
function sortIcon(column: { getIsSorted: () => false | 'asc' | 'desc' }) {
const sorted = column.getIsSorted()
if (sorted === 'asc') {
return 'i-lucide-arrow-up'
}
if (sorted === 'desc') {
return 'i-lucide-arrow-down'
}
function sortIcon(field: string) {
const [id, direction] = props.sort.split(':')
if (id !== field) {
return undefined
}
return direction === 'asc' ? 'i-lucide-arrow-up' : 'i-lucide-arrow-down'
}
function editPath(article: Article) {
return `/article/${article.id}/edit`
@@ -143,7 +183,7 @@ function onSelect(_event: Event, row: { original: Article }) {
<div v-if="loading" aria-busy="true" class="hidden border border-default bg-default md:block">
<span role="status" class="sr-only">{{ t('Loading articles') }}</span>
<div
v-for="n in 5"
v-for="n in skeletonRows"
:key="n"
class="flex h-11 items-center gap-3 border-t border-muted px-3 first:border-t-0"
>
@@ -153,7 +193,7 @@ function onSelect(_event: Event, row: { original: Article }) {
<USkeleton class="h-3 w-20 rounded-none bg-accented" />
</div>
</div>
<div v-else class="hidden border border-default bg-default md:block">
<div v-else ref="tableRoot" class="hidden border border-default bg-default md:block">
<UTable
:data="articles"
:columns="columns"
@@ -163,13 +203,14 @@ function onSelect(_event: Event, row: { original: Article }) {
th: `px-3 ${columnWidths}`,
td: `h-11 px-3 py-0 ${columnWidths}`,
}"
v-model:sorting="sorting"
:sorting="sorting"
:sorting-options="{ manualSorting: true }"
@select="onSelect"
>
<template #caption>
<caption class="sr-only">
{{
t('Articles, sorted by last updated, newest first')
caption
}}
</caption>
</template>
@@ -178,21 +219,31 @@ function onSelect(_event: Event, row: { original: Article }) {
<button
type="button"
class="inline-flex items-center gap-1 text-highlighted"
@click.stop="column.toggleSorting()"
@click.stop="emit('sort', column.id as ArticleSortField)"
>
{{ t('Title') }}
<UIcon v-if="sortIcon(column)" :name="sortIcon(column)!" class="size-3" />
<UIcon
v-if="sortIcon(column.id)"
:name="sortIcon(column.id)!"
:data-sort-direction="props.sort.split(':')[1]"
class="size-3"
/>
</button>
</template>
<template #is_online-header="{ column }">
<template #status-header="{ column }">
<button
type="button"
class="inline-flex items-center gap-1 text-highlighted"
@click.stop="column.toggleSorting()"
@click.stop="emit('sort', column.id as ArticleSortField)"
>
{{ t('Status') }}
<UIcon v-if="sortIcon(column)" :name="sortIcon(column)!" class="size-3" />
<UIcon
v-if="sortIcon(column.id)"
:name="sortIcon(column.id)!"
:data-sort-direction="props.sort.split(':')[1]"
class="size-3"
/>
</button>
</template>
@@ -200,10 +251,15 @@ function onSelect(_event: Event, row: { original: Article }) {
<button
type="button"
class="inline-flex items-center gap-1 text-highlighted"
@click.stop="column.toggleSorting()"
@click.stop="emit('sort', column.id as ArticleSortField)"
>
{{ t('Created') }}
<UIcon v-if="sortIcon(column)" :name="sortIcon(column)!" class="size-3" />
<UIcon
v-if="sortIcon(column.id)"
:name="sortIcon(column.id)!"
:data-sort-direction="props.sort.split(':')[1]"
class="size-3"
/>
</button>
</template>
@@ -211,10 +267,15 @@ function onSelect(_event: Event, row: { original: Article }) {
<button
type="button"
class="inline-flex items-center gap-1 text-highlighted"
@click.stop="column.toggleSorting()"
@click.stop="emit('sort', column.id as ArticleSortField)"
>
{{ t('Updated') }}
<UIcon v-if="sortIcon(column)" :name="sortIcon(column)!" class="size-3" />
<UIcon
v-if="sortIcon(column.id)"
:name="sortIcon(column.id)!"
:data-sort-direction="props.sort.split(':')[1]"
class="size-3"
/>
</button>
</template>
@@ -229,7 +290,7 @@ function onSelect(_event: Event, row: { original: Article }) {
</RouterLink>
</template>
<template #is_online-cell="{ row }">
<template #status-cell="{ row }">
<ArticleStatusBadge
:online="row.original.is_online"
size="sm"
+2 -12
View File
@@ -1,9 +1,8 @@
<script setup lang="ts">
import { t } from '@/i18n'
import { computed, onMounted, onUnmounted, ref, useSlots, watch } from 'vue'
import AppLogo from '@/components/AppLogo.vue'
import LanguageChip from '@/components/LanguageChip.vue'
import { useCardHeading } from '@/composables/documentTitle'
import { isInAppNavigation } from '@/composables/useAuthShellNavigation'
const props = defineProps<{
@@ -70,16 +69,7 @@ const colorModeSelectUi = computed(() => ({
content: 'w-auto min-w-36',
}))
watch(
() => props.title,
(title) => {
if (!title) {
return
}
document.title = t('{0} · RenewCMS', [title])
},
{ immediate: true },
)
useCardHeading(() => props.title)
watch(
() => props.title,
+41
View File
@@ -0,0 +1,41 @@
<script setup lang="ts">
import { computed } from 'vue'
const props = defineProps<{
items: string[]
label: string
display?: string
warning?: boolean
}>()
const model = defineModel<string>({ required: true })
const options = computed(() => props.items.map((item) => ({ label: item, value: item })))
const borderClass = computed(() => (props.warning ? 'border-warning' : 'border-accented'))
const shown = computed(() => props.display ?? model.value)
</script>
<template>
<USelectMenu
:model-value="model"
:items="options"
value-key="value"
label-key="label"
:search-input="false"
:aria-label="label"
color="neutral"
variant="outline"
class="w-full"
:ui="{
base: `h-11 rounded-none border ${borderClass} bg-default px-2.5 text-sm ring-0 data-[state=open]:border-primary data-[state=open]:ring-1 data-[state=open]:ring-primary lg:h-8`,
trailingIcon: 'size-3.5 text-muted',
content: 'min-w-(--reka-combobox-trigger-width)',
item: 'min-h-11 text-sm lg:min-h-8',
itemLeadingIcon: 'hidden',
itemTrailingIcon: 'hidden',
}"
@update:model-value="model = $event as string"
>
<span class="truncate text-highlighted">{{ shown }}</span>
</USelectMenu>
</template>
-64
View File
@@ -1,64 +0,0 @@
<script setup lang="ts">
import { t } from '@/i18n'
import { computed, ref, watchEffect } from 'vue'
import { useCopyToClipboard } from '@/composables/useCopyToClipboard'
import { highlightToHtml, useShikiHighlighter } from '@/composables/useShikiHighlighter'
const props = defineProps<{
code: string
lang: string
label?: string
}>()
const { copied, copy } = useCopyToClipboard()
const buttonLabel = computed(() => (copied.value ? t('Copied') : t('Copy')))
const buttonIcon = computed(() => (copied.value ? 'i-lucide-check' : 'i-lucide-copy'))
const highlightedHtml = ref<string | null>(null)
watchEffect(async () => {
const highlighter = await useShikiHighlighter()
highlightedHtml.value = highlightToHtml(highlighter, props.code, props.lang)
})
function onCopy() {
copy(props.code)
}
</script>
<template>
<div class="bg-elevated">
<div class="flex h-8 items-center justify-between border-b border-default pr-1 pl-3">
<span class="font-mono text-xs leading-tight font-medium text-muted">{{
label ?? lang
}}</span>
<UButton
:icon="buttonIcon"
color="neutral"
variant="ghost"
size="xs"
:aria-label="t('Copy {0} example', [label ?? lang])"
aria-live="polite"
class="gap-1.5 px-2 font-medium text-toned"
:ui="{ leadingIcon: 'size-3.5' }"
@click="onCopy"
>
{{ buttonLabel }}
</UButton>
</div>
<div
v-if="highlightedHtml"
tabindex="0"
class="shiki-block overflow-x-auto px-3 py-3 font-mono text-code whitespace-pre"
v-html="highlightedHtml"
/>
<pre
v-else
tabindex="0"
class="overflow-x-auto px-3 py-3 font-mono text-code whitespace-pre text-default"
>{{ code }}</pre
>
</div>
</template>
+120
View File
@@ -0,0 +1,120 @@
<script setup lang="ts">
import { t } from '@/i18n'
import { computed, ref } from 'vue'
import { useCopyToClipboard } from '@/composables/useCopyToClipboard'
import type { CodeSnippetTab } from '@/lib/codeSnippet'
const props = defineProps<{
tabs: CodeSnippetTab[]
}>()
const active = defineModel<string>('active')
const { copied, copy } = useCopyToClipboard()
const tabList = ref<HTMLElement | null>(null)
const copyButton = ref<{ $el: HTMLElement } | null>(null)
const current = computed(() => props.tabs.find((tab) => tab.k === active.value) ?? props.tabs[0])
const single = computed(() => props.tabs.length === 1)
const copyLabel = computed(() => (copied.value ? t('Copied') : t('Copy')))
const copyIcon = computed(() => (copied.value ? 'i-lucide-check' : 'i-lucide-copy'))
const TAB_BASE =
'flex h-8 cursor-pointer items-center px-2.5 text-sm whitespace-nowrap focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-primary'
const TAB_SELECTED = 'font-medium text-highlighted shadow-[inset_0_-2px_0_var(--ui-primary)]'
const TAB_IDLE = 'font-normal text-toned'
function isSelected(tab: CodeSnippetTab) {
return tab.k === current.value?.k
}
function select(tab: CodeSnippetTab) {
active.value = tab.k
}
function targetIndex(key: string, from: number) {
const last = props.tabs.length - 1
const targets: Record<string, number> = {
ArrowRight: from === last ? 0 : from + 1,
ArrowLeft: from === 0 ? last : from - 1,
Home: 0,
End: last,
}
return targets[key]
}
function onTabKeydown(event: KeyboardEvent, index: number) {
const target = targetIndex(event.key, index)
if (target === undefined) {
return
}
event.preventDefault()
select(props.tabs[target]!)
const buttons = tabList.value?.querySelectorAll<HTMLElement>('[role="tab"]')
buttons?.[target]?.focus()
}
function onCopy() {
copy(current.value?.code ?? '')
}
function focusCopy() {
copyButton.value?.$el?.focus()
}
defineExpose({ focusCopy })
</script>
<template>
<div class="flex min-w-0 flex-col border border-default bg-elevated text-default">
<div class="flex min-h-11 items-center gap-2 border-b border-default pr-1 pl-2">
<div
ref="tabList"
role="tablist"
:aria-label="t('Language')"
class="flex min-w-0 flex-1 gap-0.5 overflow-x-auto"
>
<template v-if="single">
<span class="flex h-8 items-center px-2.5 text-sm font-normal text-muted">{{
current?.label
}}</span>
</template>
<template v-else>
<button
v-for="(tab, index) in tabs"
:key="tab.k"
type="button"
role="tab"
:aria-selected="isSelected(tab)"
:tabindex="isSelected(tab) ? 0 : -1"
:class="[TAB_BASE, isSelected(tab) ? TAB_SELECTED : TAB_IDLE]"
@click="select(tab)"
@keydown="onTabKeydown($event, index)"
>
{{ tab.label }}
</button>
</template>
</div>
<UButton
ref="copyButton"
:icon="copyIcon"
color="neutral"
variant="ghost"
:aria-label="t('Copy code')"
class="h-8 min-w-11 justify-center gap-1.5 rounded-none px-2.5 text-sm font-medium focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-primary"
:class="copied ? 'text-success' : 'text-highlighted'"
:ui="{ leadingIcon: 'size-3.5' }"
@click="onCopy"
>
<span aria-live="polite">{{ copyLabel }}</span>
</UButton>
</div>
<pre
tabindex="0"
class="m-0 overflow-x-auto px-4 py-3 font-mono text-code whitespace-pre text-highlighted"
>{{ current?.code }}</pre
>
</div>
</template>
+11 -5
View File
@@ -1,7 +1,8 @@
<script setup lang="ts">
import { SHEET_CONTENT_CLASS, SHEET_FOOTER_CLASS } from '@/components/sheetClasses'
import { t, translate } from '@/i18n'
import { computed, nextTick, onMounted, ref, watch } from 'vue'
import { computed, nextTick, onMounted, ref, useSlots, watch } from 'vue'
import MediaThumb from '@/components/MediaThumb.vue'
const props = withDefaults(
@@ -23,6 +24,8 @@ const props = withDefaults(
const emit = defineEmits<{ close: [confirmed: boolean] }>()
const slots = useSlots()
const open = defineModel<boolean>('open', { default: true })
const pending = ref(false)
const error = ref('')
@@ -39,6 +42,10 @@ const previewThumb = computed(() => ({
content_type: '',
sha256: '',
}))
const hasBody = computed(() => Boolean(error.value || props.preview || slots.body))
const bodyClass = computed(() =>
hasBody.value ? 'px-6 pt-5 pb-0 sm:px-6 sm:pt-5 sm:pb-0' : 'p-0 sm:p-0',
)
const confirmColor = computed(() => (props.tone === 'danger' ? 'error' : 'primary'))
const confirmText = computed(() => (pending.value ? props.pendingLabel : props.confirmLabel))
@@ -108,13 +115,12 @@ function onCancel() {
'aria-busy': pending ? 'true' : undefined,
}"
:ui="{
content:
'divide-y-0 shadow-(--shadow-modal) ring-0 sm:top-35 sm:max-w-115 sm:translate-y-0 max-sm:!inset-x-4 max-sm:!top-auto max-sm:!bottom-4 max-sm:!left-4 max-sm:!w-auto max-sm:!max-w-none max-sm:!translate-x-0 max-sm:!translate-y-0',
content: `${SHEET_CONTENT_CLASS} sm:top-35 sm:max-w-115`,
header: 'min-h-0 px-6 pt-5 pb-0 sm:px-6',
title: 'text-lg/6 font-semibold',
description: 'mt-1 text-sm text-muted text-pretty',
body: 'px-6 pt-5 pb-0 sm:px-6 sm:pt-5 sm:pb-0',
footer: 'px-6 py-5 sm:px-6',
body: bodyClass,
footer: SHEET_FOOTER_CLASS,
}"
>
<template #body>
+7 -3
View File
@@ -161,6 +161,9 @@ const sidebarCollapsed = useSidebarCollapsed()
const sidebarUi = computed(() => ({
root: sidebarCollapsed.value ? 'min-w-14 px-1 py-3' : 'min-w-14 p-3',
content: 'w-75 gap-0.5 divide-y-0 p-3 shadow-modal',
overlay: 'bg-(--rc-overlay)',
toggle: 'hidden',
header: 'mb-3 h-10 gap-2.5 px-1.5',
body: 'gap-0.5 p-0',
footer: 'p-0',
@@ -170,12 +173,13 @@ const navUi = computed(() => ({
list: 'flex flex-col gap-0.5',
link: sidebarCollapsed.value
? 'h-8 justify-center gap-0 px-0 text-sm'
: 'h-8 gap-2.5 px-2.5 py-0 text-sm [li[data-state=open]>&]:font-medium [li[data-state=open]>&]:text-highlighted',
: 'h-8 gap-2.5 px-2.5 py-0 text-sm max-lg:h-11 [li[data-state=open]>&:not([aria-current=page])]:font-medium [li[data-state=open]>&:not([aria-current=page])]:text-highlighted',
linkLeadingIcon: 'size-4',
linkTrailingIcon: 'size-3.5 group-data-[state=open]:rotate-90',
label: 'px-2.5 pt-1.5 pb-0.5 pl-3 text-[11px] leading-4 font-semibold tracking-[.04em] text-muted uppercase',
childList: 'ms-[19px] gap-0.5 border-s border-default ps-0',
childLink: 'h-8 gap-2.5 py-0 pr-2.5 pl-3 text-sm',
childList: 'ms-[19px] mt-0.5 flex flex-col gap-0.5 border-s border-default ps-0',
childItem: 'ms-0 ps-0',
childLink: 'h-8 max-lg:h-11 gap-2.5 py-0 pr-2.5 pl-3 text-sm',
childLinkIcon: 'size-3.5',
}))
const loggingOut = ref(false)
+8 -57
View File
@@ -3,13 +3,8 @@ import { t, translate } from '@/i18n'
import { computed, ref } from 'vue'
import ApiFieldTable from '@/components/ApiFieldTable.vue'
import CodeBlock from '@/components/CodeBlock.vue'
import {
RATE_LIMIT_SENTENCE,
NO_CONTENT_RESPONSE,
endpointExamples,
type ApiEndpoint,
} from '@/data/apiCatalogue'
import CodeSnippet from '@/components/CodeSnippet.vue'
import { RATE_LIMIT_SENTENCE, endpointExamples, type ApiEndpoint } from '@/data/apiCatalogue'
import { CHIP_CLASS, METHOD_CLASS, endpointAnchor } from '@/lib/apiReference'
const props = defineProps<{
@@ -30,23 +25,12 @@ const bodyTitle = computed(() => {
}
return props.endpoint.bodyKind === 'json' ? t('Request body · JSON') : t('Request body')
})
const responseLabel = computed(() =>
props.endpoint.response === NO_CONTENT_RESPONSE ? 'HTTP' : 'JSON',
)
const responseLang = computed(() =>
props.endpoint.response === NO_CONTENT_RESPONSE ? 'text' : 'json',
)
const tabItems = [
{ label: 'fetch', value: 'fetch' },
{ label: 'curl', value: 'curl' },
{
get label() {
return t('Response')
},
value: 'response',
},
]
const snippetTabs = computed(() => [
{ k: 'fetch', label: 'fetch', code: examples.value.fetch },
{ k: 'curl', label: 'curl', code: examples.value.curl },
{ k: 'response', label: t('Response'), code: examples.value.response },
])
</script>
<template>
@@ -119,40 +103,7 @@ const tabItems = [
<span v-else class="text-muted">{{ t('No request body.') }}</span>
</div>
<UTabs
v-model="activeTab"
:items="tabItems"
variant="link"
color="primary"
:ui="{
root: 'gap-0 border border-default',
list: 'gap-4 border-b border-default px-3 py-0 before:hidden',
trigger:
'h-9 grow-0 px-0 text-sm font-medium data-[state=inactive]:font-medium data-[state=inactive]:text-toned max-lg:h-11',
content: 'mt-0',
}"
>
<template #content="{ item }">
<CodeBlock
v-if="item.value === 'fetch'"
label="JavaScript"
lang="javascript"
:code="examples.fetch"
/>
<CodeBlock
v-else-if="item.value === 'curl'"
label="Shell"
lang="shell"
:code="examples.curl"
/>
<CodeBlock
v-else
:label="responseLabel"
:lang="responseLang"
:code="examples.response"
/>
</template>
</UTabs>
<CodeSnippet v-model:active="activeTab" :tabs="snippetTabs" />
<div v-if="endpoint.rateLimited" class="flex gap-2.5 text-toned">
<UIcon name="i-lucide-info" class="mt-0.5 size-4 shrink-0 text-info" />
+3 -2
View File
@@ -1,4 +1,5 @@
<script setup lang="ts">
import { SHEET_CONTENT_CLASS, SHEET_FOOTER_CLASS } from '@/components/sheetClasses'
import { t } from '@/i18n'
import { computed, nextTick, onUnmounted, ref, watch } from 'vue'
@@ -197,7 +198,7 @@ const modalDescription = computed(() => {
const modalContentClass = computed(
() =>
`divide-y-0 shadow-(--shadow-modal) ring-0 sm:translate-y-0 max-sm:!inset-x-4 max-sm:!top-auto max-sm:!bottom-4 max-sm:!left-4 max-sm:!w-auto max-sm:!max-w-none max-sm:!translate-x-0 max-sm:!translate-y-0 ${
`${SHEET_CONTENT_CLASS} ${
showTabs.value ? 'sm:top-10' : 'sm:top-35'
} ${wideModal.value ? 'sm:max-w-160' : 'sm:max-w-120'}`,
)
@@ -765,7 +766,7 @@ onUnmounted(() => {
close: 'top-5 end-6',
title: 'text-lg/6 font-semibold',
body: 'p-0 sm:p-0',
footer: 'px-6 py-5 sm:px-6',
footer: SHEET_FOOTER_CLASS,
}"
>
<template #body>
+412
View File
@@ -0,0 +1,412 @@
<script setup lang="ts">
import { t } from '@/i18n'
import { computed, onBeforeUnmount, onMounted, ref } from 'vue'
import BuilderSelect from '@/components/BuilderSelect.vue'
import CodeSnippet from '@/components/CodeSnippet.vue'
import CodeText from '@/components/CodeText.vue'
import { SECTION_TITLE } from '@/lib/apiReference'
import { useCanManageVariants } from '@/composables/useCanManageVariants'
import {
SAMPLE_IMAGE,
SETTINGS_VARIANTS_PATH,
imageResponseRows,
imageSnippets,
unknownVariantBody,
variantUrl,
} from '@/lib/imageSnippets'
import { formatDimensions, formatLabel } from '@/lib/variants/variantFormat'
import { useImageVariantsStore } from '@/stores/imageVariants'
const props = defineProps<{
origin: string
}>()
const MAX_ROWS_BEFORE_SCROLL = 6
const DEFAULT_RATIO = '4 / 3'
const store = useImageVariantsStore()
const canManage = useCanManageVariants()
const chosen = ref<string | null>(null)
const tab = ref<string>()
const urlTab = ref<string>()
const enabled = computed(() => store.items.filter((item) => item.enabled))
const enabledNames = computed(() => enabled.value.map((item) => item.name))
const hasDisabled = computed(() => store.items.some((item) => !item.enabled))
const view = computed(() => {
if (!canManage.value || store.loadState === 'forbidden') {
return 'plain'
}
if (store.loadState === 'loading') {
return 'loading'
}
if (store.loadState === 'error') {
return 'error'
}
return enabled.value.length === 0 ? 'none' : 'many'
})
const showSnippets = computed(() => view.value !== 'loading')
const showBuilder = computed(() => view.value === 'many')
const showResponses = computed(() => view.value !== 'loading' && view.value !== 'error')
const snippetNames = computed(() => (view.value === 'many' ? enabledNames.value : []))
const snippets = computed(() => imageSnippets(props.origin, snippetNames.value))
const activeTab = computed(() => tab.value ?? (view.value === 'many' ? 'html' : 'curl'))
const selected = computed(() => chosen.value ?? enabledNames.value[0] ?? '')
const removed = computed(() => showBuilder.value && !enabledNames.value.includes(selected.value))
const selectedVariant = computed(() => enabled.value.find((item) => item.name === selected.value))
const variantDisplay = computed(() =>
removed.value ? t('{0} (removed)', [selected.value]) : selected.value,
)
const urlTabs = computed(() => [
{ k: 'url', label: t('URL'), code: variantUrl(props.origin, selected.value) },
])
const previewLabel = computed(() => {
const variant = selectedVariant.value
if (!variant) {
return t('No preview: unknown variant')
}
return [
variant.name,
formatDimensions(variant.width, variant.height),
formatLabel(variant.format),
].join(' · ')
})
const previewRatio = computed(() => {
const variant = selectedVariant.value
if (!variant || variant.width === null || variant.height === null) {
return DEFAULT_RATIO
}
return `${variant.width} / ${variant.height}`
})
const countText = computed(() =>
enabled.value.length === 1
? t('1 enabled variant')
: t('{0} enabled variants', [enabled.value.length]),
)
const rows = computed(() =>
enabled.value.map((item) => ({
name: item.name,
dimensions: formatDimensions(item.width, item.height),
format: formatLabel(item.format),
url: variantUrl('', item.name),
})),
)
const scrollBody = computed(() => rows.value.length > MAX_ROWS_BEFORE_SCROLL)
const responseRows = computed(() => imageResponseRows())
const removedTitle = computed(() => t('The variant "{0}" no longer exists', [selected.value]))
const removedDescription = computed(() =>
t(
'There is no fallback to the original. Requests with ?v={0} return status 400 with the body `{1}`. Remove the parameter to get the original image, or pick another variant.',
[selected.value, unknownVariantBody(selected.value)],
),
)
function loadList() {
return store.load()
}
function reloadOnFocus() {
if (!canManage.value) {
return
}
if (store.loadState === 'ready') {
return store.reloadQuietly()
}
return store.load()
}
onMounted(() => {
if (canManage.value) {
store.load()
}
window.addEventListener('focus', reloadOnFocus)
})
onBeforeUnmount(() => window.removeEventListener('focus', reloadOnFocus))
const SUB_HEADING = 'text-base/5.5 font-semibold text-highlighted'
const FIELD_LABEL = 'font-medium text-highlighted'
const TABLE_BOX = 'border border-default bg-default overflow-x-auto'
const VARIANT_COLUMNS = 'grid grid-cols-[96px_112px_72px_minmax(0,1fr)] items-center gap-3 px-3'
const RESPONSE_COLUMNS = 'grid grid-cols-[minmax(0,1.3fr)_56px_minmax(0,1fr)] gap-3 px-3'
const EMPTY_UI = {
root: 'gap-3 border border-default bg-default px-6 py-8',
header: 'max-w-none gap-3',
body: 'w-full max-w-none items-center gap-3',
avatar: 'mb-0 size-11 rounded-none bg-elevated text-toned',
title: 'text-md font-semibold',
description: 'max-w-105 text-pretty text-muted',
actions: 'w-full flex-col items-center justify-center gap-3',
}
</script>
<template>
<section
data-anchor="images"
aria-labelledby="h-images"
class="flex max-w-220 scroll-mt-16 flex-col gap-5 lg:scroll-mt-8 lg:gap-6"
>
<div class="flex flex-col gap-2">
<h2 id="h-images" :class="SECTION_TITLE">
{{ t('Images and variants') }}
</h2>
<p class="max-w-180 text-pretty text-toned">
<CodeText
:text="
t(
'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.',
)
"
/>
</p>
</div>
<section
v-if="view === 'loading'"
:aria-label="t('Loading image variants')"
aria-busy="true"
class="flex flex-col gap-3"
>
<USkeleton class="h-35 rounded-none bg-accented" />
<USkeleton class="h-50 rounded-none bg-accented" />
<USkeleton class="h-30 rounded-none bg-accented" />
</section>
<UAlert
v-if="view === 'error'"
role="alert"
color="error"
variant="soft"
orientation="vertical"
:close="false"
icon="i-lucide-circle-x"
:title="t('Couldn\'t load image variants')"
:description="
t(
'The snippets below still work. The variant list and the URL builder need a connection.',
)
"
:ui="{ actions: 'mt-2' }"
>
<template #actions>
<UButton
color="neutral"
variant="outline"
class="h-11 gap-1.5 rounded-none border border-accented bg-default px-3 text-sm font-medium text-highlighted ring-0 lg:h-8"
@click="loadList"
>
{{ t('Try again') }}
</UButton>
</template>
</UAlert>
<div v-if="showSnippets" class="flex flex-col gap-2">
<h3 :class="SUB_HEADING">{{ t('Request an image') }}</h3>
<CodeSnippet :active="activeTab" :tabs="snippets" @update:active="tab = $event" />
</div>
<UEmpty
v-if="view === 'none'"
variant="naked"
icon="i-lucide-layers"
:title="t('No image variants yet')"
:description="
t(
'Until you add a variant, any request with the ?v= parameter returns status 400 unknown_variant. Requests without it return the original image.',
)
"
:ui="EMPTY_UI"
>
<template #actions>
<UButton :to="SETTINGS_VARIANTS_PATH" class="h-11 px-4 lg:h-8">
{{ t('Go to image variants') }}
</UButton>
</template>
</UEmpty>
<UEmpty
v-if="view === 'plain'"
variant="naked"
icon="i-lucide-layers"
:title="t('No image variants yet')"
:description="
t(
'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.',
)
"
:ui="EMPTY_UI"
/>
<template v-if="showBuilder">
<div class="flex flex-col gap-2">
<div class="flex flex-wrap items-baseline gap-3">
<h3 :class="SUB_HEADING">{{ t('Variants') }}</h3>
<span class="text-muted">{{ countText }}</span>
</div>
<div :class="TABLE_BOX">
<div role="table" :aria-label="t('Variants')" class="min-w-130">
<div role="rowgroup">
<div
role="row"
:class="[VARIANT_COLUMNS, 'h-9 bg-elevated font-medium text-muted']"
>
<span role="columnheader">{{ t('Name') }}</span>
<span role="columnheader">{{ t('Dimensions') }}</span>
<span role="columnheader">{{ t('Format') }}</span>
<span role="columnheader">{{ t('Example URL') }}</span>
</div>
</div>
<div
role="rowgroup"
class="overflow-y-auto"
:class="scrollBody ? 'max-h-66' : ''"
>
<div
v-for="row in rows"
:key="row.name"
role="row"
:class="[
VARIANT_COLUMNS,
'min-h-10 border-t border-default',
row.name === selected ? 'bg-elevated' : 'bg-default',
]"
>
<span
role="cell"
class="font-mono text-xs/5 font-medium text-highlighted"
>{{ row.name }}</span
>
<span role="cell" class="text-toned">{{ row.dimensions }}</span>
<span role="cell" class="text-toned">{{ row.format }}</span>
<span role="cell" class="truncate font-mono text-xs/5 text-toned">{{
row.url
}}</span>
</div>
</div>
</div>
</div>
<span v-if="hasDisabled" class="text-muted">{{
t(
'Disabled variants are not served. A request for one returns 400 "Unknown variant".',
)
}}</span>
</div>
<div class="flex flex-col gap-2">
<h3 :class="SUB_HEADING">{{ t('URL builder') }}</h3>
<div
class="grid items-start gap-4 border border-default bg-default p-4 lg:grid-cols-2 lg:p-5"
>
<div class="flex min-w-0 flex-col gap-3">
<div class="flex flex-col gap-1.5">
<span :class="FIELD_LABEL">{{ t('Image') }}</span>
<BuilderSelect
:model-value="SAMPLE_IMAGE"
:items="[SAMPLE_IMAGE]"
:label="t('Image')"
/>
</div>
<div class="flex flex-col gap-1.5">
<span :class="FIELD_LABEL">{{ t('Variant') }}</span>
<BuilderSelect
:model-value="selected"
:items="enabledNames"
:label="t('Variant')"
:display="variantDisplay"
:warning="removed"
@update:model-value="chosen = $event"
/>
</div>
<div class="flex flex-col gap-1.5">
<span :class="FIELD_LABEL">{{ t('URL') }}</span>
<CodeSnippet v-model:active="urlTab" :tabs="urlTabs" />
</div>
<UAlert
v-if="removed"
role="alert"
color="warning"
variant="soft"
:close="false"
icon="i-lucide-triangle-alert"
:title="removedTitle"
:ui="{
root: 'gap-2.5 px-3.5 py-3',
description: 'text-toned text-pretty',
}"
>
<template #description>
<CodeText :text="removedDescription" />
</template>
</UAlert>
</div>
<div class="flex min-w-0 flex-col gap-1.5">
<span :class="FIELD_LABEL">{{ t('Preview') }}</span>
<div
role="img"
:aria-label="previewLabel"
class="image-placeholder flex max-h-60 w-full items-center justify-center border border-default text-toned"
:class="removed ? 'opacity-50' : ''"
:style="{ aspectRatio: previewRatio }"
>
<span
class="border border-default bg-default px-2 py-1 font-mono text-xs font-medium"
>{{ previewLabel }}</span
>
</div>
</div>
</div>
</div>
</template>
<div v-if="showResponses" class="flex flex-col gap-2">
<h3 :class="SUB_HEADING">{{ t('Responses') }}</h3>
<div :class="TABLE_BOX">
<div role="table" :aria-label="t('Responses')" class="min-w-140">
<div role="rowgroup" class="sr-only">
<div role="row">
<span role="columnheader">{{ t('Request') }}</span>
<span role="columnheader">{{ t('Status') }}</span>
<span role="columnheader">{{ t('Response') }}</span>
</div>
</div>
<div role="rowgroup">
<div
v-for="(row, index) in responseRows"
:key="row.request"
role="row"
:class="[
RESPONSE_COLUMNS,
'min-h-10 items-center py-1.5',
index > 0 ? 'border-t border-default' : '',
]"
>
<span role="cell" class="font-mono text-xs/5 text-highlighted">{{
row.request
}}</span>
<span
role="cell"
class="font-mono text-xs/5 font-medium text-highlighted"
>{{ row.status }}</span
>
<span role="cell" class="flex min-w-0 flex-col gap-0.5 text-toned">
{{ row.response }}
<span
v-if="row.body"
class="font-mono text-xs/4.5 wrap-anywhere text-muted"
>{{ row.body }}</span
>
</span>
</div>
</div>
</div>
</div>
</div>
</section>
</template>
+275
View File
@@ -0,0 +1,275 @@
<script setup lang="ts">
import { t } from '@/i18n'
import type { MessageKey } from '@/i18n/messages'
import { computed, nextTick, ref, useId, watch } from 'vue'
import { useMediaQuery } from '@vueuse/core'
import { normalizeLinkUrl } from '@/lib/articleLinkUrl'
const SHEET_QUERY = '(max-width: 39.999rem)'
const TEXT_PLACEHOLDER = 'What the reader sees'
const URL_PLACEHOLDER = 'https://example.com, /page, mailto: or #anchor'
const DIALOG_CONTENT_CLASS =
'divide-y-0 shadow-(--shadow-modal) ring-0 sm:top-35 sm:max-w-115 sm:translate-y-0'
const SHEET_CONTENT_CLASS =
'divide-y-0 shadow-(--shadow-modal) ring-0 !inset-x-0 !top-auto !bottom-0 !left-0 !w-auto !max-w-none !translate-x-0 !translate-y-0 before:absolute before:top-2 before:left-1/2 before:h-1 before:w-9 before:-translate-x-1/2 before:bg-accented'
export interface LinkModalSubmit {
text: string
href: string
newTab: boolean
}
const props = defineProps<{
mode: 'insert' | 'edit'
text: string
href: string
newTab: boolean
}>()
const emit = defineEmits<{
submit: [value: LinkModalSubmit]
remove: []
}>()
const open = defineModel<boolean>('open', { default: false })
const isSheet = useMediaQuery(SHEET_QUERY)
const textId = useId()
const urlId = useId()
const formId = useId()
const textValue = ref('')
const urlValue = ref('')
const newTabValue = ref(false)
const textError = ref<MessageKey | ''>('')
const urlError = ref<MessageKey | ''>('')
const focusedField = ref<'text' | 'url' | ''>('')
const editing = computed(() => props.mode === 'edit')
const title = computed(() => (editing.value ? t('Edit link') : t('Insert link')))
const confirmLabel = computed(() => (editing.value ? t('Save link') : t('Insert link')))
const presentation = computed(() => (isSheet.value ? 'sheet' : 'dialog'))
const modalUi = computed(() => ({
content: isSheet.value ? SHEET_CONTENT_CLASS : DIALOG_CONTENT_CLASS,
header: isSheet.value
? 'items-start gap-3 px-6 pt-7.5 pb-0 sm:px-6'
: 'items-start gap-3 px-6 pt-5 pb-0 sm:px-6',
wrapper: isSheet.value ? 'pe-10 max-sm:pe-18' : 'pe-10',
close: isSheet.value ? 'end-8 top-9 size-11' : '',
title: 'text-lg/6 font-semibold',
description: 'text-sm text-muted text-pretty',
body: 'px-6 pt-5 pb-0 sm:px-6 sm:pt-5 sm:pb-0',
footer: 'px-6 py-5 sm:px-6',
}))
const modalContent = computed(() => ({
'data-presentation': presentation.value,
onOpenAutoFocus: (event: Event) => {
event.preventDefault()
focusInitialField()
},
onCloseAutoFocus: (event: Event) => event.preventDefault(),
}))
function focusField(id: string) {
document.getElementById(id)?.focus()
}
async function focusInitialField() {
await nextTick()
focusField(props.text === '' ? textId : urlId)
}
watch(
open,
(isOpen) => {
if (!isOpen) {
return
}
textValue.value = props.text
urlValue.value = props.href
newTabValue.value = props.newTab
textError.value = ''
urlError.value = ''
focusedField.value = ''
},
{ immediate: true },
)
function validateText() {
textError.value = textValue.value.trim() === '' ? 'Enter the link text.' : ''
}
function resolveHref() {
const keptAsStored =
props.mode === 'edit' &&
props.href.trim() !== '' &&
urlValue.value.trim() === props.href.trim()
return keptAsStored ? urlValue.value.trim() : normalizeLinkUrl(urlValue.value)
}
function validateUrl() {
urlError.value =
resolveHref() === null ? 'Enter a valid URL. Use http(s), mailto, a path or #anchor.' : ''
}
function onUrlBlur() {
focusedField.value = ''
if (urlValue.value.trim() !== '') {
validateUrl()
}
}
function onSubmit() {
validateText()
validateUrl()
if (textError.value) {
focusField(textId)
return
}
if (urlError.value) {
focusField(urlId)
return
}
emit('submit', {
text: textValue.value.trim(),
href: resolveHref() ?? '',
newTab: newTabValue.value,
})
}
function onRemove() {
emit('remove')
}
function onCancel() {
open.value = false
}
</script>
<template>
<UModal
v-model:open="open"
:title="title"
:description="t('Links open in the same tab unless you turn on a new tab.')"
:content="modalContent"
:ui="modalUi"
>
<template #body>
<UForm
:id="formId"
:loading-auto="false"
:state="{ text: textValue, url: urlValue }"
class="flex flex-col gap-4"
@submit="onSubmit"
>
<UFormField
:label="t('Link text')"
name="text"
:error="textError ? t(textError) : undefined"
@focusin="focusedField = 'text'"
@focusout="focusedField = ''"
>
<template v-if="textError" #error="{ error }">
<span class="flex items-center gap-1.5">
<UIcon
name="i-lucide-circle-alert"
class="size-3.5 shrink-0 text-error"
/>
{{ error }}
</span>
</template>
<UInput
:id="textId"
v-model="textValue"
:placeholder="t(TEXT_PLACEHOLDER)"
color="primary"
autocomplete="off"
:highlight="focusedField === 'text' || !!textError"
:aria-invalid="textError ? 'true' : undefined"
:ui="{ base: 'h-11 text-base md:h-10' }"
class="w-full"
/>
</UFormField>
<UFormField
:label="t('URL')"
name="url"
:error="urlError ? t(urlError) : undefined"
@focusin="focusedField = 'url'"
@focusout="onUrlBlur"
>
<template v-if="urlError" #error="{ error }">
<span class="flex items-center gap-1.5">
<UIcon
name="i-lucide-circle-alert"
class="size-3.5 shrink-0 text-error"
/>
{{ error }}
</span>
</template>
<UInput
:id="urlId"
v-model="urlValue"
:placeholder="t(URL_PLACEHOLDER)"
:title="urlValue"
color="primary"
autocomplete="off"
spellcheck="false"
:highlight="focusedField === 'url' || !!urlError"
:aria-invalid="urlError ? 'true' : undefined"
:ui="{ root: 'min-w-0', base: 'h-11 text-base md:h-10' }"
class="w-full min-w-0"
/>
</UFormField>
<USwitch
v-model="newTabValue"
:label="t('Open in new tab')"
:ui="{
root: 'min-h-11 items-center gap-3 md:min-h-10',
container: 'h-auto',
base: 'h-4.5 w-8 p-0.5',
thumb: 'size-3.5 bg-default data-[state=checked]:translate-x-2.5',
wrapper: 'ms-0',
label: 'text-base font-medium text-highlighted',
}"
/>
<UButton
v-if="editing"
color="error"
variant="link"
icon="i-lucide-unlink"
class="min-h-11 self-start px-0 md:min-h-10"
@click="onRemove"
>
{{ t('Remove link') }}
</UButton>
</UForm>
</template>
<template #footer>
<div
class="flex w-full gap-2"
:class="isSheet ? 'flex-col-reverse' : 'flex-row justify-end'"
>
<UButton
color="neutral"
variant="outline"
:block="isSheet"
:ui="{ base: 'h-11 justify-center md:h-8' }"
@click="onCancel"
>
{{ t('Cancel') }}
</UButton>
<UButton
type="submit"
:form="formId"
:block="isSheet"
:ui="{ base: 'h-11 justify-center md:h-8' }"
>
{{ confirmLabel }}
</UButton>
</div>
</template>
</UModal>
</template>
+168
View File
@@ -0,0 +1,168 @@
<script setup lang="ts">
import { t } from '@/i18n'
import { useMediaQuery } from '@vueuse/core'
const COARSE_POINTER_QUERY = '(pointer: coarse)'
const ACTION_CLASS = 'h-8 gap-1.5 px-2.5 text-sm font-normal'
const ROW_CLASS = 'h-12 justify-start gap-3 px-4 text-md font-normal'
defineProps<{
href: string
text: string
reference: HTMLElement | null
}>()
const emit = defineEmits<{
edit: []
'open-link': []
remove: []
}>()
const open = defineModel<boolean>('open', { default: false })
const isTouch = useMediaQuery(COARSE_POINTER_QUERY)
const popoverContent = {
side: 'bottom' as const,
align: 'start' as const,
sideOffset: 8,
onOpenAutoFocus: (event: Event) => event.preventDefault(),
onCloseAutoFocus: (event: Event) => event.preventDefault(),
}
const sheetContent = {
onOpenAutoFocus: (event: Event) => {
event.preventDefault()
const container = event.currentTarget as HTMLElement | null
container?.focus()
},
onCloseAutoFocus: (event: Event) => event.preventDefault(),
}
function choose(action: 'edit' | 'openLink' | 'remove') {
open.value = false
if (action === 'edit') {
emit('edit')
} else if (action === 'openLink') {
emit('open-link')
} else {
emit('remove')
}
}
</script>
<template>
<USlideover
v-if="isTouch"
v-model:open="open"
side="bottom"
:title="text"
:description="href"
:close="false"
:content="sheetContent"
:ui="{
content: 'max-h-none',
body: 'p-0 sm:p-0',
header: 'sr-only',
}"
>
<template #body>
<div role="dialog" :aria-label="t('Link')">
<div class="mx-auto mt-2 h-1 w-9 bg-accented" aria-hidden="true" />
<div class="flex flex-col gap-0.5 border-b border-default px-4 pt-3 pb-3">
<span class="text-lg/6 font-semibold text-highlighted">{{ text }}</span>
<span class="truncate font-mono text-xs/4.5 text-toned">{{ href }}</span>
</div>
<div class="flex flex-col pt-2 pb-4">
<UButton
color="neutral"
variant="ghost"
block
icon="i-lucide-pencil"
:class="[ROW_CLASS, 'text-highlighted']"
:ui="{ leadingIcon: 'size-4.5' }"
@click="choose('edit')"
>
{{ t('Edit link') }}
</UButton>
<UButton
color="neutral"
variant="ghost"
block
icon="i-lucide-external-link"
:class="[ROW_CLASS, 'text-highlighted']"
:ui="{ leadingIcon: 'size-4.5' }"
@click="choose('openLink')"
>
{{ t('Open link') }}
</UButton>
<UButton
color="error"
variant="ghost"
block
icon="i-lucide-unlink"
:class="ROW_CLASS"
:ui="{ leadingIcon: 'size-4.5' }"
@click="choose('remove')"
>
{{ t('Remove link') }}
</UButton>
</div>
</div>
</template>
</USlideover>
<UPopover
v-else
v-model:open="open"
:reference="reference ?? undefined"
:content="popoverContent"
:ui="{
content:
'w-72 rounded-none bg-default shadow-(--rc-shadow-pop) ring-0 border border-default',
}"
>
<template #content>
<div role="dialog" :aria-label="t('Link')" class="flex flex-col text-sm text-default">
<div
class="flex items-center gap-2 border-b border-default px-3 py-2 font-mono text-xs/4.5 text-toned"
>
<UIcon name="i-lucide-link" class="size-3.5 shrink-0" />
<span class="min-w-0 flex-1 truncate" :title="href">{{ href }}</span>
</div>
<div class="flex gap-0.5 p-1">
<UButton
color="neutral"
variant="ghost"
icon="i-lucide-pencil"
:class="[ACTION_CLASS, 'text-highlighted']"
:ui="{ leadingIcon: 'size-3.5' }"
@click="choose('edit')"
>
{{ t('Edit') }}
</UButton>
<UButton
color="neutral"
variant="ghost"
icon="i-lucide-external-link"
:class="[ACTION_CLASS, 'text-highlighted']"
:ui="{ leadingIcon: 'size-3.5' }"
@click="choose('openLink')"
>
{{ t('Open') }}
</UButton>
<UButton
color="error"
variant="ghost"
icon="i-lucide-unlink"
:class="ACTION_CLASS"
:ui="{ leadingIcon: 'size-3.5' }"
@click="choose('remove')"
>
{{ t('Remove') }}
</UButton>
</div>
</div>
</template>
</UPopover>
</template>
+17
View File
@@ -0,0 +1,17 @@
import { describe, expect, it } from 'vitest'
import { mount } from '@vue/test-utils'
import uiPlugin from '@nuxt/ui/vue-plugin'
import router from '@/router'
import MediaLinksCard from './MediaLinksCard.vue'
describe('MediaLinksCard', () => {
it('links to the variants and cache pages', () => {
const wrapper = mount(MediaLinksCard, { global: { plugins: [router, uiPlugin] } })
const hrefs = wrapper.findAll('a').map((link) => link.attributes('href'))
expect(hrefs).toEqual(['/settings/media/variants', '/settings/media/cache'])
expect(wrapper.text()).toContain('Manage image variants')
expect(wrapper.text()).toContain('Generated images and disk space')
})
})
+52
View File
@@ -0,0 +1,52 @@
<script setup lang="ts">
import { t } from '@/i18n'
import { computed } from 'vue'
const links = computed(() => [
{
to: '/settings/media/variants',
icon: 'i-lucide-layers',
label: t('Manage image variants'),
hint: t('Named sizes requested with ?v='),
},
{
to: '/settings/media/cache',
icon: 'i-lucide-database',
label: t('Cache usage'),
hint: t('Generated images and disk space'),
},
])
</script>
<template>
<section
aria-labelledby="media-links-h"
data-testid="media-links-card"
class="flex flex-col gap-3 border border-default bg-default p-4 lg:p-5"
>
<div class="flex flex-col gap-0.5">
<h2 id="media-links-h" class="text-[0.9375rem]/6 font-semibold text-highlighted">
{{ t('Media') }}
</h2>
<p class="text-pretty text-muted">
{{ t('Image sizes, cache and cleanup for your media library.') }}
</p>
</div>
<div class="flex flex-col">
<RouterLink
v-for="link in links"
:key="link.to"
:to="link.to"
class="flex min-h-11 items-center gap-3 border-t border-default py-2 text-highlighted focus-visible:outline-2 focus-visible:outline-primary"
>
<UIcon :name="link.icon" class="size-4 shrink-0" />
<span class="flex min-w-0 flex-1 flex-col">
<span class="font-medium">{{ link.label }}</span>
<span class="text-muted">{{ link.hint }}</span>
</span>
<UIcon name="i-lucide-chevron-right" class="size-3.5 shrink-0" />
</RouterLink>
</div>
</section>
</template>
+2 -1
View File
@@ -51,7 +51,7 @@ function onJump(id: string) {
</nav>
<div
class="sticky -top-5 z-5 order-first -mx-4 -mt-5 mb-5 border-b border-default bg-default px-4 py-2 lg:hidden"
class="sticky -top-4 z-5 order-first -mx-4 -mt-4 mb-4 border-b border-default bg-default px-4 py-2 lg:hidden"
>
<USelectMenu
:model-value="active"
@@ -64,6 +64,7 @@ function onJump(id: string) {
color="neutral"
variant="outline"
class="w-full"
:content="{ sideOffset: 4 }"
:ui="{
base: 'h-11 rounded-none border border-accented bg-default px-3 text-base ring-0 hover:bg-default',
trailingIcon: 'size-4 text-muted',
+1 -1
View File
@@ -147,7 +147,7 @@ const items = computed(() => [
:aria-expanded="chipExpanded"
:class="chipClass"
:trailing-icon="collapsed ? undefined : 'i-lucide-chevrons-up-down'"
:ui="{ trailingIcon: 'ms-auto size-3.5 text-current' }"
:ui="{ trailingIcon: 'ms-auto size-3.5 text-current max-lg:hidden' }"
:aria-label="triggerAriaLabel"
>
<template #leading>
File diff suppressed because it is too large. Load diff
+8 -22
View File
@@ -8,10 +8,7 @@ beforeEach(() => {
resetAuthShellNavigation()
})
function mountShell(
props: Record<string, unknown>,
slots: Record<string, unknown> = {},
) {
function mountShell(props: Record<string, unknown>, slots: Record<string, unknown> = {}) {
return mount(AuthShell, {
props,
slots,
@@ -21,36 +18,29 @@ function mountShell(
})
}
describe('AuthShell renders its title as the page heading and sets the document title', () => {
it('renders an h1 containing the title and sets document.title', () => {
describe('AuthShell renders its title as the page heading', () => {
it('renders an h1 containing the title', () => {
const wrapper = mountShell({ title: 'Log in' })
const heading = wrapper.find('h1')
expect(heading.text()).toBe('Log in')
expect(heading.attributes('tabindex')).toBe('-1')
expect(document.title).toBe('Log in · RenewCMS')
})
})
describe('AuthShell with an empty title renders no heading and leaves document.title untouched', () => {
it('mounts directly with an empty title without rendering an h1 or touching document.title', () => {
document.title = 'Existing title · RenewCMS'
describe('AuthShell with an empty title renders no heading', () => {
it('mounts with an empty title without rendering an h1', () => {
const wrapper = mountShell({ title: '' })
expect(wrapper.find('h1').exists()).toBe(false)
expect(document.title).toBe('Existing title · RenewCMS')
})
it('leaves document.title untouched and does not crash when the title changes to empty', async () => {
it('removes the heading when the title changes to empty', async () => {
const wrapper = mountShell({ title: 'Create the owner account' })
expect(document.title).toBe('Create the owner account · RenewCMS')
await wrapper.setProps({ title: '' })
expect(wrapper.find('h1').exists()).toBe(false)
expect(document.title).toBe('Create the owner account · RenewCMS')
})
})
@@ -66,17 +56,13 @@ describe('AuthShell renders its notice and footer slots', () => {
const notice = wrapper.find('span')
expect(notice.text()).toBe('Your session expired.')
expect(
wrapper.findAll('[data-slot="root"][data-orientation]').length,
).toBe(1)
expect(wrapper.findAll('[data-slot="root"][data-orientation]').length).toBe(1)
const card = wrapper.find('[data-testid="auth-card"]')
expect(card.element.contains(notice.element)).toBe(true)
const html = wrapper.html()
expect(html.indexOf('<h1')).toBeLessThan(
html.indexOf('Your session expired.'),
)
expect(html.indexOf('<h1')).toBeLessThan(html.indexOf('Your session expired.'))
const footerLink = wrapper.find('a[href="/register/reset/request"]')
expect(footerLink.exists()).toBe(true)
@@ -0,0 +1,132 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
import { flushPromises, mount, type VueWrapper } from '@vue/test-utils'
import uiPlugin from '@nuxt/ui/vue-plugin'
import UButton from '@nuxt/ui/components/Button.vue'
import CodeSnippet from '@/components/CodeSnippet.vue'
import type { CodeSnippetTab } from '@/lib/codeSnippet'
const THREE_TABS: CodeSnippetTab[] = [
{ k: 'curl', label: 'curl', code: 'curl -O "https://cms.renew.example/a"' },
{ k: 'html', label: 'HTML', code: '<img src="a">' },
{ k: 'js', label: 'JavaScript', code: 'const res = await fetch("a")' },
]
let wrapper: VueWrapper | null = null
function stubClipboard() {
const writeText = vi.fn().mockResolvedValue(undefined)
Object.defineProperty(navigator, 'clipboard', { configurable: true, value: { writeText } })
return writeText
}
function mountSnippet(tabs: CodeSnippetTab[] = THREE_TABS) {
wrapper = mount(CodeSnippet, {
props: { tabs },
attachTo: document.body,
global: { plugins: [uiPlugin] },
})
return wrapper
}
function copyButton(target: VueWrapper) {
return target.get('button[aria-label="Copy code"]')
}
afterEach(() => {
wrapper?.unmount()
wrapper = null
vi.useRealTimers()
document.body.innerHTML = ''
})
describe('CodeSnippet', () => {
it('renders three tabs, the first selected with an underline, and a Copy code button', () => {
const target = mountSnippet()
const list = target.get('[role="tablist"]')
expect(list.attributes('aria-label')).toBe('Language')
const tabs = list.findAll('[role="tab"]')
expect(tabs.map((tab) => tab.text())).toEqual(['curl', 'HTML', 'JavaScript'])
expect(tabs[0]!.attributes('aria-selected')).toBe('true')
expect(tabs[0]!.classes().join(' ')).toContain('shadow-')
expect(tabs[1]!.attributes('aria-selected')).toBe('false')
expect(tabs[1]!.classes().join(' ')).not.toContain('shadow-')
expect(copyButton(target).text()).toBe('Copy')
})
it('switches the pre on a tab click and copies the active tab', async () => {
const writeText = stubClipboard()
const target = mountSnippet()
expect(target.get('pre').text()).toBe(THREE_TABS[0]!.code)
await target.findAll('[role="tab"]')[2]!.trigger('click')
expect(target.get('pre').text()).toBe(THREE_TABS[2]!.code)
await copyButton(target).trigger('click')
expect(writeText).toHaveBeenCalledWith(THREE_TABS[2]!.code)
})
it('moves between tabs with the arrow keys', async () => {
const target = mountSnippet()
await target.findAll('[role="tab"]')[0]!.trigger('keydown', { key: 'ArrowRight' })
expect(target.get('pre').text()).toBe(THREE_TABS[1]!.code)
await target.findAll('[role="tab"]')[1]!.trigger('keydown', { key: 'ArrowLeft' })
expect(target.get('pre').text()).toBe(THREE_TABS[0]!.code)
})
it('renders a muted label and no tab for a single tab', () => {
const target = mountSnippet([
{ k: 'base', label: 'Base URL', code: 'https://cms.renew.example' },
])
expect(target.findAll('[role="tab"]')).toHaveLength(0)
expect(target.text()).toContain('Base URL')
expect(target.get('pre').text()).toBe('https://cms.renew.example')
})
it('copies, reads Copied in a polite region for 2 s, then reverts', async () => {
const writeText = stubClipboard()
vi.useFakeTimers()
const target = mountSnippet()
await copyButton(target).trigger('click')
await flushPromises()
expect(writeText).toHaveBeenCalledWith(THREE_TABS[0]!.code)
const region = target.get('[aria-live="polite"]')
expect(region.text()).toBe('Copied')
expect(target.findComponent(UButton).props('icon')).toBe('i-lucide-check')
await vi.advanceTimersByTimeAsync(1999)
expect(region.text()).toBe('Copied')
await vi.advanceTimersByTimeAsync(1)
expect(region.text()).toBe('Copy')
expect(target.findComponent(UButton).props('icon')).toBe('i-lucide-copy')
})
it('copies two instances independently', async () => {
stubClipboard()
const first = mountSnippet()
const second = mount(CodeSnippet, {
props: { tabs: THREE_TABS },
attachTo: document.body,
global: { plugins: [uiPlugin] },
})
await copyButton(first).trigger('click')
await flushPromises()
expect(copyButton(first).text()).toBe('Copied')
expect(copyButton(second).text()).toBe('Copy')
second.unmount()
})
it('draws a focusable pre without syntax markup', () => {
const target = mountSnippet()
const pre = target.get('pre')
expect(pre.attributes('tabindex')).toBe('0')
expect(pre.find('span').exists()).toBe(false)
})
})
@@ -6,6 +6,8 @@ import router from '@/router'
import { useApi } from '@/composables/useApi'
import { useColorMode } from '@/composables/useColorMode'
import DashboardShell from '../DashboardShell.vue'
import { readFileSync } from 'node:fs'
import { join } from 'node:path'
import { DESKTOP_WIDTH, MOBILE_WIDTH, setViewportWidth } from './viewport'
vi.mock('@/composables/useApi', async (importOriginal) => {
@@ -429,3 +431,342 @@ describe('DashboardShell Settings expands to the Media subpages', () => {
expect(nav.text()).not.toContain('Cache')
})
})
describe('DashboardShell selected nav rows use sand with on-sand text', () => {
const SAND = 'bg-(--rc-sand)'
const ON_SAND = 'text-(--rc-on-sand)'
const STATES = ['', 'hover:', 'active:', 'focus-visible:']
const selectedClasses = STATES.flatMap((state) => [`${state}${SAND}`, `${state}${ON_SAND}`])
const SCOPED_BOLD = '[li[data-state=open]>&:not([aria-current=page])]:font-medium'
const UNSCOPED_BOLD = '[li[data-state=open]>&]:font-medium'
it.each([
'/settings',
'/settings/media/variants',
'/settings/media/cache',
'/home',
'/users',
'/activity',
])('fills the selected row on %s with sand and on-sand in every state', async (path) => {
const wrapper = await mountShell(path, { role: 'owner' })
const nav = wrapper.find('nav[aria-label="Main"]')
const selected = nav.find(`a[href="${path}"]`)
expect(selected.attributes('aria-current')).toBe('page')
expect(selected.classes()).toEqual(expect.arrayContaining(selectedClasses))
expect(selected.classes()).toContain('focus-visible:outline-(--ui-primary)')
expect(selected.find('[class*="--rc-on-sand"]').exists()).toBe(true)
const unselected = nav
.findAll('a')
.filter((link) => link.attributes('aria-current') === undefined)
expect(unselected.length).toBeGreaterThan(0)
for (const link of unselected) {
for (const cls of selectedClasses) {
expect(link.classes()).not.toContain(cls)
}
}
})
it('keeps the unfilled Settings parent bold when a child is selected', async () => {
const wrapper = await mountShell('/settings/media/variants', { role: 'owner' })
const parent = wrapper.find('nav[aria-label="Main"] a[href="/settings"]')
expect(parent.attributes('aria-current')).toBeUndefined()
expect(parent.classes()).not.toContain(SAND)
expect(parent.classes()).toContain(SCOPED_BOLD)
expect(parent.classes()).not.toContain(UNSCOPED_BOLD)
})
it('scopes the open-parent bold rule away from the selected row', async () => {
const wrapper = await mountShell('/settings', { role: 'owner' })
const selected = wrapper.find('nav[aria-label="Main"] a[href="/settings"]')
expect(selected.classes()).toContain(SCOPED_BOLD)
expect(selected.classes()).not.toContain(UNSCOPED_BOLD)
expect(selected.classes()).not.toContain('[li[data-state=open]>&]:text-highlighted')
})
it('draws drawer rows 44 px tall with the same selected treatment', async () => {
await mountShell('/settings', { role: 'owner', width: MOBILE_WIDTH })
const toggle = document.body.querySelector('[data-slot="toggle"]') as HTMLButtonElement
toggle.click()
await flushPromises()
const settings = document.body.querySelector(
'[role="dialog"] nav[aria-label="Main"] a[href="/settings"]',
) as HTMLElement
expect(settings.classList.contains('max-lg:h-11')).toBe(true)
for (const cls of selectedClasses) {
expect(settings.classList.contains(cls)).toBe(true)
}
})
})
const mainCss = readFileSync(join(import.meta.dirname, '../../assets/main.css'), 'utf8')
function declarationsOf(selector: string) {
const start = mainCss.indexOf(`\n${selector} {`)
const end = mainCss.indexOf('\n}', start)
const block = mainCss.slice(start, end)
return new Map(
[...block.matchAll(/^\t(--[a-z0-9-]+): ([^;]+);$/gm)].map((match) => [
match[1]!,
match[2]!,
]),
)
}
function resolveToken(declarations: Map<string, string>, token: string) {
const value = declarations.get(token) ?? declarationsOf(':root').get(token)!
const alias = /^var\((--[a-z0-9-]+)\)$/.exec(value)
if (!alias) {
return value
}
return declarations.get(alias[1]!) ?? resolveFromTheme(alias[1]!)
}
function resolveFromTheme(token: string) {
return new RegExp(`^\t${token}: ([^;]+);$`, 'm').exec(mainCss)![1]!
}
const tokenRows: [string, 'light' | 'dark', string][] = [
['--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)'],
]
const lightUiTokens = {
'--ui-bg': 'var(--color-white)',
'--ui-bg-muted': 'var(--color-chalk-50)',
'--ui-bg-elevated': 'var(--color-chalk-100)',
'--ui-bg-accented': 'var(--color-chalk-200)',
'--ui-bg-inverted': 'var(--color-chalk-900)',
'--ui-text-dimmed': 'var(--color-chalk-400)',
'--ui-text-muted': 'var(--color-chalk-500)',
'--ui-text-toned': 'var(--color-chalk-600)',
'--ui-text': 'var(--color-chalk-800)',
'--ui-text-highlighted': 'var(--color-chalk-900)',
'--ui-text-inverted': 'var(--color-white)',
'--ui-border': 'var(--color-chalk-200)',
'--ui-border-muted': 'var(--color-chalk-100)',
'--ui-border-accented': 'var(--color-chalk-450)',
'--ui-border-inverted': 'var(--color-chalk-900)',
'--ui-primary': 'var(--ui-color-primary-900)',
'--ui-secondary': 'var(--ui-color-secondary-700)',
'--ui-success': 'var(--ui-color-success-700)',
'--ui-info': 'var(--ui-color-info-700)',
'--ui-warning': 'var(--ui-color-warning-700)',
'--ui-error': 'var(--ui-color-error-700)',
}
const darkUiTokens = {
'--ui-bg': 'var(--color-chalk-900)',
'--ui-bg-muted': 'var(--color-chalk-950)',
'--ui-bg-elevated': 'var(--color-chalk-850)',
'--ui-bg-accented': 'var(--color-chalk-800)',
'--ui-bg-inverted': 'var(--color-chalk-50)',
'--ui-text-dimmed': 'var(--color-chalk-500)',
'--ui-text-muted': 'var(--color-chalk-400)',
'--ui-text-toned': 'var(--color-chalk-300)',
'--ui-text': 'var(--color-chalk-200)',
'--ui-text-highlighted': 'var(--color-chalk-50)',
'--ui-text-inverted': 'var(--color-chalk-900)',
'--ui-border': 'var(--color-chalk-700)',
'--ui-border-muted': 'var(--color-chalk-800)',
'--ui-border-accented': 'var(--color-chalk-500)',
'--ui-border-inverted': 'var(--color-chalk-50)',
'--ui-primary': 'var(--ui-color-primary-50)',
'--ui-secondary': 'var(--ui-color-secondary-300)',
'--ui-success': 'var(--ui-color-success-300)',
'--ui-info': 'var(--ui-color-info-300)',
'--ui-warning': 'var(--ui-color-warning-300)',
'--ui-error': 'var(--ui-color-error-300)',
}
function uiTokensOf(declarations: Map<string, string>) {
return Object.fromEntries(
[...declarations].filter(
([name]) => name.startsWith('--ui-') && !/radius|header|container/.test(name),
),
)
}
describe('main.css declares the shell design tokens', () => {
it.each(tokenRows)(
'%s resolves to the foundations value in the %s theme',
(token, theme, value) => {
const declarations = declarationsOf(theme === 'light' ? ':root' : '.dark')
expect(resolveToken(declarations, token)).toBe(value)
},
)
it('declares no --rc-canvas', () => {
expect(mainCss).not.toContain('--rc-canvas')
})
it('leaves every --ui-* token value unchanged', () => {
expect(uiTokensOf(declarationsOf(':root'))).toEqual(lightUiTokens)
expect(uiTokensOf(declarationsOf('.dark'))).toEqual(darkUiTokens)
})
})
const SELECTED_BASE = ['bg-(--rc-sand)', 'text-(--rc-on-sand)']
const SELECTED_STATES = ['hover', 'active', 'focus-visible'].flatMap((state) => [
`${state}:bg-(--rc-sand)`,
`${state}:text-(--rc-on-sand)`,
])
const FORBIDDEN_TEXT = /(^|:)(text-muted|text-white|text-inverted)$/
function navLink(root: ParentNode, href: string) {
return root.querySelector(`nav[aria-label="Main"] a[href="${href}"]`) as HTMLElement
}
function classesOf(element: Element) {
return Array.from(element.classList)
}
function expectSelected(link: HTMLElement) {
const classes = classesOf(link)
for (const cls of [...SELECTED_BASE, ...SELECTED_STATES]) {
expect(classes).toContain(cls)
}
expect(link.getAttribute('aria-current')).toBe('page')
const forbidden = classes.filter((cls) => FORBIDDEN_TEXT.test(cls))
expect(forbidden).toEqual([])
const iconClasses = classesOf(link.querySelector('svg, [data-slot="linkLeadingIcon"]')!)
expect(iconClasses.filter((cls) => FORBIDDEN_TEXT.test(cls))).toEqual([])
}
function expectUnfilled(link: HTMLElement) {
expect(link.getAttribute('aria-current')).toBeNull()
expect(classesOf(link).filter((cls) => cls.includes('--rc-sand'))).toEqual([])
}
function expectBoldParent(link: HTMLElement) {
expectUnfilled(link)
const classes = classesOf(link)
expect(classes).toContain('[li[data-state=open]>&:not([aria-current=page])]:text-highlighted')
expect(classes).toContain('[li[data-state=open]>&:not([aria-current=page])]:font-medium')
expect(link.closest('li')!.getAttribute('data-state')).toBe('open')
const chevron = link.querySelector('[data-slot="linkTrailingIcon"]')!
expect(classesOf(chevron)).toContain('group-data-[state=open]:rotate-90')
}
describe('DashboardShell selected nav rows keep the sand contract in every state', () => {
it('gives the selected Settings row a 2 px --ui-primary focus outline and keeps the sand fill', async () => {
const wrapper = await mountShell('/settings', { role: 'owner' })
const classes = classesOf(navLink(wrapper.element, '/settings'))
expect(classes).toContain('focus-visible:outline-2')
expect(classes).toContain('focus-visible:outline-(--ui-primary)')
expect(classes).toContain('focus-visible:bg-(--rc-sand)')
expect(classes).toContain('bg-(--rc-sand)')
})
it.each([
['/settings', '/settings'],
['/settings/media/variants', '/settings/media/variants'],
['/settings/media/cache', '/settings/media/cache'],
['/home', '/home'],
['/users', '/users'],
['/activity', '/activity'],
])(
'paints the selected row on %s with sand and never white or muted text',
async (path, href) => {
const wrapper = await mountShell(path, { role: 'owner' })
expectSelected(navLink(wrapper.element, href))
},
)
it('keeps Variants and Cache unselected under the filled Settings row on /settings', async () => {
const wrapper = await mountShell('/settings', { role: 'owner' })
expectUnfilled(navLink(wrapper.element, '/settings/media/variants'))
expectUnfilled(navLink(wrapper.element, '/settings/media/cache'))
})
it.each([
['/settings/media/variants', '/settings/media/cache'],
['/settings/media/cache', '/settings/media/variants'],
])('shows Settings unfilled, bold and open when %s is selected', async (path, other) => {
const wrapper = await mountShell(path, { role: 'owner' })
expectBoldParent(navLink(wrapper.element, '/settings'))
expectUnfilled(navLink(wrapper.element, other))
})
it.each([
['/settings', 'N1'],
['/settings/media/variants', 'N2'],
])('applies the same contract in the dark theme on %s (%s)', async (path) => {
document.documentElement.classList.add('dark')
try {
const wrapper = await mountShell(path, { role: 'owner' })
if (path === '/settings') {
expectSelected(navLink(wrapper.element, '/settings'))
expectUnfilled(navLink(wrapper.element, '/settings/media/variants'))
expectUnfilled(navLink(wrapper.element, '/settings/media/cache'))
} else {
expectSelected(navLink(wrapper.element, path))
expectBoldParent(navLink(wrapper.element, '/settings'))
}
} finally {
document.documentElement.classList.remove('dark')
}
})
})
describe('DashboardShell mobile drawer rows', () => {
async function openDrawer(path: string) {
await mountShell(path, { role: 'owner', width: MOBILE_WIDTH })
const toggle = document.body.querySelector('[data-slot="toggle"]') as HTMLButtonElement
toggle.click()
await flushPromises()
return document.body.querySelector('[role="dialog"]') as HTMLElement
}
it('draws every drawer row 44 px tall', async () => {
const drawer = await openDrawer('/settings')
const links = Array.from(drawer.querySelectorAll('nav[aria-label="Main"] a'))
expect(links).toHaveLength(9)
for (const link of links) {
expect(classesOf(link)).toContain('max-lg:h-11')
}
})
it('lists Variants and Cache unselected under the filled Settings row on /settings', async () => {
const drawer = await openDrawer('/settings')
expect(drawer.querySelector('nav[aria-label="Main"]')!.textContent).toContain('Media')
expectSelected(navLink(drawer, '/settings'))
expectUnfilled(navLink(drawer, '/settings/media/variants'))
expectUnfilled(navLink(drawer, '/settings/media/cache'))
})
it('fills Variants and leaves Settings unfilled and bold on /settings/media/variants', async () => {
const drawer = await openDrawer('/settings/media/variants')
expectSelected(navLink(drawer, '/settings/media/variants'))
expectBoldParent(navLink(drawer, '/settings'))
expectUnfilled(navLink(drawer, '/settings/media/cache'))
})
})
+6
View File
@@ -0,0 +1,6 @@
export const SHEET_MOBILE_CLASS =
'max-sm:!inset-x-0 max-sm:!top-auto max-sm:!bottom-0 max-sm:!left-0 max-sm:!w-full max-sm:!max-w-none max-sm:!translate-x-0 max-sm:!translate-y-0 max-sm:pt-3 max-sm:before:absolute max-sm:before:top-2 max-sm:before:left-1/2 max-sm:before:h-1 max-sm:before:w-9 max-sm:before:-translate-x-1/2 max-sm:before:bg-(--ui-border-accented)'
export const SHEET_CONTENT_CLASS = `divide-y-0 shadow-(--shadow-modal) ring-0 sm:translate-y-0 ${SHEET_MOBILE_CLASS}`
export const SHEET_FOOTER_CLASS = 'px-6 py-5 sm:px-6'
@@ -18,6 +18,7 @@ defineProps<{ files: number }>()
root: 'items-center rounded-none px-3.5 py-3',
icon: 'size-4 animate-spin',
title: 'font-semibold',
description: 'mt-2',
}"
>
<template #description>
+10 -1
View File
@@ -9,7 +9,8 @@ const VARIANT_ROWS = 5
const IMAGE_ROWS = 6
const BAR = 'rounded-none bg-accented'
const CARD_UI = {
root: 'min-w-0 rounded-none border border-default bg-default ring-0',
root: 'min-w-0 rounded-none border border-default bg-default ring-0 divide-y-0',
header: 'flex min-h-11 items-center border-b border-default px-4 py-0 sm:px-4 sm:py-0',
body: 'flex flex-col gap-5 p-4 sm:p-4',
}
</script>
@@ -24,12 +25,20 @@ const CARD_UI = {
</div>
<div class="grid grid-cols-1 gap-4 sm:grid-cols-[460px_minmax(0,1fr)]">
<UCard :ui="CARD_UI">
<template #header>
<h2 class="font-semibold text-highlighted">{{ t('By variant') }}</h2>
</template>
<div v-for="row in VARIANT_ROWS" :key="row" class="flex flex-col gap-2">
<USkeleton class="h-3.25 w-[50%]" :class="BAR" />
<USkeleton class="h-2 w-full" :class="BAR" />
</div>
</UCard>
<UCard v-if="desktop" :ui="CARD_UI">
<template #header>
<h2 class="font-semibold text-highlighted">
{{ t('Top 10 images by variant disk usage') }}
</h2>
</template>
<USkeleton
v-for="row in IMAGE_ROWS"
:key="row"
@@ -1,4 +1,5 @@
<script setup lang="ts">
import { SHEET_CONTENT_CLASS, SHEET_FOOTER_CLASS } from '@/components/sheetClasses'
import { computed, nextTick, onMounted, ref, watch } from 'vue'
const props = defineProps<{
@@ -55,13 +56,12 @@ function onConfirm() {
:close="false"
:content="{ role: 'alertdialog' }"
:ui="{
content:
'divide-y-0 shadow-(--shadow-modal) ring-0 sm:top-35 sm:max-w-115 sm:translate-y-0 max-sm:!inset-x-4 max-sm:!top-auto max-sm:!bottom-4 max-sm:!left-4 max-sm:!w-auto max-sm:!max-w-none max-sm:!translate-x-0 max-sm:!translate-y-0',
content: `${SHEET_CONTENT_CLASS} sm:top-35 sm:max-w-115`,
header: 'min-h-0 px-6 pt-5 pb-0 sm:px-6',
title: 'text-lg/6 font-semibold',
description: 'mt-1 text-sm text-muted text-pretty',
body: 'px-6 pt-5 pb-0 sm:px-6 sm:pt-5 sm:pb-0',
footer: 'px-6 py-5 sm:px-6',
footer: SHEET_FOOTER_CLASS,
}"
@update:open="open = $event"
>
@@ -41,6 +41,7 @@ const overlay = useLocalizedOverlay()
const { announceFailure } = useVariantToasts()
const isDesktop = useMediaQuery(DESKTOP_QUERY)
const form = useVariantForm(props.mode, props.initial)
const side = computed(() => (isDesktop.value ? 'right' : 'bottom'))
const saving = ref(false)
const saveFailed = ref(false)
@@ -63,6 +64,29 @@ const discardDescription = computed(() =>
: t("You have unsaved changes. If you close now, they're lost."),
)
const closeButton = computed(() => ({
icon: 'i-lucide-x',
color: 'neutral' as const,
variant: 'ghost' as const,
'aria-label': t('Close'),
class: isDesktop.value
? 'size-7 justify-center text-muted'
: 'top-4.5 end-1.5 size-11 justify-center p-0 text-muted',
ui: { leadingIcon: isDesktop.value ? 'size-4' : 'size-5' },
}))
const overlayUi = computed(() => ({
content: isDesktop.value
? 'w-full max-w-none sm:max-w-240'
: 'h-23/25 max-h-none pt-3 before:absolute before:top-2 before:left-1/2 before:h-1 before:w-9 before:-translate-x-1/2 before:bg-(--ui-border-accented)',
header: 'h-14 min-h-14 gap-3 px-5 py-0 max-sm:gap-1 max-sm:px-1.5',
wrapper: 'min-w-0 flex-1',
title: 'truncate text-lg font-semibold',
description: 'sr-only',
body: 'min-h-0 p-0 sm:overflow-hidden sm:p-0',
footer: 'h-18 gap-2 px-4 py-0 sm:h-16 sm:gap-3 sm:px-5',
}))
function focusField(field: FieldName) {
const target = document.querySelector<HTMLElement>(
`[data-field="${field}"] input:not([type="hidden"])`,
@@ -208,50 +232,19 @@ async function submit() {
<template>
<USlideover
:open="true"
side="right"
:side="side"
:title="title"
:description="t('Define a named size and format for generated images.')"
:close="
isDesktop
? {
icon: 'i-lucide-x',
color: 'neutral',
variant: 'ghost',
'aria-label': t('Close'),
class: 'size-7 justify-center text-muted',
}
: false
"
:close="closeButton"
:content="{ onOpenAutoFocus: focusOnOpen }"
:ui="{
content: 'w-full max-w-none sm:max-w-240',
header: 'h-14 min-h-14 gap-3 px-5 py-0 max-sm:gap-1 max-sm:px-1.5',
wrapper: 'min-w-0 flex-1',
title: 'truncate text-lg font-semibold',
description: 'sr-only',
body: 'min-h-0 p-0 sm:overflow-hidden sm:p-0',
footer: 'h-18 gap-2 px-4 py-0 sm:h-16 sm:gap-3 sm:px-5',
}"
:ui="overlayUi"
@update:open="onOpenChange"
>
<template #actions>
<UButton
v-if="!isDesktop"
icon="i-lucide-arrow-left"
color="neutral"
variant="ghost"
:aria-label="t('Back')"
class="order-first size-11 shrink-0 justify-center"
:ui="{ leadingIcon: 'size-5' }"
@click="requestClose"
/>
</template>
<template #body>
<UForm
:state="form.values"
:validate-on="[]"
class="flex flex-col gap-6 p-4 max-sm:pb-25 sm:grid sm:h-full sm:grid-cols-[440px_minmax(0,1fr)] sm:gap-0 sm:p-0"
class="flex flex-col gap-6 p-4 sm:grid sm:h-full sm:grid-cols-[440px_minmax(0,1fr)] sm:gap-0 sm:p-0"
@submit="submit"
>
<div class="min-w-0 sm:overflow-y-auto sm:p-5">
@@ -1,4 +1,5 @@
<script setup lang="ts">
import { SHEET_CONTENT_CLASS, SHEET_FOOTER_CLASS } from '@/components/sheetClasses'
import { t } from '@/i18n'
import { computed } from 'vue'
@@ -41,14 +42,13 @@ const originalTitle = computed(
:title="t('Preview: {0}', [variant.name])"
:description="t('Both images are shown at actual size. Scroll to pan.')"
:ui="{
content:
'sm:top-20 sm:translate-y-0 sm:max-w-220 max-sm:!inset-x-4 max-sm:!top-auto max-sm:!bottom-4 max-sm:!w-auto max-sm:!max-w-none max-sm:!translate-x-0 max-sm:!translate-y-0 divide-y-0 shadow-(--shadow-modal) ring-0',
content: `${SHEET_CONTENT_CLASS} sm:top-20 sm:max-w-220`,
header: 'min-h-0 px-6 pt-5 pb-0 sm:px-6',
close: 'top-5 end-6',
close: 'top-5 end-6 max-sm:top-8 max-sm:size-11 max-sm:justify-center',
title: 'text-lg/6 font-semibold',
description: 'sr-only',
body: 'px-6 pt-5 pb-0 sm:px-6 sm:pt-5 sm:pb-0',
footer: 'px-6 py-5 sm:px-6',
footer: SHEET_FOOTER_CLASS,
}"
>
<template #body>
@@ -239,3 +239,30 @@ describe('getMe maps the account fields', () => {
expect(me.displayName).toBe('')
})
})
describe('useApi abort and blob handling', () => {
it('rethrows an AbortError without flagging the app offline', async () => {
fetchMock.mockRejectedValue(new DOMException('aborted', 'AbortError'))
await expect(useApi().request('/v1/x')).rejects.toMatchObject({ name: 'AbortError' })
expect(isOffline.value).toBe(false)
})
it('requestBlob returns the response blob', async () => {
const blob = new Blob(['a,b'])
fetchMock.mockResolvedValue({ ...mockResponse(200), blob: async () => blob })
await expect(useApi().requestBlob('/v1/activity/export')).resolves.toBe(blob)
})
it('requestBlob reuses the 401 handling and redirects to login', async () => {
fetchMock.mockResolvedValue(mockResponse(401))
await expectApiError(useApi().requestBlob('/v1/activity/export'), { status: 401 })
await settle()
expect(router.currentRoute.value.path).toBe('/login')
expect(router.currentRoute.value.query.reason).toBe('expired')
})
})
@@ -8,16 +8,51 @@ vi.mock('@/composables/useApi', () => ({
import { useArticles } from '@/composables/useArticles'
const envelope = {
items: [],
total: 0,
page: 1,
size: 25,
counts: { all: 0, online: 0, draft: 0 },
}
describe('useArticles', () => {
beforeEach(() => {
request.mockReset()
request.mockResolvedValue(envelope)
})
it('asks the API for html bodies when listing articles', async () => {
request.mockResolvedValue([])
it('asks the API for html bodies with explicit paging when listing articles', async () => {
await useArticles().listArticles({ page: 1, size: 25 })
await useArticles().listArticles()
expect(request).toHaveBeenCalledWith('/v1/article/?format=html&page=1&size=25')
})
expect(request).toHaveBeenCalledWith('/v1/article/?format=html')
it('sends the search text and the status when they are set', async () => {
await useArticles().listArticles({ page: 2, size: 50, q: 'plaster', status: 'draft' })
expect(request).toHaveBeenCalledWith(
'/v1/article/?format=html&page=2&size=50&q=plaster&status=draft',
)
})
it('sends the sort when it is set', async () => {
await useArticles().listArticles({ page: 1, size: 25, sort: 'title:asc' })
expect(request).toHaveBeenCalledWith(
'/v1/article/?format=html&page=1&size=25&sort=title%3Aasc',
)
})
it('omits an empty search and an empty status', async () => {
await useArticles().listArticles({ page: 3, size: 5, q: '', status: '' })
expect(request).toHaveBeenCalledWith('/v1/article/?format=html&page=3&size=5')
})
it('returns the envelope untouched', async () => {
const result = await useArticles().listArticles({ page: 1, size: 25 })
expect(result).toEqual(envelope)
})
})
@@ -0,0 +1,63 @@
import { describe, expect, it } from 'vitest'
import { defineComponent, h, nextTick, ref } from 'vue'
import { mount } from '@vue/test-utils'
import { useScrollEdges } from '../useScrollEdges'
function mountEdges() {
const element = document.createElement('div')
let edges!: ReturnType<typeof useScrollEdges>
const Host = defineComponent({
setup() {
edges = useScrollEdges(ref(element))
return () => h('span')
},
})
mount(Host)
return { element, edges }
}
function layout(element: HTMLElement, scrollLeft: number) {
Object.defineProperty(element, 'clientWidth', { configurable: true, value: 390 })
Object.defineProperty(element, 'scrollWidth', { configurable: true, value: 1100 })
element.scrollLeft = scrollLeft
element.dispatchEvent(new Event('scroll'))
}
describe('useScrollEdges', () => {
it('hides nothing at the start except the end', async () => {
const { element, edges } = mountEdges()
layout(element, 0)
await nextTick()
expect([edges.hiddenBefore.value, edges.hiddenAfter.value]).toEqual([false, true])
})
it('hides both sides in the middle', async () => {
const { element, edges } = mountEdges()
layout(element, 100)
await nextTick()
expect([edges.hiddenBefore.value, edges.hiddenAfter.value]).toEqual([true, true])
})
it('hides only the start at the end, within one pixel', async () => {
const { element, edges } = mountEdges()
layout(element, 710)
await nextTick()
expect([edges.hiddenBefore.value, edges.hiddenAfter.value]).toEqual([true, false])
layout(element, 709)
await nextTick()
expect(edges.hiddenAfter.value).toBe(false)
})
it('shows no fade when the content fits', async () => {
const { element, edges } = mountEdges()
Object.defineProperty(element, 'clientWidth', { configurable: true, value: 500 })
Object.defineProperty(element, 'scrollWidth', { configurable: true, value: 500 })
element.dispatchEvent(new Event('scroll'))
await nextTick()
expect([edges.hiddenBefore.value, edges.hiddenAfter.value]).toEqual([false, false])
})
})
+66
View File
@@ -0,0 +1,66 @@
import { getCurrentScope, onScopeDispose, shallowRef, watchEffect } from 'vue'
import type { Router } from 'vue-router'
import { t, translate } from '@/i18n'
const PRODUCT_NAME = 'RenewCMS'
type TitleSource = () => string | undefined
const overrides = shallowRef<TitleSource[]>([])
const headings = shallowRef<TitleSource[]>([])
function register(list: typeof overrides, source: TitleSource) {
list.value = [...list.value, source]
if (getCurrentScope()) {
onScopeDispose(() => {
list.value = list.value.filter((entry) => entry !== source)
})
}
}
function firstName(sources: TitleSource[]) {
for (const source of [...sources].reverse()) {
const name = source()
if (name) {
return name
}
}
return undefined
}
export function usePageTitleOverride(source: TitleSource) {
register(overrides, source)
}
export function useCardHeading(source: TitleSource) {
register(headings, source)
}
function formatTitle(name: string | undefined) {
return name ? t('{0} · RenewCMS', [name]) : PRODUCT_NAME
}
function routeName(router: Router) {
const meta = router.currentRoute.value.meta
if (typeof meta.documentTitle === 'string') {
return meta.documentTitle
}
const override = firstName(overrides.value)
if (override) {
return override
}
const heading = firstName(headings.value)
if (heading) {
return heading
}
return typeof meta.title === 'string' ? translate(meta.title) : undefined
}
let stopTitleWatcher: (() => void) | null = null
export function installDocumentTitle(router: Router) {
stopTitleWatcher?.()
stopTitleWatcher = watchEffect(() => {
document.title = formatTitle(routeName(router))
})
}
+19 -2
View File
@@ -1,6 +1,8 @@
import { useApi } from '@/composables/useApi'
import {
exportAllQuery,
exportQuery,
type ExportRange,
listQuery,
summaryQuery,
type ActivityFilters,
@@ -17,7 +19,6 @@ export interface PersonOptions {
export const ACTIVITY_SKELETON_ROWS = 9
export const ACTIVITY_SKELETON_CARDS = 5
export const EXPORT_FILE_NAME = 'activity.csv'
export function useActivity() {
const { request, requestBlob } = useApi()
@@ -43,6 +44,15 @@ export function useActivity() {
return requestBlob(`/v1/activity/export?${exportQuery(filters)}`)
}
function exportAllActivity(
range: ExportRange,
from: string,
to: string,
signal: AbortSignal,
): Promise<Blob> {
return requestBlob(`/v1/activity/export?${exportAllQuery(range, from, to)}`, { signal })
}
async function listPeople(): Promise<PersonOptions> {
const [users, keys] = await Promise.all([
request<UserListItem[]>('/v1/user/'),
@@ -58,7 +68,14 @@ export function useActivity() {
}
}
return { listActivity, listRecentActivity, getSummary, exportActivity, listPeople }
return {
listActivity,
listRecentActivity,
getSummary,
exportActivity,
exportAllActivity,
listPeople,
}
}
export function downloadBlob(blob: Blob, fileName: string) {
+201
View File
@@ -0,0 +1,201 @@
import { computed, onBeforeUnmount, ref, toValue, type MaybeRefOrGetter } from 'vue'
import { t } from '@/i18n'
import { useLocalizedToast } from '@/i18n/presentation'
import { ApiError, isAbort } from '@/composables/useApi'
import { downloadBlob, useActivity } from '@/composables/useActivity'
import { useSessionStore } from '@/stores/session'
import {
allActivityFileName,
currentViewFileName,
isExportRangeValid,
isHeaderOnlyCsv,
readBlobText,
type ActivityFilters,
NOTHING_TO_EXPORT_COPY,
OWNERS_ONLY_COPY,
type ExportRange,
} from '@/lib/activity'
export type ExportStage = 'configure' | 'preparing' | 'started' | 'failed' | 'empty' | 'denied'
const HTTP_UNAUTHORIZED = 401
const HTTP_FORBIDDEN = 403
const HTTP_BAD_REQUEST = 400
const SERVER_ERROR_COPY =
'Something went wrong on our side. Nothing was changed. Try again in a moment.'
const BAD_REQUEST_COPY = "That request wasn't valid. Check the fields and try again."
export function useActivityExport(filters: MaybeRefOrGetter<ActivityFilters>) {
const session = useSessionStore()
const toast = useLocalizedToast()
const { exportActivity, exportAllActivity } = useActivity()
const forbidden = ref(false)
const currentBusy = ref(false)
const dialogOpen = ref(false)
const stage = ref<ExportStage>('configure')
const range = ref<ExportRange>('all')
const from = ref('')
const to = ref('')
const startedFileName = ref('')
let controller: AbortController | null = null
const canSubmit = computed(
() => stage.value === 'configure' && isExportRangeValid(range.value, from.value, to.value),
)
function notify(
color: 'success' | 'error' | 'neutral',
icon: string,
title: () => string,
description?: () => string,
) {
toast.add(() => ({
color,
icon,
get title() {
return title()
},
get description() {
return description?.()
},
}))
}
function notifyStarted(fileName: string) {
notify(
'success',
'i-lucide-circle-check',
() => t('Download started'),
() => t('{0} is downloading.', [fileName]),
)
}
function isGlobalFailure(error: unknown) {
if (!(error instanceof ApiError)) return false
if (error.status === HTTP_UNAUTHORIZED) return true
return error.status === HTTP_FORBIDDEN && session.session?.verified === false
}
async function hasRows(blob: Blob) {
return !isHeaderOnlyCsv(await readBlobText(blob))
}
async function exportCurrentView() {
if (currentBusy.value) return
currentBusy.value = true
try {
const blob = await exportActivity(toValue(filters))
if (!(await hasRows(blob))) {
notify(
'neutral',
'i-lucide-file-x',
() => t('Nothing to export'),
() => t(NOTHING_TO_EXPORT_COPY),
)
return
}
const fileName = currentViewFileName()
downloadBlob(blob, fileName)
notifyStarted(fileName)
} catch (error) {
failCurrentView(error)
} finally {
currentBusy.value = false
}
}
function failCurrentView(error: unknown) {
if (isGlobalFailure(error)) return
if (error instanceof ApiError && error.status === HTTP_FORBIDDEN) {
forbidden.value = true
notify(
'error',
'i-lucide-lock',
() => t("You can't export all activity"),
() => t(OWNERS_ONLY_COPY),
)
return
}
const copy =
error instanceof ApiError && error.status === HTTP_BAD_REQUEST
? BAD_REQUEST_COPY
: SERVER_ERROR_COPY
notify(
'error',
'i-lucide-circle-x',
() => t("Couldn't prepare the download"),
() => t(copy),
)
}
function openDialog() {
stage.value = 'configure'
range.value = 'all'
from.value = ''
to.value = ''
dialogOpen.value = true
}
async function submit() {
if (stage.value !== 'configure' && stage.value !== 'failed') return
if (!isExportRangeValid(range.value, from.value, to.value)) return
stage.value = 'preparing'
const current = new AbortController()
controller = current
try {
const blob = await exportAllActivity(range.value, from.value, to.value, current.signal)
if (current.signal.aborted) return
if (!(await hasRows(blob))) {
stage.value = 'empty'
return
}
startedFileName.value = allActivityFileName()
downloadBlob(blob, startedFileName.value)
stage.value = 'started'
} catch (error) {
if (current.signal.aborted || isAbort(error)) return
failDialog(error)
} finally {
if (controller === current) controller = null
}
}
function failDialog(error: unknown) {
if (isGlobalFailure(error)) {
dialogOpen.value = false
return
}
if (error instanceof ApiError && error.status === HTTP_FORBIDDEN) {
forbidden.value = true
stage.value = 'denied'
return
}
stage.value = 'failed'
}
function closeDialog() {
controller?.abort()
controller = null
if (stage.value === 'started') notifyStarted(startedFileName.value)
dialogOpen.value = false
}
onBeforeUnmount(() => controller?.abort())
return {
forbidden,
currentBusy,
dialogOpen,
stage,
range,
from,
to,
startedFileName,
canSubmit,
exportCurrentView,
openDialog,
submit,
closeDialog,
}
}
+14 -45
View File
@@ -1,13 +1,6 @@
import { computed, onBeforeUnmount, ref } from 'vue'
import { t } from '@/i18n'
import { useLocalizedToast } from '@/i18n/presentation'
import { ApiError } from '@/composables/useApi'
import {
downloadBlob,
EXPORT_FILE_NAME,
useActivity,
type PersonOptions,
} from '@/composables/useActivity'
import { useActivity, type PersonOptions } from '@/composables/useActivity'
import { useSessionStore } from '@/stores/session'
import {
activeChips,
@@ -52,8 +45,7 @@ function delayedFlag() {
export function useActivityPage() {
const session = useSessionStore()
const toast = useLocalizedToast()
const { listActivity, getSummary, exportActivity, listPeople } = useActivity()
const { listActivity, getSummary, listPeople } = useActivity()
const filters = ref<ActivityFilters>(defaultFilters())
const page = ref(1)
@@ -64,7 +56,6 @@ export function useActivityPage() {
const summary = ref<ActivitySummary | null>(null)
const summaryState = ref<SummaryState>('idle')
const people = ref<PersonOptions | null>(null)
const exporting = ref(false)
const selectedId = ref<number | null>(null)
const navigating = ref(false)
const listSkeleton = delayedFlag()
@@ -85,10 +76,7 @@ export function useActivityPage() {
)
const isEmpty = computed(() => listState.value === 'ready' && total.value === 0)
const exportDisabled = computed(
() =>
exporting.value ||
listState.value === 'error' ||
(isEmpty.value && chips.value.length === 0),
() => listState.value === 'error' || (isEmpty.value && chips.value.length === 0),
)
const pageCount = computed(() => Math.max(1, Math.ceil(total.value / size.value)))
const rangeStart = computed(() => (total.value === 0 ? 0 : (page.value - 1) * size.value + 1))
@@ -190,6 +178,15 @@ export function useActivityPage() {
applyFilters(defaultFilters(), true)
}
function toggleFailed() {
const outcome = filters.value.outcome === 'failed' ? 'all' : 'failed'
applyFilters({ ...filters.value, outcome })
}
function toggleSecurity() {
applyFilters({ ...filters.value, security: !filters.value.security })
}
function goToPage(next: number) {
if (next === page.value || next < 1 || next > pageCount.value) return
fetchPage(next)
@@ -215,34 +212,6 @@ export function useActivityPage() {
}
}
async function runExport() {
if (exportDisabled.value) return
exporting.value = true
try {
const blob = await exportActivity(filters.value)
downloadBlob(blob, EXPORT_FILE_NAME)
toast.add(() => ({
color: 'success',
icon: 'i-lucide-circle-check',
get title() {
return t('Export started. Your file will download shortly.')
},
}))
} catch (error) {
if (!(error instanceof ApiError && error.status === 401)) {
toast.add(() => ({
color: 'error',
icon: 'i-lucide-circle-x',
get title() {
return t("Couldn't export activity. Try again.")
},
}))
}
} finally {
exporting.value = false
}
}
function openDetails(id: number) {
selectedId.value = id
}
@@ -284,7 +253,6 @@ export function useActivityPage() {
summary,
summaryState,
people,
exporting,
chips,
isFullView,
isEmpty,
@@ -303,11 +271,12 @@ export function useActivityPage() {
applyFilters,
removeChip,
clearAll,
toggleFailed,
toggleSecurity,
goToPage,
setSize,
retry,
ensurePeople,
runExport,
openDetails,
closeDetails,
previous: () => step(-1),
+8 -1
View File
@@ -40,6 +40,10 @@ export interface RequestOptions extends RequestInit {
onForbidden?: OnForbidden
}
export function isAbort(error: unknown) {
return error instanceof DOMException && error.name === 'AbortError'
}
export const isOffline = ref(false)
export const authRedirectPending = ref(false)
@@ -107,7 +111,10 @@ export function useApi() {
let response: Response
try {
response = await fetch(path, { credentials: 'include', ...init })
} catch {
} catch (error) {
if (isAbort(error)) {
throw error
}
isOffline.value = true
throw new NetworkError()
}
+174
View File
@@ -0,0 +1,174 @@
import { ref, watch } from 'vue'
import type { Ref } from 'vue'
import { useMediaQuery } from '@vueuse/core'
import type { EditorToolbarItem } from '@nuxt/ui'
import type { Editor } from '@tiptap/core'
import { t } from '@/i18n'
import {
applyLinkEdit,
describeLinkDialog,
imageIsSelected,
linkRangeAtPos,
linkTouchesSelection,
removeLinkInRange,
textOfRange,
} from '@/lib/articleLink'
import type { LinkDialogDraft, LinkEdit, LinkPopoverTarget, TextRange } from '@/lib/articleLink'
const LINK_TOOLTIP_DELAY_MS = 400
const COARSE_POINTER_QUERY = '(pointer: coarse)'
const MAC_PLATFORM = /mac|iphone|ipad|ipod/i
const LINK_BUTTON_FOCUS_CLASS =
'focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-primary'
const LINK_BUTTON_CLASS = `text-toned hover:text-highlighted ${LINK_BUTTON_FOCUS_CLASS}`
const LINK_BUTTON_ACTIVE_CLASS = `bg-(--rc-sand) text-(--rc-on-sand) hover:bg-(--rc-sand) hover:text-(--rc-on-sand) ${LINK_BUTTON_FOCUS_CLASS}`
export type LinkToolbarItem = EditorToolbarItem & {
'aria-label': string
'aria-pressed': 'true' | 'false'
'aria-disabled'?: 'true'
}
interface LinkPopoverState {
element: HTMLElement | null
text: string
href: string
range: TextRange
}
function isMacPlatform() {
return MAC_PLATFORM.test(navigator.platform)
}
export function useArticleLink(editorRef: Ref<Editor | null>, isDisabled: () => boolean) {
const isTouch = useMediaQuery(COARSE_POINTER_QUERY)
const dialogOpen = ref(false)
const dialog = ref<LinkDialogDraft>({
mode: 'insert',
text: '',
href: '',
newTab: false,
range: { from: 0, to: 0 },
})
const popoverOpen = ref(false)
const popover = ref<LinkPopoverState>({
element: null,
text: '',
href: '',
range: { from: 0, to: 0 },
})
function editableEditor(): Editor | null {
const editor = editorRef.value
if (!editor || isDisabled() || !editor.isEditable || imageIsSelected(editor)) {
return null
}
return editor
}
function openDialog() {
const editor = editableEditor()
if (!editor) {
return
}
popoverOpen.value = false
dialog.value = describeLinkDialog(editor)
dialogOpen.value = true
}
function openPopover(target: LinkPopoverTarget) {
const editor = editableEditor()
const range = editor ? linkRangeAtPos(editor, target.pos) : null
if (!editor || !range) {
return
}
popover.value = {
element: target.element,
text: textOfRange(editor, range),
href: range.attrs.href,
range: { from: range.from, to: range.to },
}
popoverOpen.value = true
}
function apply(edit: LinkEdit) {
const editor = editorRef.value
dialogOpen.value = false
if (editor) {
applyLinkEdit(editor, dialog.value, edit)
}
}
function removeFromDialog() {
dialogOpen.value = false
if (editorRef.value) {
removeLinkInRange(editorRef.value, dialog.value.range)
}
}
function editFromPopover() {
editorRef.value?.commands.setTextSelection(popover.value.range)
openDialog()
}
function openFromPopover() {
window.open(popover.value.href, '_blank', 'noopener,noreferrer')
}
function removeFromPopover() {
if (editorRef.value) {
removeLinkInRange(editorRef.value, popover.value.range)
}
}
watch(dialogOpen, (isOpen, wasOpen) => {
if (wasOpen && !isOpen) {
editorRef.value?.commands.focus()
}
})
watch(popoverOpen, (isOpen, wasOpen) => {
if (wasOpen && !isOpen && !dialogOpen.value) {
editorRef.value?.commands.focus()
}
})
function toolbarItem(editor: Editor): LinkToolbarItem {
const blocked = imageIsSelected(editor)
const active = !blocked && linkTouchesSelection(editor)
return {
icon: 'i-lucide-link',
class: active ? LINK_BUTTON_ACTIVE_CLASS : LINK_BUTTON_CLASS,
'aria-label': t('Insert link'),
'aria-pressed': active ? 'true' : 'false',
'aria-disabled': blocked ? 'true' : undefined,
tooltip:
blocked || isTouch.value
? undefined
: {
delayDuration: LINK_TOOLTIP_DELAY_MS,
get text() {
return isMacPlatform()
? t('Insert link (⌘K)')
: t('Insert link (Ctrl+K)')
},
},
onClick: () => openDialog(),
}
}
return {
dialogOpen,
dialog,
popoverOpen,
popover,
openDialog,
openPopover,
apply,
removeFromDialog,
editFromPopover,
openFromPopover,
removeFromPopover,
toolbarItem,
}
}
+41 -2
View File
@@ -1,4 +1,5 @@
import { useApi } from '@/composables/useApi'
import type { ArticleStatus } from '@/lib/articleListQuery'
export interface Article {
id: number
@@ -9,11 +10,49 @@ export interface Article {
updated_at: string
}
export type { ArticleStatus }
export interface ArticleCounts {
all: number
online: number
draft: number
}
export interface ArticlePage {
items: Article[]
total: number
page: number
size: number
counts: ArticleCounts
}
export interface ListArticlesParams {
page: number
size: number
q?: string
status?: ArticleStatus | ''
sort?: string
}
export function useArticles() {
const { request } = useApi()
function listArticles(): Promise<Article[]> {
return request<Article[]>('/v1/article/?format=html')
function listArticles(params: ListArticlesParams): Promise<ArticlePage> {
const query = new URLSearchParams({
format: 'html',
page: String(params.page),
size: String(params.size),
})
if (params.q) {
query.set('q', params.q)
}
if (params.status) {
query.set('status', params.status)
}
if (params.sort) {
query.set('sort', params.sort)
}
return request<ArticlePage>(`/v1/article/?${query.toString()}`)
}
return { listArticles }
+47
View File
@@ -0,0 +1,47 @@
import { onBeforeUnmount, ref, watch } from 'vue'
import type { Ref } from 'vue'
const EDGE_TOLERANCE_PX = 1
export function useScrollEdges(target: Ref<HTMLElement | null>) {
const hiddenBefore = ref(false)
const hiddenAfter = ref(false)
let observer: ResizeObserver | null = null
let attached: HTMLElement | null = null
function measure() {
const element = attached
if (!element) {
return
}
hiddenBefore.value = element.scrollLeft > EDGE_TOLERANCE_PX
hiddenAfter.value =
element.scrollLeft + element.clientWidth < element.scrollWidth - EDGE_TOLERANCE_PX
}
function detach() {
attached?.removeEventListener('scroll', measure)
observer?.disconnect()
observer = null
attached = null
}
function attach(element: HTMLElement | null) {
detach()
if (!element) {
return
}
attached = element
element.addEventListener('scroll', measure, { passive: true })
if (typeof ResizeObserver !== 'undefined') {
observer = new ResizeObserver(measure)
observer.observe(element)
}
measure()
}
watch(target, attach, { immediate: true, flush: 'post' })
onBeforeUnmount(detach)
return { hiddenBefore, hiddenAfter }
}
Loaded 100 of 154 files, more files were not shown because too many files have changed in this diff. Show more