feat(API): media field type

This commit is contained in:
Florian Sylvain committed 2026-10-21 05:07:36 +02:00
1 parent ad5faf3d19
commit a2d596f4ca
63 files changed
+2567 -259

No files matched your search

+1
View File
@@ -28,3 +28,4 @@ CLAUDE.md
.agents/
AGENTS.md
codex-workflow.md
CODING_STANDARDS.md
+8 -8
View File
@@ -332,7 +332,7 @@ func getUseCases(repos *Repositories, imageStorage domainImage.Storage, settings
renderer := markdown.NewConverter()
keyGenerator := hashing.NewSHA256KeyGenerator()
recorder := auditing.NewRecorder(repos.AuditRepo, time.Now, log.Default())
mergeMedia := useCases.NewMergeMediaUseCase(repos.ImageRepo, repos.ArticleRepo, imageStorage, repos.VariantFileRepo, recorder, repos.SiteRepo, repos.AuthorRepo)
mergeMedia := useCases.NewMergeMediaUseCase(repos.ImageRepo, repos.ArticleRepo, imageStorage, repos.VariantFileRepo, recorder, repos.SiteRepo, repos.AuthorRepo, repos.ContentTypeRepo, repos.EntryRepo)
runPurge := useCases.NewRunPurgeUseCase(repos.ImageRepo, repos.ArticleRepo, mergeMedia, repos.PurgeSettingsRepo, time.Now, log.Default(), recorder, repos.SiteRepo, repos.AuthorRepo)
purgeScheduler := useCases.NewPurgeSchedulerUseCase(repos.PurgeSettingsRepo, runPurge, recorder)
@@ -372,10 +372,10 @@ func getUseCases(repos *Repositories, imageStorage domainImage.Storage, settings
ListBuiltinTypesUseCase: useCases.NewListBuiltinTypesUseCase(),
GetBuiltinTypeUseCase: useCases.NewGetBuiltinTypeUseCase(),
LookupUserNamesUseCase: useCases.NewLookupUserNamesUseCase(repos.UserRepo),
CreateEntryUseCase: useCases.NewCreateEntryUseCase(repos.ContentTypeRepo, repos.EntryRepo, time.Now),
GetEntryUseCase: useCases.NewGetEntryUseCase(repos.ContentTypeRepo, repos.EntryRepo),
ListEntriesUseCase: useCases.NewListEntriesUseCase(repos.ContentTypeRepo, repos.EntryRepo),
UpdateEntryUseCase: useCases.NewUpdateEntryUseCase(repos.ContentTypeRepo, repos.EntryRepo, time.Now),
CreateEntryUseCase: useCases.NewCreateEntryUseCase(repos.ContentTypeRepo, repos.EntryRepo, repos.ImageRepo, time.Now),
GetEntryUseCase: useCases.NewGetEntryUseCase(repos.ContentTypeRepo, repos.EntryRepo, repos.ImageRepo),
ListEntriesUseCase: useCases.NewListEntriesUseCase(repos.ContentTypeRepo, repos.EntryRepo, repos.ImageRepo),
UpdateEntryUseCase: useCases.NewUpdateEntryUseCase(repos.ContentTypeRepo, repos.EntryRepo, repos.ImageRepo, time.Now),
DeleteEntryUseCase: useCases.NewDeleteEntryUseCase(repos.ContentTypeRepo, repos.EntryRepo),
GetUserUseCase: useCases.NewGetUserUseCase(repos.UserRepo),
CreateUserUseCase: useCases.NewCreateUserUseCase(repos.UserRepo, hasher, repos.MailRepo, settings.PublicURL, recorder),
@@ -395,14 +395,14 @@ func getUseCases(repos *Repositories, imageStorage domainImage.Storage, settings
SendMailUseCase: useCases.NewSendMailUseCase(repos.MailRepo),
CreateImageUseCase: useCases.NewCreateImageUseCase(repos.ImageRepo, imageStorage, recorder),
OpenMediaUseCase: useCases.NewOpenMediaUseCase(imageStorage),
ListMediaUseCase: useCases.NewListMediaUseCase(repos.ImageRepo, repos.ArticleRepo, repos.UserRepo, repos.VariantFileRepo, repos.SiteRepo, repos.AuthorRepo),
ListMediaUseCase: useCases.NewListMediaUseCase(repos.ImageRepo, repos.ArticleRepo, repos.UserRepo, repos.VariantFileRepo, repos.SiteRepo, repos.AuthorRepo, repos.ContentTypeRepo, repos.EntryRepo),
RenameMediaUseCase: useCases.NewRenameMediaUseCase(repos.ImageRepo, recorder),
DeleteMediaUseCase: useCases.NewDeleteMediaUseCase(repos.ImageRepo, imageStorage, repos.VariantFileRepo, recorder, repos.SiteRepo, repos.AuthorRepo, repos.ArticleRepo),
MergeMediaUseCase: mergeMedia,
GetMediaUsageUseCase: useCases.NewGetMediaUsageUseCase(repos.ImageRepo, repos.ArticleRepo, repos.SiteRepo, repos.AuthorRepo),
GetMediaUsageUseCase: useCases.NewGetMediaUsageUseCase(repos.ImageRepo, repos.ArticleRepo, repos.SiteRepo, repos.AuthorRepo, repos.ContentTypeRepo, repos.EntryRepo),
GetPurgeSettingsUseCase: useCases.NewGetPurgeSettingsUseCase(repos.PurgeSettingsRepo),
UpdatePurgeSettingsUseCase: useCases.NewUpdatePurgeSettingsUseCase(repos.PurgeSettingsRepo, time.Now),
PreviewPurgeUseCase: useCases.NewPreviewPurgeUseCase(repos.ImageRepo, repos.ArticleRepo, repos.SiteRepo, repos.AuthorRepo),
PreviewPurgeUseCase: useCases.NewPreviewPurgeUseCase(repos.ImageRepo, repos.ArticleRepo, repos.SiteRepo, repos.AuthorRepo, repos.ContentTypeRepo, repos.EntryRepo),
RunPurgeUseCase: runPurge,
GetSettingsUseCase: useCases.NewGetSettingsUseCase(settings.Version),
GetUpdateStatusUseCase: useCases.NewGetUpdateStatusUseCase(repos.UpdateStore, repos.UpdateJobs, repos.UpdateHelper, repos.UpdateResults, repos.RestartRequests, settings.Version, settings.Container, time.Now),
+28
View File
@@ -42,6 +42,33 @@ type entryResponse struct {
UpdatedBy uint32 `json:"updated_by"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
Media map[string]any `json:"media"`
}
type mediaBody struct {
ID uint32 `json:"id"`
Filename string `json:"filename"`
Width *int `json:"width"`
Height *int `json:"height"`
Size int64 `json:"size"`
ThumbnailURL string `json:"thumbnail_url"`
}
type missingMediaBody struct {
ID uint32 `json:"id"`
Missing bool `json:"missing"`
}
func toMediaResponse(media map[string]useCases.EntryMedia) map[string]any {
body := make(map[string]any, len(media))
for key, item := range media {
if item.Missing {
body[key] = missingMediaBody{ID: item.ID, Missing: true}
continue
}
body[key] = mediaBody{ID: item.ID, Filename: item.Filename, Width: item.Width, Height: item.Height, Size: item.Size, ThumbnailURL: item.ThumbnailURL}
}
return body
}
func toResponse(typed useCases.TypedEntry) entryResponse {
@@ -53,6 +80,7 @@ func toResponse(typed useCases.TypedEntry) entryResponse {
UpdatedBy: typed.UpdatedBy,
CreatedAt: typed.CreatedAt,
UpdatedAt: typed.UpdatedAt,
Media: toMediaResponse(typed.Media),
}
}
+20 -2
View File
@@ -92,9 +92,27 @@ func intQueryParam(values url.Values, name string, fallback int) (int, error) {
type usageResponse struct {
Type string `json:"type"`
ID uint32 `json:"id"`
Title string `json:"title"`
Title string `json:"title,omitempty"`
Published *bool `json:"published,omitempty"`
Fields []string `json:"fields"`
ContentTypeKey string `json:"content_type_key,omitempty"`
ContentTypeName string `json:"content_type_name,omitempty"`
FirstField *usageFirstFieldBody `json:"first_field,omitempty"`
}
type usageFirstFieldBody struct {
Key string `json:"key"`
Type string `json:"type"`
Value any `json:"value"`
}
func toUsageResponse(usage useCases.MediaUsage) usageResponse {
body := usageResponse{Type: usage.Type, ID: usage.ID, Title: usage.Title, Published: usage.Published, Fields: usage.Fields, ContentTypeKey: usage.ContentTypeKey, ContentTypeName: usage.ContentTypeName}
if usage.FirstField != nil {
body.FirstField = &usageFirstFieldBody{Key: usage.FirstField.Key, Type: string(usage.FirstField.Type), Value: usage.FirstField.Value}
}
return body
}
type mergeResponse struct {
@@ -347,7 +365,7 @@ func (h *Handler) Usage(w http.ResponseWriter, r *http.Request) {
response := make([]usageResponse, 0, len(usages))
for _, usage := range usages {
response = append(response, usageResponse{Type: usage.Type, ID: usage.ID, Title: usage.Title, Published: usage.Published, Fields: usage.Fields})
response = append(response, toUsageResponse(usage))
}
writeJSON(w, http.StatusOK, response)
}
-108
View File
@@ -1,108 +0,0 @@
# Claude Design prompt: custom content types
Paste everything below the line into Claude Design, with the existing RenewCMS design system attached.
---
You are extending the RenewCMS back-office design. RenewCMS is a small self-hosted CMS (Go API plus a Vue 3 SPA built with Nuxt UI v4 and Tailwind 4). The existing screens, the AppFrame back-office shell, the AuthCard auth frames, the design tokens and the component inventory are already in this design system: reuse them, never invent new colors, spacing, radius or type values, and keep the same copy tone (short, plain, sentence case). Deliver the same artifacts the system already uses: one board per screen with every state, the exact copy per state, the routes with their auth requirement, the new components with their Nuxt UI mapping, and light and dark variants at desktop (1440x900) and mobile (390x844).
## The feature
Until now RenewCMS only managed fixed content: articles, authors, sites, media and users. We are adding custom content types: an owner or admin defines a content type (for example "Recipe" or "Event") made of ordered fields, and then any verified user creates entries of that type. Think of the clear part of Directus: a type is a collection, a field is a typed column. Do not copy Strapi's split between collections, components and fields into separate screens: everything about a type happens on one screen. Do not draw a table-builder feel with database jargon; speak in terms of content.
The backend for the first part already exists. Design the full experience including the parts that come later, and mark each screen or state as "available now" or "later" (see the scope table).
## What the backend does today (design against this, do not contradict it)
Routes, all behind the normal signed-in, verified-user back-office session (cookie or API key):
- GET /v1/content-type: list of types, ordered by name.
- POST /v1/content-type, PUT /v1/content-type/{key}, DELETE /v1/content-type/{key}: owner or admin only.
- GET /v1/content-type/{key}.
- GET and POST /v1/content-type/{key}/entry; GET, PUT and DELETE /v1/content-type/{key}/entry/{id}. Any verified user.
A content type: id, key, name, fields, created_at, updated_at.
- key: lowercase slug, 2 to 40 characters, unique, chosen at creation, never editable afterwards. It appears in URLs and the API.
- name: free text, up to 100 characters, editable.
- fields: ordered list, 1 to 50 fields.
A field: key, label, type, required, unique, default, min, max, options.
- key: lowercase letters, digits and underscores, starts with a letter, up to 40 characters, unique within the type. It becomes the JSON key in the API.
- label: the text shown in the editor.
- type: one of text, richtext (markdown), number, boolean, date (a calendar date, no time), select (a single choice from a list of 1 to 50 distinct options).
- required, unique (text, number, date and select only), default (applied only when an entry is created and the field is omitted), min and max.
- min and max mean: length in characters for text and richtext, value for number, earliest and latest date for date. They do not exist for boolean and select. min must not exceed max. A default must satisfy the field's own rules. A unique field cannot have a default.
- A field's type can never change after the type is saved, and the type key never changes.
An entry: id, content_type (the type's key), data (an object keyed by field key), created_by, updated_by, created_at, updated_at.
- Saving an entry replaces its whole data. Defaults apply only on create. An explicit empty value stays empty, and a required field cannot be empty.
- Unknown keys are rejected. Values of a removed field disappear.
Schema changes once entries exist:
- Removing a field is allowed; its stored values stop being returned.
- Every existing entry is re-validated against the new schema. If any entry would become invalid (a new required field without a default, a field made unique while duplicates exist, a tighter min or max below a stored value, a removed option still in use), the whole change is refused as incompatible and nothing changes.
- Adding a required field is fine if it has a default.
- A type that has entries cannot be deleted.
Entry lists are paginated: page size 5, 25, 50 or 100 (default 25), sort by id, created_at or updated_at in either direction (default most recently updated first). There is no filtering or search on custom fields yet.
Errors come back as plain text. Map each to friendly copy:
- content_type_not_found, entry_not_found
- content_type_key_taken
- content_type_has_entries
- invalid_content_type_key
- invalid_field
- schema_incompatible
- "invalid_entry: <field key>: <rule>", rule being one of required, type, min, max, options, unique, unknown_field. Unique violations arrive as HTTP 409, the other entry rules as 422.
- The usual 401, 403 (unverified account or insufficient role), 400 and 500 already covered in the system's HTTP-status-to-copy table.
## Screens to design
For each screen: every state (loading, empty, populated, error, forbidden, offline or failed save where relevant), the exact copy, the routes and their auth requirement, and a mobile layout.
### 1. Schema screen: list of types (available now)
Sits in the back-office navigation as "Schema", visible to owners and admins; other verified users do not see it. Shows the types as a list or table: name, key, number of fields, last updated. Shows the built-in types (Articles, Authors, Sites, Media, Users) in the same list with a "Built-in" badge and a lock icon. Built-ins are read-only entries here: they open a read-only view listing their fields, with no edit, no delete and no ability to add fields. Do not suggest that built-ins are custom collections; the badge and a one-line explanation make clear they are managed by RenewCMS. Primary action "New content type". States: loading, empty (no custom type yet: invite the user to create one, built-ins still listed), populated, error, forbidden (non-admin who types the URL).
### 2. Schema builder (available now, the main screen)
One screen with three regions, not three separate areas:
- Left: the ordered field list. Reorder (drag with a keyboard-accessible alternative), add field, remove field. Each row shows label, key, type icon and small badges for required and unique.
- Right: the field inspector for the selected field: label, key (generated from the label, editable until the type is first saved, then locked), type (a gallery of the six types with icon and one-line description), required, unique (disabled with an explanation where not allowed), default, min and max (with the right unit wording per type), and for select an options editor (add, remove, reorder, no duplicates, no blanks). Show the rules inline as the user types, not only after save.
- Top: type name, type key (editable only at creation; afterwards locked with a tooltip explaining why), Save and Discard.
- Live API preview: a collapsible panel showing the exact JSON an entry of this type looks like (a sample entry using each field's type and default) and the route it lives at, updating as fields change. Include a copy button.
States: new type, editing an existing type, unsaved changes, validation errors per field and at type level (inline, with the field highlighted in the list), saving, saved, save failed, key already taken, schema incompatible with existing entries.
### 3. Schema change review (available now for the review step, later for the diff)
Before saving changes to a type that already has entries, show a review step: "Add 2 fields, change 1, remove 1", listing each change, with destructive ones (removing a field, removing an option, tightening a limit, making a field unique or required) clearly flagged. Because the server decides compatibility, the review is informational plus an explicit Apply button; if the server answers schema incompatible, show a refusal state that says nothing was changed and which kind of change likely caused it (we cannot tell which entry, so write copy that does not pretend to). Also design the "delete type" confirmation: blocked when entries exist (explain that entries must be deleted first) and a plain confirmation when empty. Mark per-change entry counts and a full diff as "later" (the API does not return them yet).
### 4. Field-type gallery (available now)
A reference board for the six field types showing, for each: its icon, its inspector options, its list cell (how a value renders in the entries table, including the empty state), its form control in the entry editor (markdown editor for richtext with preview, number input with min and max hints, toggle for boolean using the system's single toggle component, date picker, select, text with a character counter when a limit exists), and its error states per rule (required, type, min, max, options, unique). Show the "filter" widget for each type as "later" since filtering on custom fields is not available yet.
### 5. Content navigation and entry list (available now)
The back-office sidebar gets a "Content" group generated from the custom types, one entry per type (name, with the type's icon if any; truncated gracefully with many types; collapsed on mobile). The list screen for a type shows a paginated table with a column per field (cap the visible columns and let the user choose which, defaulting to the first few), plus created and updated dates and the author of the last change. Sort control (id, created, updated), page size selector (5, 25, 50, 100), "New entry" button. Row click opens the editor. States: loading, empty for this type (with a hint pointing to "New entry"), populated, error, forbidden, type not found.
Use a sample "Events" type for all boards: title (text, required, unique, max 80), starts_on (date, required), ends_on (date), online (boolean, default false), capacity (number, min 1, max 5000), category (select: Talk, Workshop, Meetup), description (richtext).
### 6. Entry editor (available now)
Create and edit form generated from the schema, one control per field in schema order, with labels, required markers, helper text from min, max and options, a character counter where a limit exists, and inline errors per field. Show defaults pre-filled on create. Save, Cancel, Delete (with confirmation). Provenance footer: created by, updated by, dates. States: new, editing, unsaved changes, saving, saved, failed save, field errors for each rule, duplicate unique value (409), entry not found, concurrent schema change (a field disappeared or a new required field appeared since the form loaded: explain that the form must be reloaded).
### 7. Relation field and sentence-style relation picker (later, design now)
Relations are not built yet. Design the picker so that the model reads as sentences, not jargon: "Each Event has one Venue" and, beside it, "Each Venue has many Events", with a live preview of both sides. Offer the three relationship shapes in plain words. Show how a relation field renders in the inspector, the entry form (search and pick, with chips for many) and the list cell. Mark everything "later".
### 8. Permissions grid (later, design now)
A collection by action grid on the roles area: rows are types (custom and built-in), columns are read, create, update and delete, per role. Built-in rows are locked where the system dictates it. Make the grid usable on mobile (collapse to a per-role list). Mark "later". Today's rule is simple: owners and admins edit schema, any verified user reads and writes entries; show that as the default state of the grid.
### 9. Schema export and import (later, design now)
Export the whole schema or a single type to a file, import with a preview of what will be created or changed and the same compatibility review as screen 3, plus an explicit confirm. Aim at the dev-to-production flow. Mark "later".
## Scope table to include in your answer
For every screen and state, label it "available now" or "later" so engineering knows what is wired. Available now: screens 1 to 6 (except the diff counts), the live API preview, the type-level and field-level validation states. Later: relation picker, permissions grid, schema export and import, filters on custom fields, per-change entry counts, publish and draft state, public (anonymous) read access, activity log entries for types and entries.
## Constraints
- Nuxt UI v4 only, mapped to existing components in the inventory. List every new component you introduce with its Nuxt UI mapping and why an existing one does not fit.
- Tokens only. No raw hex values and no arbitrary Tailwind colors.
- Accessibility: keyboard reorder for fields, focus order, visible focus, labels on every control, error text tied to its input, sufficient contrast in light and dark.
- Copy: short and plain, no database jargon in primary labels (say "field", "choice list", "entry", "content type"; keep "key" for the API identifier and explain it once).
- Do not redesign existing screens. Only add what these screens need: new sidebar group, new routes, new components.
- Provide the routes table: /schema, /schema/new, /schema/:key, /content/:key, /content/:key/new, /content/:key/:id, each with its auth requirement (schema routes owner or admin, content routes any verified user).
- Anything the API cannot do today (see above) must not appear as if it works. If a design needs a backend capability that does not exist, flag it explicitly in a short "needs backend" list at the end.
+1 -1
View File
@@ -21,7 +21,7 @@ Back-office board groups: Sites, Sites: form, Sites: delete, Authors, Authors: f
- Role-restricted variants drawn: read-only Authors list and detail, hidden Sites entry, Sites 403, own-author edit.
## Pass 4: custom content types
Board `RenewCMS Screens Schema.dc.html` (frames: `SchemaFrame`, mounted in `AppFrame`): 9 groups, 65 states (56 available now, 9 later). 1 Schema list 6, 2 Schema builder 16, 3 Review and delete 7, 4 Field types 6, 5 Content and entry list 9, 6 Entry editor 13, 7 Relations 3, 8 Permissions 2, 9 Export and import 3. Plus tables: scope, routes, new components with their Nuxt UI mapping, errors to copy, needs backend (4 rows), decisions to confirm, accessibility. Specs: screens/schema.md, content.md, entry.md, schema-later.md.
Board `RenewCMS Screens Schema.dc.html` (frames: `SchemaFrame`, mounted in `AppFrame`): 11 groups, 97 states. 1 Schema list 7, 2 Schema builder 19, 3 Review and delete 9, 4 Field types 7, 5 Content and entry list 12, 6 Entry editor 23, 7 Relations 3, 8 Permissions 2, 9 Export and import 3, 10 Media picker for a field 8, 11 Media library usage 4. The Media field type (pass 5) is specified in `media-field-changes.md`; the exact copy and measurements are there, and the boards are the visual reference. Plus tables: scope, routes, new components with their Nuxt UI mapping, errors to copy, needs backend (4 rows), decisions to confirm, accessibility. Specs: screens/schema.md, content.md, entry.md, schema-later.md, media.md, media-picker.md, and media-field-changes.md for the Media field type.
- AppFrame gains a Schema item (owner and admin) and a Content group (sidebar and mobile drawer). Nothing else in AppFrame changed.
- Backend gaps still open: built-in types and fields, display names for created_by and updated_by, a type icon, per-change entry counts.
- Not done: Back-office and Prototype boards were not compared visually after the sidebar change (see Checks below).
+10
View File
@@ -121,3 +121,13 @@ Frames: `SchemaFrame.dc.html` (all schema, content and entry bodies; relation, p
| RelationField (later) | New | UInputMenu multiple | Chips and search |
| PermissionsGrid (later) | New | UTable + UCheckbox; UCard list on mobile | |
| SchemaImportDialog (later) | New | UModal + UFileUpload | |
## Media field (pass 5)
Frames: `SchemaFrame.dc.html` (`MCtl`) and `MediaFrame.dc.html` (picker in field mode, usage). Full spec: `media-field-changes.md`.
| Component | Status | Nuxt UI | Notes |
|---|---|---|---|
| MediaFieldControl | New | UFormField, UButton outline and ghost, UModal (desktop) or bottom UDrawer (mobile) for the picker, UTooltip, UIcon (image, image-off, unlink, image-plus). The thumbnail is a plain button | Props label, required, modelValue (image id or null), image (filename, width, height, size, or missing), disabled, error. Emits update:modelValue. States: empty, filled, hover, focus, error, missing, saving, read-only |
| FieldCell (media) | Extended | Thumbnail 40 px square, dash when empty, dashed square with unlink when the image is gone | Row height 48 px, mobile card thumbnail 32 px |
| MediaPicker (field mode) | Extended | Existing picker | Title "Choose an image", "Use this image", no alt text, no variant select, "Current" badge, optional "No image" row |
+121
View File
@@ -0,0 +1,121 @@
# Media field type: change list for implementation
Board: `RenewCMS Screens Schema.dc.html`. Frames changed: `SchemaFrame.dc.html`, `MediaFrame.dc.html`. Spec data: `schema-spec.js` (states) and `media-field-tables.js` (tables, appended to the board). No new tokens, no new colors, radius 0.
## 1. Behaviour
- New field type `media`, name "Media", icon `lucide:image`, description "One image from your media library".
- Stored value: id of a library image, or null. The file is never copied. The field always shows the current library image.
- Options: label, key, required. No default, unique, min, max or choices. The inspector hides them.
- Required: the entry can't be saved while the field is empty (422 invalid_entry, rule required).
- A saved field's type never changes. Key and type are locked after the first save (existing rule).
- Adding a required media field to a type with entries is refused, because a media field can't have a default. The review step shows this before the server is asked.
- Image deleted while entries point at it: the entry keeps the id. The control shows the missing state. Saving is refused only if the field is required.
- Entries count as uses of an image in Media. Deleting a used image is allowed after a warning.
- Variants: the editor preview uses the original. No variant select in the field. Nothing about variants in the builder.
- Galleries (several images) are out of scope and not drawn.
## 2. New component: MediaFieldControl
Props: label, required, modelValue (image id or null), image (filename, width, height, size, or `missing: true`), disabled, error. Emits `update:modelValue`. Opens the picker.
Nuxt UI v4: `UFormField` (label, help, error, required), `UButton` outline ("Pick an image", "Change image", "Choose another image"), `UButton` ghost ("Remove", "Clear"), `UModal` on desktop and bottom `UDrawer` on mobile for the picker, `UTooltip` for the list placeholder and the badge, `UIcon` lucide:image, image-off, unlink, image-plus. The thumbnail is a plain `button`.
States and measurements (SchemaFrame `MCtl`):
| State | Drawing |
|---|---|
| Empty | Dashed box (1px dashed `--ui-border-accented`), padding 12, 40 px icon square (`--ui-bg-elevated`), "No image selected.", button "Pick an image" (icon image-plus). Mobile: stacked, 44 px button |
| Filled | Solid 1px `--ui-border-accented` box, padding 12. Thumbnail 160 × 120 (mobile: full width, 16:9). Filename weight 500, then "1600 × 900 · 240 KB" 12/18 muted. Buttons "Change image" (outline, icon image) and "Remove" (ghost, icon x). Help line "One image from your library." |
| Hover (desktop) | Border `--ui-text-muted`. Bottom bar 28 px, `--ui-bg-inverted` with `--ui-text-inverted`, icon image 14 and "Change image". No hover on mobile |
| Focus | 2 px `--ui-primary` outline, offset 2, on the thumbnail button |
| Error | Box border `--ui-error` plus inset 1px `--ui-error`, error line with circle-alert 14: "Pick an image for Thumbnail." Focus ring on the first button (Pick an image, or Choose another image) |
| Missing | Dashed 160 × 120 (mobile 16:9) placeholder with image-off 24. Text "This image is no longer in the library" (weight 500). Help: optional "You can still save. The entry keeps the link until you change it." / required "Thumbnail is required. Choose another image to save." Buttons "Choose another image" (outline) and "Clear" (ghost) |
| Saving | Thumbnail at 60%, buttons at 40%, all form fields disabled, Save reads "Saving…" |
| Read-only (fields changed) | Same as saving, plus warning alert "The fields of Events changed" and button "Reload form" |
Label is the field label, plus " *" when required (existing form rule; "(optional)" is not used).
## 3. Per screen
### 3.1 Schema list (group 1), state "Custom type: read-only view"
Fields table of a custom type (Label, Key, Type, Rules) in the built-in table style. Thumbnail row: image icon, key `thumbnail`, type "Media", rules "One image from the library". Header "Events" with badge "Read only" (lock). Alert: "You can read these fields here" / "Only an owner or admin can change a content type." The built-in Media type in Schema is unchanged. Decision needed: no route shows a custom type read-only today.
### 3.2 Schema builder (group 2), 3 states
- "Media field selected": saved Thumbnail row selected (index 7). Inspector: Label, Key (locked, "Used in the API, so it can't change."), Type tiles (seven, Media selected, others dimmed with "Can't change after saving"), Required switch ("Required" / "An entry can't be saved with this field empty."). Hidden for media: Unique values, Default value, limits, choices. Hint (info-soft block, info icon): "Holds one image from the media library. Entries link to the image instead of keeping a copy, so they always show its current version."
- "New media field, seven types": new row with "New" badge, key editable ("The name used in the API. Starts with a letter. Lowercase letters, digits and underscores."), type tiles all enabled. State chip "Unsaved changes".
- "Media field, required": row shows the existing Required marker.
- Field row: grip, 28 px icon square (image), label, key (mono), badges. Mobile: inspector in the existing 92% sheet (title "Field: Thumbnail", footer "Done").
- Type tile grid now has seven tiles (3 columns desktop inspector, 2 in sheets).
### 3.3 Review (group 3), 2 states
Dialog "Review changes to Events" / "Apply them to save the content type." Summary "Add 1 field" / "Events has 12 entries. Each one is checked against the new fields when you apply." The info bar in the builder behind reads "12 entries use this content type…".
- Refused: row "Add Thumbnail", warning flag "Can't be applied", text "Media, required. A media field can't have a default, so the 12 existing entries would have no image. Make Thumbnail optional to add it." Note "Back to editing keeps your other changes." Buttons "Back to editing", "Apply changes" (disabled). This departs from the existing review (Apply is never disabled): decision.
- Clean: row "Add Thumbnail", "Media, optional. 12 entries are unaffected." Apply enabled.
### 3.4 Field types (group 4), state "Media"
Per-type frame like the others: header icon image, "Media", "One image from your media library", `type: "media"`. Columns: inspector options, entry form control (filled with hover, then empty), list cell (Filled thumbnail, Empty "–", Image missing), errors by rule, filter (later).
Errors by rule: required 422 "Pick an image for Thumbnail."; type 422 "Thumbnail must be an image from the library."; min, max, options, unique: "Not used for media." Filter widget: "Thumbnail: has an image" with Any / Has an image / No image, tagged Later.
### 3.5 Entry list (group 5), 3 states
Columns shown: Title, Thumbnail, Starts on, Category (user choice). Header "Thumbnail", no sort icon, column 80 px. Cell: 40 px square thumbnail; "–" when empty; dashed 40 px square with unlink icon, accessible name "Image no longer in the library", when the image is gone. Row height stays 48 px (thumbnail fits with 4 px above and below). Mobile card: 32 px thumbnail leads the card (empty: "–", missing: dashed square), card min height 68 px. Columns menu lists Thumbnail with the image icon ("4 of 6", "Choose up to 6 fields to show. 4 selected." on mobile). Tooltip on the missing placeholder (desktop): "Image no longer in the library".
### 3.6 Entry editor (group 6), 10 states
Control sits after Description, at the end of the form (schema order; see conflicts). States: empty optional, empty required, filled, hover, focus, validation error (status chip "Not saved"), image no longer in the library, missing + required (error), saving, read-only. The board scrolls the form so the control is visible in the frame; the real form is not scrolled.
### 3.7 Picker (group 10), 8 states, MediaFrame field mode
Existing picker (Upload and Library tabs, single selection, search "Search by filename", "Newest first · 48 images", Load more, 4 columns desktop and 3 on mobile, square tiles). Differences:
- Title "Choose an image".
- Primary "Use this image" (disabled until a tile is chosen). When "No image" is chosen it reads "Remove image".
- No alt text field, no variant select. Selected strip shows thumbnail, filename, "dimensions · size".
- Current image tile badge "Current" (replaces "In this article").
- Optional fields only: row "No image" / "Leave this field empty." at the top of the Library tab. Selected: sand fill, primary border, check.
- Empty: "Your library is empty" / "Images you upload appear here, ready to use in any article or entry." / "Upload an image".
- Failed: "Couldn't load your library" / "Check your connection and try again." / "Try again".
- Loading: skeleton tiles after 150 ms.
- Upload tab: unchanged flow (crop, resize); the new image lands in the library and is selected.
- Desktop dialog 640 wide, mobile bottom sheet.
### 3.8 Media library (group 11), 4 states
- Badge "Used in N" = articles + entries. The tooltip (hover or focus) reads "Used in entries: 3" and, if articles also use it, "Used in articles: 2" on the first line. Example: bathroom-tiles.png, 3 entries, "Used in 3".
- List view: same badge in the list row and mobile card.
- Detail panel (lime-plaster.jpg, 2 articles, 5 entries): preview is shorter when the image has entries; existing "Used in 2 articles" list; new section "Used in entries" with up to 3 rows (type name muted, entry title as link, arrow-up-right) and "and 2 more". When there are entries the empty-articles line reads "No article shows it." (not "safe to delete").
- Delete: title "Delete an image that's in use?" (existing in-use dialog), body `"lime-plaster.jpg" is used in 5 entries and 2 articles. Those entry fields will show "This image is no longer in the library", and the articles will show a broken image. This can't be undone.` with the entries and articles lists; "Cancel" and destructive "Delete image".
## 4. Copy added (exact)
Media · One image from your media library · Holds one image from the media library. Entries link to the image instead of keeping a copy, so they always show its current version. · No image selected. · Pick an image · Change image · Remove · Choose another image · Clear · One image from your library. · This image is no longer in the library · You can still save. The entry keeps the link until you change it. · Thumbnail is required. Choose another image to save. · Pick an image for Thumbnail. · Thumbnail must be an image from the library. · Not used for media. · Image no longer in the library · Choose an image · Use this image · Remove image · Current · No image · Leave this field empty. · Used in entries · and 2 more · Used in entries: 3 · Can't be applied · Media, required. A media field can't have a default, so the 12 existing entries would have no image. Make Thumbnail optional to add it. · Media, optional. 12 entries are unaffected. · The Thumbnail field was changed after you opened this form. Reload the form to continue. What you typed here can't be saved against the old fields.
Sentence case, "image" never "asset", buttons are verbs.
## 5. API and backend
- Schema API accepts type `media` with label, key, required. Value: image id or null.
- 422 invalid_entry: required → "Pick an image for Thumbnail."; type (id not in the library on a changed value) → "Thumbnail must be an image from the library."
- Entry and list responses include, per media field, filename, width, height, size and a thumbnail URL, or `missing: true`.
- GET /v1/media/{id}/usage returns articles and entries (content type name, key, entry id, title), a total and the first few items. GET /v1/media/ list items carry the combined use count.
- DELETE /v1/media/{id} stays allowed for used images. Entries keep the id.
- A new required media field on a type with entries is refused (schema_incompatible). The client shows the refusal first.
HTTP to copy (picker and field), from states.md: 400 "That request wasn't valid. Check the fields and try again."; 401/403 global; 404 "That item no longer exists."; 409 "This changed somewhere else. Reload and try again."; 413 "That file is too large."; 429 "Too many requests. Try again in a few minutes."; 500/network "Something went wrong on our side. Nothing was changed. Try again in a moment."
## 6. Accessibility
- Control is `role="group"` labelled by the field label. Required: `aria-required` on the main button.
- Names: "Pick an image for Thumbnail"; thumbnail "Change image, lime-plaster-workshop.jpg, 1600 by 900, 240 KB"; "Remove image from Thumbnail"; "Clear Thumbnail"; missing placeholder `role="img"` "Image no longer in the library".
- Error: error text has an id. The main button gets `aria-invalid="true"` and `aria-describedby` (error id, then help id). Focus moves to the first invalid control on a refused save.
- Order: label, thumbnail, Change image, Remove, help or error. The thumbnail duplicates Change image; use `tabindex="-1"` on it if one stop is preferred.
- One polite live region: "Image selected: lime-plaster-workshop.jpg", "Image removed from Thumbnail.", "Thumbnail cleared."
- Focus: Use this image → Change image. Remove or Clear → Pick an image. Cancel or Esc → the opener.
- Picker: tiles are buttons with `aria-pressed`, names "stone-steps.jpg, 310 KB, Current". "No image" has `aria-pressed`. "Use this image" uses `aria-disabled`.
- Contrast: Current badge and selected rows use `--rc-on-sand`; hover bar 18.9 (inverted pair). 44 px targets on mobile. No hover on mobile.
## 7. Conflicts to decide
1. Row height: design is 48 px (56 px media rows, 68 px cards), not 32 px. Drawn at 48 and 68.
2. Thumbnail position: existing form has Description last. Drawn after Description (end of form).
3. "Used in N" counted articles. Now articles + entries.
4. Delete title: existing in-use title kept; "Delete this image?" stays for unused images.
5. "Clear" vs glossary "Remove".
6. "1600 × 900 · 240 KB" (design separator) instead of "1600 x 900 - 240 KB".
7. Review step disables Apply for the certain refusal; existing review never does.
8. Picker button "Use this image" vs article picker "Insert image"; "Remove image" when No image is chosen is my addition.
9. "Pick an image" also on optional empty fields.
10. No read-only route for custom types.
11. Two tab stops for the same picker (thumbnail and Change image).
12. Disabled opacity: form 60%, foundations 40%.
13. The picker frame shows a stand-in entry form, not the real editor.
## 8. Not done
README.md, states.md and the screens/*.md files are not updated with the new counts (group 2 +3, 3 +2, 4 +1, 5 +3, 6 +10, 1 +1, new groups 10 (8) and 11 (4): 32 states). Light/dark and mobile frames were checked by reading the DOM, not state by state on screen.
+3
View File
@@ -21,3 +21,6 @@ The sidebar gets a "Content" group, one item per custom type (a default icon: ty
| 7 | Error | 500 or network failure. | Couldn't load entries · GET /v1/content-type/events/entry failed. Check your connection and try again. · Try again | Available now |
| 8 | Forbidden (403) | The API answers 403. Unverified accounts are redirected to /register/pending before this. | You don't have access to Events · Your account can't open this content right now. If you think this is a mistake, ask an owner or an admin. · Go to Home | Available now |
| 9 | Type not found | 404 content_type_not_found on /content/unknown. | Content type not found · It may have been deleted, or the address may be mistyped. · Go to Home | Available now |
## Media field (pass 5)
Spec, states, exact copy, measurements, backend needs and accessibility: `media-field-changes.md`, section 3.5. Board groups: 5 Content and entry list.
+3
View File
@@ -25,3 +25,6 @@ The form is generated from the schema, one control per field in schema order. Re
| 11 | Entry not found | 404 entry_not_found, for example after a delete elsewhere. | Entry not found · It may have been deleted by someone else. · Back to Events | Available now |
| 12 | Schema changed since load | 422 invalid_entry: room: required, or unknown_field. The form is read-only until reloaded. | The fields of Events changed · A field was removed and a new required field, Room, was added after you opened this form. Reload the form to continue. What you typed here can't be saved against the old fields. · Reload form | Available now |
| 13 | Delete entry: confirm | Delete. | Delete this entry? · "Lime plaster workshop" will be deleted from Events. This can't be undone. · Cancel · Delete entry | Available now |
## Media field (pass 5)
Spec, states, exact copy, measurements, backend needs and accessibility: `media-field-changes.md`, section 3.6. Board groups: 6 Entry editor.
+3
View File
@@ -45,3 +45,6 @@ The Library tab of the picker gets a Variant select. Options are Original plus t
| 3 | No variants defined | Only Original is offered. | "Articles" / "How we price a bathroom renovation" / "Edit article" |
| 4 | Variant deleted | The block keeps its URL. Pick another variant opens the select. | "Articles" / "How we price a bathroom renovation" / "Edit article" / "Variant 'hero' no longer exists." |
| 5 | Variant disabled | Same block, different cause. Proposed copy. | "Articles" / "How we price a bathroom renovation" / "Edit article" / "Variant 'hero' is disabled." |
## Media field (pass 5)
Spec, states, exact copy, measurements, backend needs and accessibility: `media-field-changes.md`, section 3.7. Board groups: 10 Media picker for a field.
+3
View File
@@ -113,3 +113,6 @@ A secondary "Purge duplicates" button (icon merge) in the toolbar next to the so
|---|---|---|---|
| 1 | Duplicates tab with the button | Owner or admin. | |
| 2 | Duplicates tab: offline | The button is disabled with the existing banner. | |
## Media field (pass 5)
Spec, states, exact copy, measurements, backend needs and accessibility: `media-field-changes.md`, section 3.8. Board groups: 11 Media library usage.
+3
View File
@@ -76,3 +76,6 @@ One frame per type: inspector options, the entry form control (default and open
| 4 | Yes or no | type: "boolean" | Yes or no · An on or off switch · On by default · Yes or no fields have no limits. · Not available for yes or no fields. (Unique) · Choose yes or no for Online. · Online must be yes or no. | Available now |
| 5 | Date | type: "date" | Date · A calendar day, without a time · Earliest date · Latest date · Pick a date · Pick a date for Starts on. · Starts on must be a date, like 2026-11-21. · Starts on can't be before 1 Jan 2026. · Starts on can't be after 31 Dec 2027. | Available now |
| 6 | Choice | type: "select" | Choice · One option from a list you define · Choices · Choose an option · Choose one of: Talk, Workshop or Meetup. · Another entry already uses this choice for Category. | Available now |
## Media field (pass 5)
Spec, states, exact copy, measurements, backend needs and accessibility: `media-field-changes.md`, section 3.1 to 3.4. Board groups: 1 Schema list, 2 Schema builder, 3 Review, 4 Field types.
+20 -13
View File
@@ -53,6 +53,8 @@ class Component extends DCLogic {
]
const VC = { 1: 4, 2: 5, 3: 5, 4: 0, 5: 3, 6: 0, 7: 2, 8: 0, 9: 1, 10: 3, 11: 4, 12: 5 }
IM.forEach(x => { x.vc = VC[x.id] || 0 })
const ENT = { 10: 3, 11: 5 }
IM.forEach(x => { x.ent = s.ent ? (ENT[x.id] || 0) : 0 })
const byId = id => IM.find(x => x.id === id)
const AR = [['How we price a bathroom renovation', 1], ['Winter checklist for timber windows', 0], ['Before and after: the Rue Verte kitchen', 1], ['Why we reuse original floorboards', 1], ['Choosing lime plaster for old stone walls', 0]]
const usedList = n => AR.slice(0, Math.min(n, 5))
@@ -60,8 +62,8 @@ class Component extends DCLogic {
const imgs = ids.map(byId)
const sel = s.sel || []
const pl = n => n + (n === 1 ? ' article' : ' articles')
const label = im => im.n + ', ' + im.sz + ', ' + (im.used ? 'used in ' + pl(im.used) : 'unused')
const usedBadge = im => im.used ? Bd('Used in ' + im.used, 'used') : Bd('Unused', 'unused')
const label = im => im.n + ', ' + im.sz + ', ' + (im.used + im.ent ? 'used in ' + [im.used && pl(im.used), im.ent && (im.ent + (im.ent === 1 ? ' entry' : ' entries'))].filter(Boolean).join(' and ') : 'unused')
const usedBadge = im => { const n = im.used + im.ent, b = n ? Bd('Used in ' + n, 'used') : Bd('Unused', 'unused'); return s.tip === im.id ? S('position:relative;display:inline-flex', b, D('position:absolute;left:0;top:26px;z-index:10;padding:6px 8px;background:var(--ui-bg-inverted);color:var(--ui-text-inverted);font-size:12px;line-height:18px;white-space:nowrap;box-shadow:var(--rc-shadow-pop)', im.used > 0 && D('', 'Used in articles: ' + im.used), D('', 'Used in entries: ' + im.ent))) : b }
// ---------- Media page pieces
const Card = im => {
@@ -196,6 +198,8 @@ class Component extends DCLogic {
const BulkBar = () => D('position:absolute;z-index:30;bottom:' + (m ? 16 : 24) + 'px;' + (m ? 'left:16px;right:16px' : 'left:calc(224px + (100% - 224px) / 2);transform:translateX(-50%);width:400px') + ';display:flex;align-items:center;gap:8px;padding:8px 8px 8px 16px;background:var(--ui-bg-inverted);color:var(--ui-text-inverted);box-shadow:var(--rc-shadow-pop)', S('flex:1;font-weight:500', sel.length + ' selected'), B('Delete', { k: 'danger', icon: 'trash-2' }), B('Clear', { k: 'inv' }))
// ---------- detail panel
const ENTL = [['Events', 'Lime plaster workshop'], ['Events', 'Heritage stone walk'], ['Events', 'Winter open day']]
const EntBox = im => D('display:flex;flex-direction:column;gap:8px', S('font:600 14px/22px \'IBM Plex Sans\',sans-serif;color:var(--ui-text-highlighted)', 'Used in entries'), D('border:1px solid var(--ui-border)', ...ENTL.map(([ty, tt], i) => D('display:flex;align-items:center;gap:8px;min-height:' + (m ? 48 : 36) + 'px;padding:0 12px;border-top:' + (i ? '1px solid var(--ui-border-muted)' : '0'), S('width:52px;flex-shrink:0;font-size:12px;color:var(--ui-text-muted)', ty), S('flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-weight:500;text-decoration:underline;text-underline-offset:3px;color:var(--ui-text-highlighted)', tt), I('arrow-up-right', 14, 'color:var(--ui-text-muted)'))), im.ent > 3 && D('padding:8px 12px;border-top:1px solid var(--ui-border-muted);color:var(--ui-text-muted)', 'and ' + (im.ent - 3) + ' more')))
const Panel = () => {
const im = byId(s.panel.id), list = usedList(im.used)
const meta = [['Type', im.ty], ['Size', im.sz], ['Dimensions', im.dim], ['Uploaded', im.d], ['Uploaded by', im.by]]
@@ -204,14 +208,14 @@ class Component extends DCLogic {
D('width:' + w + ';height:100%;background:var(--ui-bg);display:flex;flex-direction:column;' + (m ? '' : 'box-shadow:var(--rc-shadow-modal)'),
D('height:' + (m ? 56 : 56) + 'px;flex-shrink:0;display:flex;align-items:center;gap:' + (m ? 4 : 12) + 'px;padding:0 ' + (m ? 6 : 20) + 'px;border-bottom:1px solid var(--ui-border)', m && S('width:44px;height:44px;display:flex;align-items:center;justify-content:center', I('arrow-left', 20)), S('flex:1;min-width:0;font:600 16px/24px \'IBM Plex Sans\',sans-serif;color:var(--ui-text-highlighted);overflow:hidden;text-overflow:ellipsis;white-space:nowrap', im.n), !m && S('width:28px;height:28px;display:flex;align-items:center;justify-content:center;color:var(--ui-text-muted)', I('x'))),
D('flex:1;min-height:0;overflow:hidden;padding:' + (m ? 16 : 20) + 'px;display:flex;flex-direction:column;gap:20px',
Th(im, 'aspect-ratio:' + (m ? '4/3' : '16/10') + ';border:1px solid var(--ui-border);flex-shrink:0', 40),
Th(im, 'aspect-ratio:' + (im.ent ? (m ? '16/3.6' : '16/6') : m ? '4/3' : '16/10') + ';border:1px solid var(--ui-border);flex-shrink:0', 40),
D('display:flex;gap:8px;' + (m ? 'flex-wrap:wrap' : ''), B('Copy URL', { icon: 'link', full: m }), B('Rename', { icon: 'pencil', full: m }), B('Delete', { k: 'del', icon: 'trash-2', full: m })),
im.dup && Alert('info', 'copy', 'Identical to 2 other images', 'floorboards-copy.jpg and IMG_2208.jpg have the same content.', 'Review duplicates', { icon: 'arrow-right' }),
D('display:grid;grid-template-columns:110px minmax(0,1fr);gap:8px 12px;color:var(--ui-text-toned)', ...meta.flatMap(([k, v]) => [S('color:var(--ui-text-muted)', k), S('color:var(--ui-text-highlighted)', v)]), S('color:var(--ui-text-muted)', 'URL'), S('font:400 12px/20px \'IBM Plex Mono\',monospace;color:var(--ui-text-highlighted);overflow:hidden;text-overflow:ellipsis;white-space:nowrap', 'cms.renew.example/media/' + im.n)),
D('display:flex;flex-direction:column;gap:8px', S('font:600 14px/22px \'IBM Plex Sans\',sans-serif;color:var(--ui-text-highlighted)', im.used ? 'Used in ' + pl(im.used) : 'Not used in any article'),
im.used ? D('border:1px solid var(--ui-border)', ...list.map(([t, on], i) => D('display:flex;align-items:center;gap:8px;min-height:' + (m ? 48 : 40) + 'px;padding:0 12px;border-top:' + (i ? '1px solid var(--ui-border-muted)' : '0'), S('flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-weight:500;text-decoration:underline;text-underline-offset:3px;color:var(--ui-text-highlighted)', t), on ? Bd('Online', 'on', 22) : Bd('Draft', 'draft', 22), I('arrow-up-right', 14, 'color:var(--ui-text-muted)'))))
: S('color:var(--ui-text-muted)', 'This image is safe to delete. No article shows it.'),
im.used ? S('color:var(--ui-text-muted);font-size:12px', 'Counted from the text of your articles each time you open this page.') : null))))
: S('color:var(--ui-text-muted)', im.ent ? 'No article shows it.' : 'This image is safe to delete. No article shows it.'),
im.used ? S('color:var(--ui-text-muted);font-size:12px', 'Counted from the text of your articles each time you open this page.') : null), im.ent > 0 && EntBox(im))))
}
// ---------- modal
@@ -221,6 +225,7 @@ class Component extends DCLogic {
const md = s.modal, k = md.k
if (k === 'rename') return { title: 'Rename image', desc: 'Only the filename changes. The URL stays the same, so articles that use this image keep working.', body: [Field('Filename', md.err ? '' : md.val || 'north-wall', { val: !md.err, suffix: '.jpg', focus: !md.loading, err: md.err, dis: md.loading, help: md.err ? '' : 'Letters, numbers, dashes and underscores. The .jpg ending stays.' })], cancel: 'Cancel', confirm: md.loading ? 'Renaming…' : 'Rename' }
if (k === 'del') return { title: 'Delete this image?', desc: '"window-frame.jpg" will be deleted from your library. No article uses it. This can\'t be undone.', cancel: 'Cancel', confirm: md.loading ? 'Deleting…' : 'Delete image', tone: 'danger' }
if (k === 'delEnt') return { title: 'Delete an image that\'s in use?', desc: '"lime-plaster.jpg" is used in 5 entries and 2 articles. Those entry fields will show "This image is no longer in the library", and the articles will show a broken image. This can\'t be undone.', body: [EntBox(byId(11)), ArtBox(usedList(2))], cancel: 'Cancel', confirm: 'Delete image', tone: 'danger' }
if (k === 'delUsed') return { title: 'Delete an image that\'s in use?', desc: '"north-wall.jpg" is used in 2 articles. If you delete it, they will show a broken image. This can\'t be undone.', body: [ArtBox(usedList(2))], cancel: 'Cancel', confirm: md.loading ? 'Deleting…' : 'Delete image', tone: 'danger' }
if (k === 'bulk') return { title: 'Delete 3 images?', desc: '2 of them are used in 5 articles, which will show a broken image. The other one isn\'t used anywhere. This can\'t be undone.', body: [D('display:flex;flex-direction:column;border:1px solid var(--ui-border)', ...[['north-wall.jpg', 'Used in 2'], ['kitchen-after.webp', 'Used in 3'], ['window-frame.jpg', 'Unused']].map(([n, u], i) => D('display:flex;align-items:center;gap:8px;min-height:36px;padding:0 12px;border-top:' + (i ? '1px solid var(--ui-border-muted)' : '0'), S('flex:1;color:var(--ui-text-highlighted);overflow:hidden;text-overflow:ellipsis;white-space:nowrap', n), Bd(u === 'Unused' ? 'Unused' : u, u === 'Unused' ? 'unused' : 'used'))))], cancel: 'Cancel', confirm: md.loading ? 'Deleting…' : 'Delete 3 images', tone: 'danger' }
if (k === 'merge') return { title: 'Merge into floorboards.jpg?', desc: 'Articles that use the other 2 copies will be switched to floorboards.jpg, and the other 2 copies will be deleted. 5 articles will be updated. This can\'t be undone.', body: [D('display:flex;gap:12px;align-items:center;border:1px solid var(--ui-border);padding:10px 12px', Th(byId(12), 'width:56px;height:42px;flex-shrink:0;border:1px solid var(--ui-border)', 16), D('display:flex;flex-direction:column;min-width:0', S('font-weight:500;color:var(--ui-text-highlighted)', 'floorboards.jpg'), S('font-size:12px;color:var(--ui-text-muted)', 'Kept · used in 4 articles now')))], cancel: 'Cancel', confirm: md.loading ? 'Merging…' : 'Merge 2 copies', tone: 'danger' }
@@ -245,6 +250,7 @@ class Component extends DCLogic {
S('display:block', 'A bathroom is priced by what has to happen behind the walls before anything gets tiled.'),
s.inArticle && D('position:relative;aspect-ratio:16/9;border:1px solid var(--ui-border);overflow:hidden', Th(byId(1), 'position:absolute;inset:0', 40), S('position:absolute;top:8px;right:8px;height:28px;padding:0 10px;display:flex;align-items:center;gap:6px;background:var(--ui-bg);border:1px solid var(--ui-border-accented);color:var(--ui-text-highlighted);font:500 12px \'IBM Plex Sans\',sans-serif', I('trash-2', 14), 'Remove image')),
S('display:block', 'We don\'t add a margin on materials you choose yourself.'))))
const FEditor = () => D('flex:1;min-height:0;overflow:hidden;background:var(--ui-bg-muted);display:flex;flex-direction:column', D('background:var(--ui-bg);border-bottom:1px solid var(--ui-border);padding:12px ' + (m ? 16 : 24) + 'px;display:flex;align-items:center;gap:12px', S('flex:1;font:600 ' + (m ? 16 : 20) + 'px/28px \'IBM Plex Sans\',sans-serif;color:var(--ui-text-highlighted)', 'Lime plaster workshop'), !m && B('Cancel'), !m && B('Save', { k: 'primary' })), D('padding:' + (m ? 16 : 24) + 'px;display:flex;flex-direction:column;gap:16px;max-width:760px', D('background:var(--ui-bg);border:1px solid var(--ui-border);padding:16px;display:flex;flex-direction:column;gap:12px', S('font-weight:500', 'Title'), D('height:32px;border:1px solid var(--ui-border-accented);display:flex;align-items:center;padding:0 10px', 'Lime plaster workshop'), S('font-weight:500', 'Thumbnail'), D('height:120px;border:1px solid var(--ui-border-accented);background:var(--ui-bg)'))))
const PT = s.pk || {}
const pImgs = (PT.ids || [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]).map(byId)
const inArt = [1, 4]
@@ -252,7 +258,7 @@ class Component extends DCLogic {
const PTile = im => {
const on = PT.sel === im.id
return D('display:flex;flex-direction:column;gap:6px;min-width:0', D('position:relative;' + (on ? 'outline:2px solid var(--ui-primary);outline-offset:2px;' : ''), Th(im, 'aspect-ratio:1/1;border:1px solid var(--ui-border)', 20),
inArt.includes(im.id) && S('position:absolute;left:4px;bottom:4px;height:18px;padding:0 5px;display:flex;align-items:center;background:var(--rc-sand);color:var(--rc-on-sand);font-size:11px;font-weight:500', 'In this article'),
(s.field ? im.id === PT.cur : inArt.includes(im.id)) && S('position:absolute;left:4px;bottom:4px;height:18px;padding:0 5px;display:flex;align-items:center;background:var(--rc-sand);color:var(--rc-on-sand);font-size:11px;font-weight:500', s.field ? 'Current' : 'In this article'),
on && S('position:absolute;top:4px;right:4px;width:20px;height:20px;display:flex;align-items:center;justify-content:center;background:var(--ui-primary);color:var(--ui-bg)', I('check', 14))),
S('font-size:12px;color:var(--ui-text-toned);overflow:hidden;text-overflow:ellipsis;white-space:nowrap', im.n))
}
@@ -267,35 +273,36 @@ class Component extends DCLogic {
}
const kids = []
kids.push(D('height:' + (m ? 44 : 32) + 'px;padding:0 4px 0 10px;display:flex;align-items:center;gap:8px;border:1px solid var(--ui-border-accented);background:var(--ui-bg);color:' + (PT.q ? 'var(--ui-text-highlighted)' : 'var(--ui-text-muted)') + (m ? ';font-size:16px' : ''), I('search', 14), S('flex:1', PT.q || 'Search by filename'), PT.q && S('width:24px;height:24px;display:flex;align-items:center;justify-content:center;color:var(--ui-text-muted)', I('x', 14))))
if (s.field && !PT.req && !PT.error && !PT.empty && !PT.loading) { const on = PT.sel === 'none'; kids.push(D('display:flex;align-items:center;gap:10px;min-height:' + (m ? 48 : 40) + 'px;padding:0 12px;border:1px solid ' + (on ? 'var(--ui-primary)' : 'var(--ui-border-accented)') + ';background:' + (on ? 'var(--rc-sand)' : 'var(--ui-bg)') + ';color:' + (on ? 'var(--rc-on-sand)' : 'var(--ui-text-highlighted)'), I('image-off', 16), S('font-weight:500', 'No image'), S('flex:1;color:' + (on ? 'var(--rc-on-sand)' : 'var(--ui-text-muted)'), 'Leave this field empty.'), on && I('check', 16))) }
if (PT.error) kids.push(Alert('error', 'circle-x', 'Couldn\'t load your library', 'Check your connection and try again.', 'Try again'))
else if (PT.empty === 'first') kids.push(Empty('images', 'Your library is empty', 'Images you upload appear here, ready to use in any article.', 'Upload an image', true, 32))
else if (PT.empty === 'first') kids.push(Empty('images', 'Your library is empty', s.field ? 'Images you upload appear here, ready to use in any article or entry.' : 'Images you upload appear here, ready to use in any article.', 'Upload an image', true, 32))
else if (PT.empty === 'search') kids.push(Empty('search', 'No images match "wall"', 'Check the spelling, or search for a shorter part of the filename.', 'Clear search', false, 32))
else if (PT.loading) kids.push(PSkel())
else {
kids.push(S('color:var(--ui-text-muted);font-size:12px', 'Newest first · 48 images'), D('min-height:0;overflow:hidden;' + (PT.sel ? 'max-height:' + (m ? 120 : 190) + 'px' : 'max-height:' + (m ? 300 : 300) + 'px'), PGrid()))
if (!PT.sel) kids.push(D('display:flex;justify-content:center', B(PT.more ? 'Loading…' : 'Load more', { icon: PT.more ? 'loader-circle' : null, dis: !!PT.more })))
}
if (PT.sel) { const im = byId(PT.sel); kids.push(D('display:flex;flex-direction:column;gap:12px;padding-top:12px;border-top:1px solid var(--ui-border)', D('display:flex;gap:12px;align-items:center', Th(im, 'width:56px;height:56px;flex-shrink:0;border:1px solid var(--ui-border)', 16), D('display:flex;flex-direction:column;min-width:0', S('font-weight:500;color:var(--ui-text-highlighted)', im.n), S('font-size:12px;color:var(--ui-text-muted)', im.dim + ' · ' + im.sz))), Field('Alt text (optional)', PT.alt || 'e.g. North wall of the kitchen before plastering', { val: !!PT.alt, focus: !!PT.alt, help: 'Describes the image for people who use a screen reader, and shows if it doesn\'t load. Leave it empty if the image is only decoration.' }))) }
if (PT.sel && PT.sel !== 'none') { const im = byId(PT.sel); kids.push(D('display:flex;flex-direction:column;gap:12px;padding-top:12px;border-top:1px solid var(--ui-border)', D('display:flex;gap:12px;align-items:center', Th(im, 'width:56px;height:56px;flex-shrink:0;border:1px solid var(--ui-border)', 16), D('display:flex;flex-direction:column;min-width:0', S('font-weight:500;color:var(--ui-text-highlighted)', im.n), S('font-size:12px;color:var(--ui-text-muted)', im.dim + ' · ' + im.sz))), !s.field && Field('Alt text (optional)', PT.alt || 'e.g. North wall of the kitchen before plastering', { val: !!PT.alt, focus: !!PT.alt, help: 'Describes the image for people who use a screen reader, and shows if it doesn\'t load. Leave it empty if the image is only decoration.' }))) }
return D('display:flex;flex-direction:column;gap:12px', ...kids)
}
const Picker = () => {
const ins = PT.tab === 'Library'
return Shell({ title: 'Add an image', close: true, w: 640, top: 40, cancel: 'Cancel', confirm: ins ? 'Insert image' : null, cdis: ins && !PT.sel }, D('display:flex;flex-direction:column;min-height:0;flex:1', PTabs(), D('padding:16px 24px 0;min-height:0;overflow:hidden;display:flex;flex-direction:column', PBody())))
return Shell({ title: s.field ? 'Choose an image' : 'Add an image', close: true, w: 640, top: 40, cancel: 'Cancel', confirm: ins ? (s.field ? (PT.sel === 'none' ? 'Remove image' : 'Use this image') : 'Insert image') : null, cdis: ins && !PT.sel }, D('display:flex;flex-direction:column;min-height:0;flex:1', PTabs(), D('padding:16px 24px 0;min-height:0;overflow:hidden;display:flex;flex-direction:column', PBody())))
}
// ---------- shell
const isPicker = s.kind === 'picker'
const navKey = isPicker ? 'articles' : 'media'
const crumbs = isPicker ? ['Articles', 'How we price a bathroom renovation'] : ['Media']
const navKey = isPicker ? (s.field ? 'content' : 'articles') : 'media'
const crumbs = isPicker ? (s.field ? ['Content', 'Events', 'Lime plaster workshop'] : ['Articles', 'How we price a bathroom renovation']) : ['Media']
const offline = s.offline && D('flex-shrink:0;display:flex;align-items:center;gap:10px;padding:10px 16px;background:var(--ui-bg-inverted);color:var(--ui-text-inverted)', I('wifi-off'), S('flex:1', 'You\'re offline. You can look through the images that are loaded, but uploading, renaming and deleting need a connection.'))
const pad = m ? 16 : 24
const content = isPicker ? Editor() : D('flex:1;min-height:0;overflow:hidden;padding:' + pad + 'px;display:flex;flex-direction:column;gap:16px;position:relative', Header(), ...pageBody())
const content = isPicker ? (s.field ? FEditor() : Editor()) : D('flex:1;min-height:0;overflow:hidden;padding:' + pad + 'px;display:flex;flex-direction:column;gap:16px;position:relative', Header(), ...pageBody())
const dragOv = s.drag && D('position:absolute;z-index:35;inset:' + (m ? 8 : 12) + 'px;top:' + (m ? 64 : 60) + 'px;border:2px dashed var(--ui-primary);background:var(--rc-sand);color:var(--rc-on-sand);display:flex;flex-direction:column;align-items:center;justify-content:center;gap:8px;text-align:center', I('upload', 28), S('font-weight:600;font-size:16px', 'Drop images to upload'), S('color:var(--rc-on-sand)', 'PNG, JPEG, WEBP, SVG · max 10 MB each'))
const fab = m && !isPicker && !(sel.length) && !s.panel && !s.modal && !s.error && s.empty !== 'first' && !s.drag && D('position:absolute;left:16px;right:16px;bottom:16px;height:48px;display:flex;align-items:center;justify-content:center;gap:8px;background:var(--ui-primary);color:var(--ui-bg);font-weight:500;font-size:15px;box-shadow:var(--rc-shadow-pop);opacity:' + (s.limited || s.offline ? 0.4 : 1), I(s.limited ? 'timer' : 'upload', 18), s.limited ? 'Try again in 0:42' : 'Upload')
const ann = s.ann && D('position:absolute;z-index:20;' + (m ? 'left:16px;bottom:24px' : 'left:248px;bottom:20px'), Note(s.ann))
const main = D('flex:1;min-width:0;min-height:0;display:flex;flex-direction:column', offline, content)
const ov = D('display:contents', dragOv, fab, ann, sel.length > 0 && !s.panel && !s.modal && BulkBar(), s.panel && Panel(), isPicker && s.picker && Picker(), s.modal && Modal(), s.toasts && Toasts())
const shell = { kind: 'slot', display: 'Marta Alves', nav: navKey, crumbs, mTitle: isPicker ? 'Edit article' : 'Media', mLead: isPicker ? 'arrow-left' : undefined, mAction: isPicker ? 'ellipsis' : undefined }
const shell = { kind: 'slot', display: 'Marta Alves', nav: navKey, crumbs, mTitle: isPicker ? (s.field ? 'Lime plaster workshop' : 'Edit article') : 'Media', mLead: isPicker ? 'arrow-left' : undefined, mAction: isPicker ? 'ellipsis' : undefined, ...(s.field ? { content: [{ key: 'events', name: 'Events', icon: 'files' }, { key: 'recipes', name: 'Recipes', icon: 'files' }, { key: 'press-mentions', name: 'Press mentions', icon: 'files' }], contentOn: 'events' } : {}) }
return { shell, mob: m, main, ov }
}
}
@@ -17,7 +17,7 @@
<div style="display:flex;align-items:flex-end;gap:32px;max-width:1400px">
<div style="flex:1;display:flex;flex-direction:column;gap:10px">
<h1 style="margin:0;font:600 36px/44px 'IBM Plex Sans',sans-serif;letter-spacing:-0.02em;color:var(--ui-text-highlighted)">Screens: custom content types</h1>
<p style="margin:0;max-width:900px;font-size:16px;line-height:26px;color:var(--ui-text-toned);text-wrap:pretty">Schema list, builder, change review, field-type gallery, content navigation, entry list and entry editor, plus the later screens: relations, permissions, export and import. Every state at 1440 px (shown at 50%) and 390 px (shown at 75%); the switch shows dark. Each state is tagged <b>Available now</b> or <b>Later</b>. Spec tables at the end: scope, routes, components with their Nuxt UI mapping, errors, needs backend, decisions, accessibility. Same shell, tokens and copy tone as <a href="RenewCMS Screens Back-office.dc.html">the back-office board</a>. Changed in AppFrame: a Schema item and a Content group in the sidebar and the mobile drawer.</p>
<p style="margin:0;max-width:900px;font-size:16px;line-height:26px;color:var(--ui-text-toned);text-wrap:pretty">Schema list, builder, change review, field-type gallery, content navigation, entry list and entry editor, plus the later screens: relations, permissions, export and import. Every state at 1440 px (shown at 50%) and 390 px (shown at 75%); the switch shows dark. Each state is tagged <b>Available now</b> or <b>Later</b>. Spec tables at the end: scope, routes, components with their Nuxt UI mapping, errors, needs backend, decisions, accessibility. Same shell, tokens and copy tone as <a href="RenewCMS Screens Back-office.dc.html">the back-office board</a>. New field type Media (one library image) is drawn inside groups 1 to 6, plus groups 10 (picker) and 11 (media library usage), and the tables "Media field: …" at the end. Changed in AppFrame: a Schema item and a Content group in the sidebar and the mobile drawer.</p>
</div>
<div role="radiogroup" aria-label="Theme" style="display:flex;border:1px solid var(--ui-border-accented);background:var(--ui-bg)">
<sc-for list="{{ modes }}" as="m" hint-placeholder-count="3">
@@ -37,8 +37,8 @@
<div style="display:flex;flex-direction:column;gap:12px;width:1037px">
<div style="display:flex;flex-direction:column;gap:2px"><span style="font:600 16px/24px 'IBM Plex Sans',sans-serif;color:var(--ui-text-highlighted)">{{ st.name }}<span style="margin-left:10px;padding:1px 6px;border:{{ st.chipBd }};color:var(--ui-text-toned);font:500 11px/16px 'IBM Plex Mono',monospace;vertical-align:middle">{{ st.scopeLabel }}</span></span><span style="font-size:13px;color:var(--ui-text-muted)">{{ st.trigger }}</span></div>
<div style="display:flex;gap:24px;align-items:flex-start">
<div style="width:720px;height:450px;overflow:hidden;border:1px solid var(--ui-border);flex-shrink:0"><div style="width:1440px;height:900px;zoom:0.5"><dc-import name="SchemaFrame" s="{{ st.s }}" mobile="{{ false }}" hint-size="1440px,900px"></dc-import></div></div>
<div style="width:293px;height:633px;overflow:hidden;border:1px solid var(--ui-border);flex-shrink:0"><div style="width:390px;height:844px;zoom:0.75"><dc-import name="SchemaFrame" s="{{ st.s }}" mobile="{{ true }}" hint-size="390px,844px"></dc-import></div></div>
<div style="width:720px;height:450px;overflow:hidden;border:1px solid var(--ui-border);flex-shrink:0"><div style="width:1440px;height:900px;zoom:0.5"><sc-if value="{{ st.isSchema }}"><dc-import name="SchemaFrame" s="{{ st.s }}" mobile="{{ false }}" hint-size="1440px,900px"></dc-import></sc-if><sc-if value="{{ st.isMedia }}"><dc-import name="MediaFrame" s="{{ st.s }}" mobile="{{ false }}" hint-size="1440px,900px"></dc-import></sc-if></div></div>
<div style="width:293px;height:633px;overflow:hidden;border:1px solid var(--ui-border);flex-shrink:0"><div style="width:390px;height:844px;zoom:0.75"><sc-if value="{{ st.isSchema }}"><dc-import name="SchemaFrame" s="{{ st.s }}" mobile="{{ true }}" hint-size="390px,844px"></dc-import></sc-if><sc-if value="{{ st.isMedia }}"><dc-import name="MediaFrame" s="{{ st.s }}" mobile="{{ true }}" hint-size="390px,844px"></dc-import></sc-if></div></div>
</div>
<p style="margin:0;font-size:12px;line-height:18px;color:var(--ui-text-muted);text-wrap:pretty"><b style="color:var(--ui-text-toned)">Copy:</b> {{ st.copy }}</p>
</div>
@@ -69,7 +69,7 @@ class Component extends DCLogic {
componentDidUpdate(p) { if (p.theme !== this.props.theme && this.props.theme) this.setState({ mode: this.props.theme }); this.apply() }
renderVals() {
const modes = [['system', 'System'], ['light', 'Light'], ['dark', 'Dark']].map(([k, label]) => { const on = this.state.mode === k; return { label, on, bg: on ? 'var(--ui-primary)' : 'transparent', fg: on ? 'var(--ui-bg)' : 'var(--ui-text-toned)', pick: () => this.setState({ mode: k }) } })
const groups = this.state.spec.groups.map(g => ({ ...g, states: g.states.map(s => ({ ...s, scopeLabel: s.scope === 'later' ? 'Later' : 'Available now', chipBd: s.scope === 'later' ? '1px dashed var(--ui-border-accented)' : '1px solid var(--ui-border-accented)' })) }))
const groups = this.state.spec.groups.map(g => ({ ...g, states: g.states.map(s => ({ ...s, isMedia: !!(s.s && s.s.frame === 'media'), isSchema: !(s.s && s.s.frame === 'media'), scopeLabel: s.scope === 'later' ? 'Later' : 'Available now', chipBd: s.scope === 'later' ? '1px dashed var(--ui-border-accented)' : '1px solid var(--ui-border-accented)' })) }))
const tables = this.state.spec.tables.map(t => ({ ...t, rows: t.rows.map(r => ({ cells: r })) }))
return { rootRef: this.rootRef, modes, groups, tables }
}
+62 -33
View File
@@ -61,7 +61,7 @@ class Component extends DCLogic {
const Empty = (icon, title, text, action) => D('background:var(--ui-bg);border:1px solid var(--ui-border);padding:40px 24px;display:flex;flex-direction:column;align-items:center;gap:12px;text-align:center', S('width:44px;height:44px;display:flex;align-items:center;justify-content:center;background:var(--ui-bg-elevated);color:var(--ui-text-toned)', I(icon, 20)), S('font-weight:600;font-size:15px;color:var(--ui-text-highlighted)', title), S('color:var(--ui-text-muted);max-width:360px;text-wrap:pretty', text), action && B(action, { k: 'primary', icon: 'plus', px: 16 }))
// ---------- data
const FT = { text: ['type', 'Text', 'Short text, like a title or a name'], richtext: ['pilcrow', 'Rich text', 'Long text with formatting, written in Markdown'], number: ['hash', 'Number', 'Whole or decimal numbers'], boolean: ['toggle-left', 'Yes or no', 'An on or off switch'], date: ['calendar', 'Date', 'A calendar day, without a time'], select: ['list', 'Choice', 'One option from a list you define'] }
const FT = { text: ['type', 'Text', 'Short text, like a title or a name'], richtext: ['pilcrow', 'Rich text', 'Long text with formatting, written in Markdown'], number: ['hash', 'Number', 'Whole or decimal numbers'], boolean: ['toggle-left', 'Yes or no', 'An on or off switch'], date: ['calendar', 'Date', 'A calendar day, without a time'], select: ['list', 'Choice', 'One option from a list you define'], media: ['image', 'Media', 'One image from your media library'] }
const EV = [
{ key: 'title', label: 'Title', type: 'text', req: true, uniq: true, max: 80 }, { key: 'starts_on', label: 'Starts on', type: 'date', req: true }, { key: 'ends_on', label: 'Ends on', type: 'date' },
{ key: 'online', label: 'Online', type: 'boolean', def: false }, { key: 'capacity', label: 'Capacity', type: 'number', min: 1, max: 5000 }, { key: 'category', label: 'Category', type: 'select', opts: ['Talk', 'Workshop', 'Meetup'] }, { key: 'description', label: 'Description', type: 'richtext' }].map(f => ({ ...f, saved: true }))
@@ -81,6 +81,7 @@ class Component extends DCLogic {
{ id: 38, title: 'Timber joinery for beginners', starts_on: '14 Jan 2027', ends_on: '15 Jan 2027', online: false, capacity: 12, category: 'Workshop', description: 'Mortise, tenon and a lot of patience.', c: '28 Sep 2026', u: '7 Oct 2026, 10:05', by: 'Inès Duarte' },
{ id: 37, title: 'Q&A with the site managers', starts_on: '28 Oct 2026', ends_on: '', online: true, capacity: null, category: 'Meetup', description: '', c: '21 Sep 2026', u: '2 Oct 2026, 17:48', by: 'Jonas Pereira' },
{ id: 36, title: 'Reclaimed floorboards talk', starts_on: '17 Oct 2026', ends_on: '', online: false, capacity: 60, category: 'Talk', description: 'Where to find them and how to lay them.', c: '14 Sep 2026', u: '29 Sep 2026, 08:30', by: 'Marta Alves' }]
ROWS.forEach((r, i) => { r.thumbnail = ['ok', 'ok', '', 'miss', 'ok', '', 'ok'][i] })
const mdSample = 'Two days of hands-on work with **lime putty** and old stone.\n\n- Bring work clothes\n- Lunch is included'
const sampleVal = f => f.type === 'text' ? (f.def ?? 'Example text') : f.type === 'richtext' ? (f.def ?? 'Markdown text') : f.type === 'number' ? (f.def ?? f.min ?? 0) : f.type === 'boolean' ? (f.def ?? false) : f.type === 'date' ? (f.def ?? '2026-11-21') : (f.def ?? (f.opts && f.opts[0]) ?? null)
const apiJson = (fs_, key) => JSON.stringify({ id: 42, content_type: key, data: Object.fromEntries(fs_.map(f => [f.key, sampleVal(f)])), created_by: 3, updated_by: 3, created_at: '2026-10-15T11:02:00Z', updated_at: '2026-10-15T11:02:00Z' }, null, 2)
@@ -88,6 +89,23 @@ class Component extends DCLogic {
const dot = (t, ic) => S('display:inline-flex;align-items:center;gap:6px', I(ic, 14), t)
// ---------- inspector
const stripe = 'repeating-linear-gradient(135deg,var(--ui-bg-elevated) 0 6px,var(--ui-bg-accented) 6px 7px)'
const THUMB = { key: 'thumbnail', label: 'Thumbnail', type: 'media', saved: true }
const Ph = (w, hh, ex, ...c) => D('width:' + w + ';' + (hh ? 'height:' + hh + ';' : '') + 'flex-shrink:0;box-sizing:border-box;display:flex;align-items:center;justify-content:center;background:' + stripe + ';color:var(--ui-text-toned);' + mono + 'font-size:11px;line-height:16px;' + (ex || ''), ...c)
const Miss = (w, hh, ic = 'image-off', z = 20, ex = '') => h('div', { role: 'img', 'aria-label': 'Image no longer in the library', style: P('width:' + w + ';' + (hh ? 'height:' + hh + ';' : '') + 'flex-shrink:0;display:flex;align-items:center;justify-content:center;border:1px dashed var(--ui-border-accented);color:var(--ui-text-muted);box-sizing:border-box;' + ex) }, I(ic, z))
const cellM = (st, z) => st === 'ok' ? Ph(z + 'px', z + 'px', '') : st === 'miss' ? Miss(z + 'px', z + 'px', 'unlink', z > 32 ? 14 : 12) : S('color:var(--ui-text-muted);width:' + z + 'px;text-align:center;display:inline-block', '–')
const MThumb = o => D('position:relative;flex-shrink:0;box-sizing:border-box;overflow:hidden;width:' + (m ? '100%' : '160px') + ';' + (m ? 'aspect-ratio:16/9;' : 'height:120px;') + 'border:1px solid ' + (o.hover && !m ? 'var(--ui-text-muted)' : 'var(--ui-border-accented)') + ';' + (o.focus ? 'outline:2px solid var(--ui-primary);outline-offset:2px;' : '') + 'opacity:' + (o.dis ? 0.6 : 1), Ph('100%', '100%', '', '1600 × 900'), o.hover && !m && D('position:absolute;left:0;right:0;bottom:0;height:28px;display:flex;align-items:center;justify-content:center;gap:6px;background:var(--ui-bg-inverted);color:var(--ui-text-inverted);font-size:12px;font-weight:500', I('image', 14), 'Change image'))
const MCtl = (f, o = {}) => {
const dis = !!o.dis, st = o.st || 'empty'
const bd = o.err ? 'border:1px solid var(--ui-error);box-shadow:inset 0 0 0 1px var(--ui-error);' : st === 'empty' ? 'border:1px dashed var(--ui-border-accented);' : 'border:1px solid var(--ui-border-accented);'
const row = (...c) => D('display:flex;flex-direction:' + (m ? 'column' : 'row') + ';gap:' + (m ? 12 : 16) + 'px;padding:12px;align-items:' + (m ? 'stretch' : 'flex-start'), ...c)
const col = (...c) => D('flex:1;min-width:0;display:flex;flex-direction:column;gap:12px;' + (m ? '' : 'justify-content:space-between;min-height:120px'), ...c)
let inner
if (st === 'empty') inner = D('display:flex;flex-direction:' + (m ? 'column' : 'row') + ';align-items:' + (m ? 'stretch' : 'center') + ';gap:12px;padding:12px', D('display:flex;align-items:center;gap:12px;flex:1;min-width:0', S('width:40px;height:40px;display:flex;align-items:center;justify-content:center;background:var(--ui-bg-elevated);color:var(--ui-text-toned);flex-shrink:0', I('image', 20)), S('color:var(--ui-text-muted)', 'No image selected.')), B('Pick an image', { icon: 'image-plus', dis, ring: o.ringBtn === 'pick' }))
else if (st === 'filled') inner = row(MThumb(o), col(D('display:flex;flex-direction:column;gap:2px;min-width:0', S('font-weight:500;color:var(--ui-text-highlighted);overflow:hidden;text-overflow:ellipsis;white-space:nowrap', 'lime-plaster-workshop.jpg'), S('color:var(--ui-text-muted);font-size:12px;line-height:18px', '1600 × 900 · 240 KB')), D('display:flex;gap:8px', B('Change image', { icon: 'image', dis, full: m }), B('Remove', { k: 'ghost', icon: 'x', dis, full: m }))))
else inner = row(Miss(m ? '100%' : '160px', m ? null : '120px', 'image-off', 24, (m ? 'aspect-ratio:16/9;' : '') + (dis ? 'opacity:0.6;' : '')), col(D('display:flex;flex-direction:column;gap:4px', S('font-weight:500;color:var(--ui-text-highlighted)', 'This image is no longer in the library'), S('color:var(--ui-text-muted);font-size:12px;line-height:18px;text-wrap:pretty', f.req ? 'Thumbnail is required. Choose another image to save.' : 'You can still save. The entry keeps the link until you change it.')), D('display:flex;gap:8px;flex-wrap:wrap', B('Choose another image', { icon: 'image', dis, ring: o.ringBtn === 'choose', full: m }), B('Clear', { k: 'ghost', dis, full: m }))))
return D('display:flex;flex-direction:column;gap:6px;min-width:0', S('font-weight:500;color:var(--ui-text-highlighted)', f.label, f.req && ' *'), D(bd + 'background:var(--ui-bg);box-sizing:border-box', inner), o.err ? S('display:flex;gap:6px;align-items:flex-start;color:var(--ui-error);font-size:12px;line-height:18px', I('circle-alert', 14, 'margin-top:2px'), o.err) : st === 'missing' ? null : S('color:var(--ui-text-muted);font-size:12px;line-height:18px', 'One image from your library.'))
}
const Insp = (f, o = {}) => {
const t = f.type, e = f.err || {}, one = m || o.one, locked = !!f.saved
const [mnL, mxL, suf] = MM(t), canU = ['text', 'number', 'date', 'select'].includes(t), hasMM = ['text', 'richtext', 'number', 'date'].includes(t)
@@ -96,15 +114,15 @@ class Component extends DCLogic {
const mmErr = e.min || ''
const minV = f.min != null ? String(f.min) : '', maxV = f.max != null ? String(f.max) : ''
const defCtl = t === 'boolean' ? null : F('Default value', f.def != null ? String(f.def) : '', { opt: true, ph: f.def == null, phText: t === 'select' ? 'None' : t === 'date' ? 'No default' : 'No default', sel: t === 'select', ico: t === 'date' ? 'calendar' : null, area: t === 'richtext', err: e.def, dis: !!f.uniq, help: f.uniq ? 'A field with unique values can\'t have a default.' : e.def ? '' : 'Used when an entry is created and this field is left out.' })
const left = D('display:flex;flex-direction:column;min-width:0;border-top:1px solid var(--ui-border)', SwR(!!f.req, 'Required', 'An entry can\'t be saved with this field empty.'), SwR(!!f.uniq, 'Unique values', canU ? 'Each entry needs a different value.' : t === 'richtext' ? 'Not available for rich text.' : 'Not available for yes or no fields.', !canU), t === 'boolean' && SwR(!!f.def, 'On by default', 'New entries start with this switch ' + (f.def ? 'on' : 'off') + ' when the field is left out.'))
const right = hasMM ? [F(mnL, minV, { suffix: suf, ph: minV === '', phText: 'No minimum', err: mmErr, help: mmErr ? '' : null }), F(mxL, maxV, { suffix: suf, ph: maxV === '', phText: 'No maximum', help: mmErr ? '' : t === 'text' || t === 'richtext' ? 'Counted in characters. Entries show a counter.' : t === 'number' ? 'Entries outside the range are refused.' : 'Entries outside the range are refused.' }), defCtl] : [defCtl, D('display:flex;flex-direction:column;gap:6px;min-width:0', S('font-weight:500;color:var(--ui-text-highlighted)', 'Limits'), S('color:var(--ui-text-muted);font-size:12px;line-height:18px', t === 'boolean' ? 'Yes or no fields have no limits.' : 'Limits come from the choices below.'))]
const ch = t === 'select' ? Choices(f) : null
const left = D('display:flex;flex-direction:column;min-width:0;border-top:1px solid var(--ui-border)', SwR(!!f.req, 'Required', 'An entry can\'t be saved with this field empty.'), t !== 'media' && SwR(!!f.uniq, 'Unique values', canU ? 'Each entry needs a different value.' : t === 'richtext' ? 'Not available for rich text.' : 'Not available for yes or no fields.', !canU), t === 'boolean' && SwR(!!f.def, 'On by default', 'New entries start with this switch ' + (f.def ? 'on' : 'off') + ' when the field is left out.'))
const right = t === 'media' ? [] : hasMM ? [F(mnL, minV, { suffix: suf, ph: minV === '', phText: 'No minimum', err: mmErr, help: mmErr ? '' : null }), F(mxL, maxV, { suffix: suf, ph: maxV === '', phText: 'No maximum', help: mmErr ? '' : t === 'text' || t === 'richtext' ? 'Counted in characters. Entries show a counter.' : t === 'number' ? 'Entries outside the range are refused.' : 'Entries outside the range are refused.' }), defCtl] : [defCtl, D('display:flex;flex-direction:column;gap:6px;min-width:0', S('font-weight:500;color:var(--ui-text-highlighted)', 'Limits'), S('color:var(--ui-text-muted);font-size:12px;line-height:18px', t === 'boolean' ? 'Yes or no fields have no limits.' : 'Limits come from the choices below.'))]
const ch = t === 'select' ? Choices(f) : t === 'media' ? D('display:flex;gap:8px;padding:10px 12px;background:var(--rc-info-soft);color:var(--ui-info)', S('padding-top:2px;display:flex', I('info', 16)), S('color:var(--ui-text-toned);text-wrap:pretty', 'Holds one image from the media library. Entries link to the image instead of keeping a copy, so they always show its current version.')) : null
return D('display:flex;flex-direction:column;gap:' + (m ? 16 : 14) + 'px;min-width:0',
D('display:grid;grid-template-columns:' + g2 + ';gap:14px', F('Label', f.label, { req: true, err: e.label, focus: o.focus === 'label', ph: !f.label, phText: 'For example, Title' }),
D('display:flex;flex-direction:column;gap:6px;min-width:0', F('Key', f.key || '', { mono: true, auto: !locked && !e.key && !!f.key, lock: locked, err: e.key, ph: !f.key, phText: 'title', dis: false, help: locked ? 'Used in the API, so it can\'t change.' : e.key ? '' : 'The name used in the API. Starts with a letter. Lowercase letters, digits and underscores.' }))),
D('display:flex;flex-direction:column;gap:6px', D('display:flex;justify-content:space-between;gap:8px', S('font-weight:500;color:var(--ui-text-highlighted)', 'Type'), locked && S('color:var(--ui-text-muted);font-size:12px;display:flex;gap:4px;align-items:center', I('lock', 12), 'Can\'t change after saving')), D('display:grid;grid-template-columns:repeat(' + (one ? 2 : 3) + ',minmax(0,1fr));gap:8px', ...Object.keys(FT).map(tile))),
left,
D('display:grid;grid-template-columns:' + g2 + ';gap:14px;align-items:start', ...right.filter(Boolean)),
right.length > 0 && D('display:grid;grid-template-columns:' + g2 + ';gap:14px;align-items:start', ...right.filter(Boolean)),
ch)
}
const Choices = f => {
@@ -141,6 +159,7 @@ class Component extends DCLogic {
const Cal = () => { const cells = [...Array(6).fill(''), ...Array.from({ length: 30 }, (_, i) => i + 1)]; return D('width:' + (m ? 280 : 252) + 'px;padding:8px;background:var(--ui-bg);border:1px solid var(--ui-border);box-shadow:var(--rc-shadow-pop)', D('display:flex;align-items:center;justify-content:space-between;height:32px', IB('chevron-left'), S('font-weight:600', 'November 2026'), IB('chevron-right')), D('display:grid;grid-template-columns:repeat(7,1fr)', ...['Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa', 'Su'].map(d => S('height:28px;display:flex;align-items:center;justify-content:center;font-size:12px;color:var(--ui-text-muted)', d)), ...cells.map(c => S('height:' + (m ? 34 : 30) + 'px;display:flex;align-items:center;justify-content:center;background:' + (c === 21 ? 'var(--ui-primary)' : 'transparent') + ';color:' + (c === 21 ? 'var(--ui-bg)' : 'var(--ui-text-highlighted)'), c))) ) }
const Ctl = (f, o = {}) => {
const t = f.type, v = o.v == null ? '' : String(o.v)
if (t === 'media') return MCtl(f, o)
const lab = D('display:flex;justify-content:space-between;gap:8px', S('font-weight:500;color:var(--ui-text-highlighted)', f.label, f.req && ' *'), o.count && S(mono + 'font-size:12px;color:' + (o.countErr ? 'var(--ui-error)' : 'var(--ui-text-muted)'), o.count), o.def && Bd('Default', 'neu'))
const bd = o.err ? 'var(--ui-error)' : o.focus ? 'var(--ui-primary)' : 'var(--ui-border-accented)'
const box = (...inner) => D('display:flex;align-items:center;min-height:' + ih + 'px;border:1px solid ' + bd + ';background:' + (o.dis ? 'var(--ui-bg-elevated)' : 'var(--ui-bg)') + ';font-size:' + fs + 'px;' + (o.err ? 'box-shadow:inset 0 0 0 1px var(--ui-error);' : o.focus ? 'box-shadow:inset 0 0 0 1px var(--ui-primary);' : ''), ...inner)
@@ -157,6 +176,7 @@ class Component extends DCLogic {
}
const Cell = (f, v) => {
if (v === undefined || v === null || v === '') return S('color:var(--ui-text-muted)', '–')
if (f.type === 'media') return cellM(v, 40)
if (f.type === 'boolean') return S('display:flex;align-items:center;gap:6px', I(v ? 'check' : 'minus', 14, 'color:var(--ui-text-muted)'), v ? 'Yes' : 'No')
if (f.type === 'select') return S('height:20px;padding:0 6px;display:inline-flex;align-items:center;border:1px solid var(--ui-border-accented);color:var(--ui-text-toned);font-size:12px;justify-self:start', v)
if (f.type === 'number') return S('justify-self:end;font-variant-numeric:tabular-nums', v)
@@ -183,12 +203,13 @@ class Component extends DCLogic {
const newBtn = B('New content type', { k: 'primary', icon: 'plus', px: 14, dis: k === 'loading' })
const impExp = s.later ? [B('Import', { icon: 'upload' }), B('Export', { icon: 'download' })] : []
if (k === 'forbidden') { shell.role = 'user'; shell.crumbs = ['Schema']; main = Center('lock', 'You don\'t have access to Schema', 'Only owners and admins can change content types. You can still add and edit entries from the Content menu.', B('Go to Home', { k: 'primary', px: 16 })) }
else if (k === 'builtin') {
shell.crumbs = ['Schema', 'Articles']; shell.mTitle = 'Articles'; shell.mLead = 'arrow-left'
const AF = [['Title', 'title', 'text', 'Required · up to 200 characters'], ['Slug', 'slug', 'text', 'Required · unique'], ['Body', 'body', 'richtext', 'Up to 10,000 characters'], ['Online', 'online', 'boolean', 'Off by default'], ['Published on', 'published_on', 'date', '']]
else if (k === 'builtin' || k === 'customro') {
const cr = k === 'customro'
shell.crumbs = ['Schema', cr ? 'Events' : 'Articles']; shell.mTitle = cr ? 'Events' : 'Articles'; shell.mLead = 'arrow-left'
const AF = cr ? [['Title', 'title', 'text', 'Required · unique · up to 80 characters'], ['Starts on', 'starts_on', 'date', 'Required'], ['Category', 'category', 'select', 'Talk, Workshop, Meetup'], ['Description', 'description', 'richtext', ''], ['Thumbnail', 'thumbnail', 'media', 'One image from the library']] : [['Title', 'title', 'text', 'Required · up to 200 characters'], ['Slug', 'slug', 'text', 'Required · unique'], ['Body', 'body', 'richtext', 'Up to 10,000 characters'], ['Online', 'online', 'boolean', 'Off by default'], ['Published on', 'published_on', 'date', '']]
const cols = '28px minmax(0,1fr) minmax(0,1fr) 120px minmax(0,1.2fr)'
main = Page(pad, D('display:flex;align-items:center;gap:12px;flex-shrink:0', I('lock', 18, 'color:var(--ui-text-muted)'), S('font:600 20px/28px \'IBM Plex Sans\',sans-serif;color:var(--ui-text-highlighted)', 'Articles'), Bd('Built-in', 'built', 'lock')),
Alert('info', 'info', 'Managed by RenewCMS', 'Articles is a built-in type. You can read its fields here, but you can\'t edit it, delete it or add fields.'),
main = Page(pad, D('display:flex;align-items:center;gap:12px;flex-shrink:0', I('lock', 18, 'color:var(--ui-text-muted)'), S('font:600 20px/28px \'IBM Plex Sans\',sans-serif;color:var(--ui-text-highlighted)', cr ? 'Events' : 'Articles'), cr ? Bd('Read only', 'built', 'lock') : Bd('Built-in', 'built', 'lock')),
cr ? Alert('info', 'info', 'You can read these fields here', 'Only an owner or admin can change a content type.') : Alert('info', 'info', 'Managed by RenewCMS', 'Articles is a built-in type. You can read its fields here, but you can\'t edit it, delete it or add fields.'),
m ? D('background:var(--ui-bg);border:1px solid var(--ui-border)', ...AF.map(f => D('display:flex;gap:12px;align-items:center;padding:12px 16px;border-top:1px solid var(--ui-border);min-height:64px', S('width:28px;height:28px;display:flex;align-items:center;justify-content:center;background:var(--ui-bg-elevated)', I(FT[f[2]][0], 16)), D('flex:1;min-width:0;display:flex;flex-direction:column', S('font-weight:500', f[0]), S('font-size:12px;color:var(--ui-text-muted)', S(mono, f[1]), f[3] ? ' · ' + f[3] : ''))))) :
D('background:var(--ui-bg);border:1px solid var(--ui-border)', D('display:grid;grid-template-columns:' + cols + ';gap:12px;height:36px;align-items:center;padding:0 12px;background:var(--ui-bg-elevated);color:var(--ui-text-muted);font-weight:500', S('', ''), S('', 'Label'), S('', 'Key'), S('', 'Type'), S('', 'Rules')), ...AF.map(f => D('display:grid;grid-template-columns:' + cols + ';gap:12px;height:48px;align-items:center;padding:0 12px;border-top:1px solid var(--ui-border)', I(FT[f[2]][0], 16, 'color:var(--ui-text-toned)'), S('font-weight:500', f[0]), S(mono + 'font-size:12px;color:var(--ui-text-muted)', f[1]), S('', FT[f[2]][1]), S('color:var(--ui-text-muted)', f[3] || '–')))), S('color:var(--ui-text-muted);font-size:12px', 'Entries of built-in types are managed from their own screens, like Articles and Authors.'))
} else {
@@ -203,12 +224,15 @@ class Component extends DCLogic {
}
// 2 builder
const entN = v === 'review' && (k === 'mrefuse' || k === 'mclean') ? 12 : 37
const bld = () => {
let fl = EV, name = 'Events', key = 'events', sel = 0, st = 'clean', isNew = false, api = k === 'api', kb = -1, tErr = {}, banner = null, removed = null, cause = false, tip = false, toast = null, info = true, nErr = 0
if (v === 'review') { const rk = k; if (rk === 'confirm' || rk === 'fallback') { fl = RC; name = 'Recipes'; key = 'recipes'; info = false } else if (rk === 'blocked') { sel = 0 } else { fl = DIRTY; sel = 4; st = 'dirty'; removed = EV[6] } }
if (v === 'review') { const rk = k; if (rk === 'confirm' || rk === 'fallback') { fl = RC; name = 'Recipes'; key = 'recipes'; info = false } else if (rk === 'blocked') { sel = 0 } else if (rk === 'mrefuse' || rk === 'mclean') { fl = [...EV, { key: 'thumbnail', label: 'Thumbnail', type: 'media', isNew: true, req: rk === 'mrefuse' }]; sel = 7; st = 'dirty' } else { fl = DIRTY; sel = 4; st = 'dirty'; removed = EV[6] } }
if (v === 'rel') { }
if (v === 'builder') {
if (k === 'locked') { sel = 1; tip = true }
if (k === 'media' || k === 'mreq') { fl = [...EV, k === 'mreq' ? { ...THUMB, req: true } : THUMB]; sel = 7 }
if (k === 'mnew') { fl = [...EV, { key: 'thumbnail', label: 'Thumbnail', type: 'media', isNew: true }]; sel = 7; st = 'dirty' }
if (['dirty', 'saving', 'saved', 'fail', 'incompat', 'offline'].includes(k)) { fl = DIRTY; sel = 4; st = k === 'incompat' ? 'dirty' : k; removed = EV[6] }
if (k === 'saved') { removed = null; st = 'saved'; fl = DIRTY.map(f => ({ ...f, isNew: false, changed: false, saved: true })); toast = Toast('success', 'circle-check', 'Content type saved', 'Events now has 8 fields.') }
if (k === 'fail') banner = Alert('error', 'circle-x', 'Couldn\'t save the content type', 'Something went wrong on our side. Your changes are still here. Try again in a moment.', 'Try again')
@@ -227,7 +251,7 @@ class Component extends DCLogic {
const keyF = F('Key', key, { mono: true, lock: !isNew, auto: isNew && !!key && !tErr.key, err: tErr.key, ph: !key, phText: 'events', dis: dim, help: tErr.key ? '' : isNew ? 'Used in URLs and the API. Lowercase letters, digits and hyphens. It can\'t change after you save.' : null })
const save = D('display:flex;align-items:center;gap:' + (m ? 8 : 12) + 'px;flex-shrink:0', !m && stChip(st, nErr), !m && B('Discard', { dis: st === 'clean' || st === 'saving' || st === 'saved' || (st === 'errs' && isNew && k === 'new') }), !m && B(st === 'saving' ? 'Saving…' : 'Save', { k: 'primary', icon: st === 'saving' ? 'loader-circle' : null, px: 16, dis: st === 'clean' || st === 'saved' || st === 'saving' || st === 'errs' || st === 'offline' }))
const top = m ? D('display:flex;flex-direction:column;gap:12px;padding:16px;flex-shrink:0;background:var(--ui-bg);border-bottom:1px solid var(--ui-border)', nameF, keyF) : D('display:flex;align-items:flex-start;gap:16px;padding:16px 24px;flex-shrink:0;background:var(--ui-bg);border-bottom:1px solid var(--ui-border);position:relative', D('width:320px', nameF), D('width:320px', keyF), D('flex:1'), D('display:flex;align-items:center;gap:12px;height:32px;margin-top:26px', save, IB('ellipsis')), tip && D('position:absolute;left:352px;top:84px;z-index:30', Tip('The key is used in URLs and the API, so it can\'t change after the type is created.')))
const infoBar = info && !isNew && D('flex-shrink:0;display:flex;align-items:center;gap:8px;padding:8px ' + (m ? 16 : 24) + 'px;background:var(--rc-info-soft);color:var(--ui-info);font-size:12px;line-height:18px', I('info', 14, 'flex-shrink:0'), S('color:var(--ui-text-toned)', '37 entries use this content type. Changes are checked against them when you save.'))
const infoBar = info && !isNew && D('flex-shrink:0;display:flex;align-items:center;gap:8px;padding:8px ' + (m ? 16 : 24) + 'px;background:var(--rc-info-soft);color:var(--ui-info);font-size:12px;line-height:18px', I('info', 14, 'flex-shrink:0'), S('color:var(--ui-text-toned)', entN + ' entries use this content type. Changes are checked against them when you save.'))
const listHdr = D('display:flex;align-items:center;justify-content:space-between;height:28px', S('font-weight:600;color:var(--ui-text-highlighted)', 'Fields'), S(mono + 'font-size:12px;color:var(--ui-text-muted)', fl.length + ' of 50'))
const live = kb >= 0 && D('padding:8px 10px;background:var(--ui-bg-inverted);color:var(--ui-text-inverted);font-size:12px;line-height:18px', S('font-weight:600', 'Moving Ends on. Position 2 of 7.'), ' Press Up or Down to move, Space to drop, Esc to cancel.')
const rows = fl.length ? fl.map((x, i) => FRow(x, i, { sel: m ? -1 : sel, kb, dim, cause })) : [D('display:flex;flex-direction:column;align-items:center;gap:8px;text-align:center;padding:32px 16px;border:1px dashed ' + (tErr.fields ? 'var(--ui-error)' : 'var(--ui-border-accented)'), I('rows-3', 20, 'color:var(--ui-text-muted)'), S('font-weight:600', 'No fields yet'), S('color:' + (tErr.fields ? 'var(--ui-error)' : 'var(--ui-text-muted)'), tErr.fields || 'Add the first field.'))]
@@ -240,7 +264,7 @@ class Component extends DCLogic {
shell.nav = 'schema'; shell.crumbs = ['Schema', isNew ? 'New content type' : name]; shell.mTitle = isNew ? 'New content type' : name; shell.mLead = 'arrow-left'; shell.mAction = 'ellipsis'
shell.offline = false
main = D('flex:1;min-width:0;min-height:0;display:flex;flex-direction:column;position:relative', st === 'offline' && Offline(), top, infoBar, banner && D('padding:12px ' + (m ? 16 : 24) + 'px 0', banner), D('flex:1;min-height:0;display:flex;' + (m ? 'flex-direction:column' : ''), list, inspPane), m ? bar : ApiPanel(fl, key || 'events', api))
if (m && f && (s.sheet || (v === 'builder' && ['edit-sheet', 'choices'].includes(k)))) ov.push(Sheet({ title: 'Field: ' + (f.label || 'Untitled field') }, Insp(f), [B('Done', { k: 'primary', full: true })]))
if (m && f && (s.sheet || (v === 'builder' && ['edit-sheet', 'choices', 'media', 'mreq', 'mnew'].includes(k)))) ov.push(Sheet({ title: 'Field: ' + (f.label || 'Untitled field') }, Insp(f), [B('Done', { k: 'primary', full: true })]))
if (m && api) ov.push(Sheet({ title: 'API preview' }, [S('color:var(--ui-text-muted);font-size:12px', 'GET /v1/content-type/' + key + '/entry'), S('display:block;flex:1;overflow:hidden;padding:10px 12px;background:var(--ui-bg-elevated);border:1px solid var(--ui-border);white-space:pre;' + mono + 'font-size:12px;line-height:19px;color:var(--ui-text-highlighted)', apiJson(fl, key))], [B('Copy JSON', { k: 'primary', full: true, icon: 'copy' })]))
if (toast) ov.push(toast)
}
@@ -258,28 +282,29 @@ class Component extends DCLogic {
if (k === 'refused') ov.push(Shell({ title: 'Nothing was changed', desc: 'RenewCMS refused the changes because some entries don\'t fit the new fields. It doesn\'t say which entries.', w: 560, top: 60, close: true, cancel: 'Discard changes', confirm: 'Back to editing' }, [Alert('error', 'circle-x', 'Your content type is as it was', 'No field was added, changed or removed.'), S('font-weight:600;color:var(--ui-text-highlighted)', 'The change that can cause this in your edit'), chg('pencil', 'n', 'Change Capacity', 'Highest value goes from 5000 to 2000. An entry may have a higher value.', 'Possible cause'), S('color:var(--ui-text-muted);font-size:12px;line-height:18px;text-wrap:pretty', 'This kind of change is refused when an entry is over the new limit, a new required field has no default, a field becomes unique while entries share a value, or a removed choice is still in use.')]))
if (k === 'blocked') ov.push(Shell({ title: 'You can\'t delete Events yet', desc: 'A content type can only be deleted when it has no entries.', close: true, cancel: 'Close', confirm: 'View entries' }, [Alert('warning', 'triangle-alert', 'Events has 37 entries', 'Delete all of its entries first, then delete the content type.')]))
if (k === 'confirm') ov.push(Shell({ title: 'Delete Recipes?', desc: 'Recipes has no entries. Its fields and its API routes will be deleted. This can\'t be undone.', close: true, cancel: 'Cancel', confirm: 'Delete content type', tone: 'danger' }, [S('color:var(--ui-text-toned)', 'Key: ', S(mono + 'font-size:12px', 'recipes'))]))
if (k === 'mrefuse' || k === 'mclean') { const rf = k === 'mrefuse'; ov.push(Shell({ title: 'Review changes to Events', desc: 'Apply them to save the content type.', w: 560, top: 60, cancel: 'Back to editing', confirm: 'Apply changes', cdis: rf }, [D('display:flex;flex-direction:column;gap:2px', S('font-weight:600;font-size:15px;color:var(--ui-text-highlighted)', 'Add 1 field'), S('color:var(--ui-text-muted)', 'Events has 12 entries. Each one is checked against the new fields when you apply.')), chg('plus', 'n', 'Add Thumbnail', rf ? 'Media, required. A media field can\'t have a default, so the 12 existing entries would have no image. Make Thumbnail optional to add it.' : 'Media, optional. 12 entries are unaffected.', rf ? 'Can\'t be applied' : null), rf && S('color:var(--ui-text-muted);font-size:12px;line-height:18px', 'Back to editing keeps your other changes.')])) }
if (k === 'fallback') ov.push(Shell({ title: 'Delete Recipes?', desc: 'Recipes has no entries. Its fields and its API routes will be deleted. This can\'t be undone.', close: true, cancel: 'Close', confirm: 'View entries' }, [Alert('error', 'circle-x', 'Recipes now has entries', 'Someone added an entry after this page loaded, so nothing was deleted. Delete the entries first, then try again.')]))
}
// 4 gallery
const GF = { text: EV[0], richtext: { key: 'description', label: 'Description', type: 'richtext', max: 5000 }, number: EV[4], boolean: EV[3], date: { key: 'starts_on', label: 'Starts on', type: 'date', req: true, max: '31 Dec 2027' }, select: { ...EV[5], req: false } }
const GF = { media: THUMB, text: EV[0], richtext: { key: 'description', label: 'Description', type: 'richtext', max: 5000 }, number: EV[4], boolean: EV[3], date: { key: 'starts_on', label: 'Starts on', type: 'date', req: true, max: '31 Dec 2027' }, select: { ...EV[5], req: false } }
if (v === 'gallery') {
bare = true; if (m) { bw = '390px'; bhh = '844px' }
const f = { ...GF[k], saved: false }, t = k, L = f.label
const ERR = { text: [['required', 422, 'Fill in ' + L + '.'], ['type', 422, L + ' must be text.'], ['min', 422, L + ' needs at least 3 characters.'], ['max', 422, L + ' can be up to 80 characters.'], ['options', '', 'Not used for text.'], ['unique', 409, 'Another entry already uses this ' + L + '. Enter a different one.']], richtext: [['required', 422, 'Fill in ' + L + '.'], ['type', 422, L + ' must be text.'], ['min', 422, L + ' needs at least 10 characters.'], ['max', 422, L + ' can be up to 5000 characters.'], ['options', '', 'Not used for rich text.'], ['unique', '', 'Not used for rich text.']], number: [['required', 422, 'Fill in ' + L + '.'], ['type', 422, L + ' must be a number.'], ['min', 422, L + ' must be at least 1.'], ['max', 422, L + ' must be at most 5000.'], ['options', '', 'Not used for numbers.'], ['unique', 409, 'Another entry already uses this ' + L + '.']], boolean: [['required', 422, 'Choose yes or no for ' + L + '.'], ['type', 422, L + ' must be yes or no.'], ['min', '', 'Not used for yes or no.'], ['max', '', 'Not used for yes or no.'], ['options', '', 'Not used for yes or no.'], ['unique', '', 'Not used for yes or no.']], date: [['required', 422, 'Pick a date for ' + L + '.'], ['type', 422, L + ' must be a date, like 2026-11-21.'], ['min', 422, L + ' can\'t be before 1 Jan 2026.'], ['max', 422, L + ' can\'t be after 31 Dec 2027.'], ['options', '', 'Not used for dates.'], ['unique', 409, 'Another entry already uses this date for ' + L + '.']], select: [['required', 422, 'Choose an option for ' + L + '.'], ['type', 422, L + ' must be one of the choices.'], ['min', '', 'Not used for choices.'], ['max', '', 'Not used for choices.'], ['options', 422, 'Choose one of: Talk, Workshop or Meetup.'], ['unique', 409, 'Another entry already uses this choice for ' + L + '.']] }[t]
const SAMPLE = { text: ['Lime plaster workshop', ''], richtext: [mdSample, ''], number: ['18', ''], boolean: ['true', 'false'], date: ['21 Nov 2026', ''], select: ['Workshop', ''] }[t]
const ERR = { media: [['required', 422, 'Pick an image for ' + L + '.'], ['type', 422, L + ' must be an image from the library.'], ['min', '', 'Not used for media.'], ['max', '', 'Not used for media.'], ['options', '', 'Not used for media.'], ['unique', '', 'Not used for media.']], text: [['required', 422, 'Fill in ' + L + '.'], ['type', 422, L + ' must be text.'], ['min', 422, L + ' needs at least 3 characters.'], ['max', 422, L + ' can be up to 80 characters.'], ['options', '', 'Not used for text.'], ['unique', 409, 'Another entry already uses this ' + L + '. Enter a different one.']], richtext: [['required', 422, 'Fill in ' + L + '.'], ['type', 422, L + ' must be text.'], ['min', 422, L + ' needs at least 10 characters.'], ['max', 422, L + ' can be up to 5000 characters.'], ['options', '', 'Not used for rich text.'], ['unique', '', 'Not used for rich text.']], number: [['required', 422, 'Fill in ' + L + '.'], ['type', 422, L + ' must be a number.'], ['min', 422, L + ' must be at least 1.'], ['max', 422, L + ' must be at most 5000.'], ['options', '', 'Not used for numbers.'], ['unique', 409, 'Another entry already uses this ' + L + '.']], boolean: [['required', 422, 'Choose yes or no for ' + L + '.'], ['type', 422, L + ' must be yes or no.'], ['min', '', 'Not used for yes or no.'], ['max', '', 'Not used for yes or no.'], ['options', '', 'Not used for yes or no.'], ['unique', '', 'Not used for yes or no.']], date: [['required', 422, 'Pick a date for ' + L + '.'], ['type', 422, L + ' must be a date, like 2026-11-21.'], ['min', 422, L + ' can\'t be before 1 Jan 2026.'], ['max', 422, L + ' can\'t be after 31 Dec 2027.'], ['options', '', 'Not used for dates.'], ['unique', 409, 'Another entry already uses this date for ' + L + '.']], select: [['required', 422, 'Choose an option for ' + L + '.'], ['type', 422, L + ' must be one of the choices.'], ['min', '', 'Not used for choices.'], ['max', '', 'Not used for choices.'], ['options', 422, 'Choose one of: Talk, Workshop or Meetup.'], ['unique', 409, 'Another entry already uses this choice for ' + L + '.']] }[t]
const SAMPLE = { media: ['', ''], text: ['Lime plaster workshop', ''], richtext: [mdSample, ''], number: ['18', ''], boolean: ['true', 'false'], date: ['21 Nov 2026', ''], select: ['Workshop', ''] }[t]
const sec = (title, ...c) => D('display:flex;flex-direction:column;gap:10px;min-width:0', S('font:600 15px/24px \'IBM Plex Sans\',sans-serif;color:var(--ui-text-highlighted)', title), ...c)
const card = (...c) => D('background:var(--ui-bg);border:1px solid var(--ui-border);padding:16px;display:flex;flex-direction:column;gap:14px', ...c)
const specCtl = { text: Ctl(f, { v: 'Lime plaster workshop, two days of work with the whole team on site', count: '74 / 80', focus: true }), richtext: Ctl({ ...f, max: 5000 }, { v: mdSample, tab: 'write', count: '86 / 5000', help: 'Markdown. Switch to Preview to check the result.' }), number: Ctl(f, { v: '18', focus: true }), boolean: Ctl(f, { v: 'true' }), date: Ctl(f, { v: '21 Nov 2026', focus: true, extra: D('position:absolute;left:0;top:68px;z-index:3', Cal()) }), select: Ctl(f, { v: 'Workshop', focus: true, extra: D('position:absolute;left:0;top:66px;right:0;z-index:3;border:1px solid var(--ui-border);background:var(--ui-bg);box-shadow:var(--rc-shadow-pop);padding:4px', ...['Talk', 'Workshop', 'Meetup'].map(o_ => D('height:' + (m ? 44 : 32) + 'px;padding:0 8px;display:flex;align-items:center;justify-content:space-between;background:' + (o_ === 'Workshop' ? 'var(--ui-bg-elevated)' : 'transparent'), o_, o_ === 'Workshop' && I('check', 14)))) }) }[t]
const specCtl = { media: Ctl(f, { st: 'filled', hover: true }), text: Ctl(f, { v: 'Lime plaster workshop, two days of work with the whole team on site', count: '74 / 80', focus: true }), richtext: Ctl({ ...f, max: 5000 }, { v: mdSample, tab: 'write', count: '86 / 5000', help: 'Markdown. Switch to Preview to check the result.' }), number: Ctl(f, { v: '18', focus: true }), boolean: Ctl(f, { v: 'true' }), date: Ctl(f, { v: '21 Nov 2026', focus: true, extra: D('position:absolute;left:0;top:68px;z-index:3', Cal()) }), select: Ctl(f, { v: 'Workshop', focus: true, extra: D('position:absolute;left:0;top:66px;right:0;z-index:3;border:1px solid var(--ui-border);background:var(--ui-bg);box-shadow:var(--rc-shadow-pop);padding:4px', ...['Talk', 'Workshop', 'Meetup'].map(o_ => D('height:' + (m ? 44 : 32) + 'px;padding:0 8px;display:flex;align-items:center;justify-content:space-between;background:' + (o_ === 'Workshop' ? 'var(--ui-bg-elevated)' : 'transparent'), o_, o_ === 'Workshop' && I('check', 14)))) }) }[t]
const spacer = { date: 'height:236px', select: 'height:120px', richtext: '', text: '', number: '', boolean: '' }[t]
const stateLbl = { text: 'Typing, close to the limit', richtext: 'Write tab, with counter', number: 'Focused', boolean: 'On', date: 'Date picker open', select: 'Choices open' }[t]
const stateLbl = { media: 'Filled, pointer over the thumbnail', text: 'Typing, close to the limit', richtext: 'Write tab, with counter', number: 'Focused', boolean: 'On', date: 'Date picker open', select: 'Choices open' }[t]
const ctlCol = sec('Entry form control', card(S('font-size:12px;color:var(--ui-text-muted)', stateLbl), D('', specCtl, spacer && D(spacer)), D('border-top:1px solid var(--ui-border)'), S('font-size:12px;color:var(--ui-text-muted)', t === 'richtext' ? 'Preview tab' : t === 'boolean' ? 'Off, and not set' : 'Empty'), t === 'richtext' ? Ctl(f, { v: mdSample, tab: 'preview', help: '' }) : t === 'boolean' ? Ctl(f, { v: 'false' }) : Ctl(f, { v: '' })))
const cell = (val, lab) => D('display:grid;grid-template-columns:' + (m ? '90px' : '110px') + ' minmax(0,1fr);gap:12px;align-items:center;min-height:40px;padding:0 12px;border-top:1px solid var(--ui-border)', S('font-size:12px;color:var(--ui-text-muted)', lab), Cell(f, val))
const cellVals = { text: ['Lime plaster workshop', ''], richtext: ['Two days of hands-on work with lime putty and old stone.', ''], number: [18, null], boolean: [true, null], date: ['21 Nov 2026', ''], select: ['Workshop', ''] }[t]
const listCol = sec('List cell', D('background:var(--ui-bg);border:1px solid var(--ui-border)', D('display:grid;grid-template-columns:' + (m ? '90px' : '110px') + ' minmax(0,1fr);gap:12px;height:36px;align-items:center;padding:0 12px;background:var(--ui-bg-elevated);color:var(--ui-text-muted);font-weight:500', S('', 'Value'), S('', L)), D('', cell(cellVals[0], 'Filled'), cell(cellVals[1], 'Empty'))), S('font-size:12px;color:var(--ui-text-muted)', { text: 'Truncated on one line, full text on hover.', richtext: 'First line as plain text, truncated.', number: 'Right-aligned, tabular figures.', boolean: 'Yes or No with an icon. Empty only when the field has no value.', date: 'Day, month and year.', select: 'The chosen option as a small tag.' }[t]))
const cellVals = { media: ['ok', ''], text: ['Lime plaster workshop', ''], richtext: ['Two days of hands-on work with lime putty and old stone.', ''], number: [18, null], boolean: [true, null], date: ['21 Nov 2026', ''], select: ['Workshop', ''] }[t]
const listCol = sec('List cell', D('background:var(--ui-bg);border:1px solid var(--ui-border)', D('display:grid;grid-template-columns:' + (m ? '90px' : '110px') + ' minmax(0,1fr);gap:12px;height:36px;align-items:center;padding:0 12px;background:var(--ui-bg-elevated);color:var(--ui-text-muted);font-weight:500', S('', 'Value'), S('', L)), D('', cell(cellVals[0], 'Filled'), cell(cellVals[1], 'Empty'), t === 'media' && cell('miss', 'Image missing'))), S('font-size:12px;color:var(--ui-text-muted)', { text: 'Truncated on one line, full text on hover.', richtext: 'First line as plain text, truncated.', number: 'Right-aligned, tabular figures.', boolean: 'Yes or No with an icon. Empty only when the field has no value.', date: 'Day, month and year.', select: 'The chosen option as a small tag.', media: 'A 40 px square thumbnail, 32 px in cards. Not sortable. A dash when empty.' }[t]))
const errCol = sec('Errors by rule', D('background:var(--ui-bg);border:1px solid var(--ui-border)', D('display:grid;grid-template-columns:' + (m ? '64px 38px' : '72px 40px') + ' minmax(0,1fr);gap:10px;height:32px;align-items:center;padding:0 12px;background:var(--ui-bg-elevated);color:var(--ui-text-muted);font-weight:500', S('', 'Rule'), S('', 'HTTP'), S('', 'Message')), ...ERR.map(r => D('display:grid;grid-template-columns:' + (m ? '64px 38px' : '72px 40px') + ' minmax(0,1fr);gap:10px;padding:8px 12px;border-top:1px solid var(--ui-border);align-items:start;line-height:18px', S(mono + 'font-size:12px;color:var(--ui-text-highlighted)', r[0]), S(mono + 'font-size:12px;color:var(--ui-text-muted)', String(r[1] || '–')), S('color:' + (r[1] ? 'var(--ui-error)' : 'var(--ui-text-muted)') + ';text-wrap:pretty', r[2])))))
const FW = { text: [['contains', 'Any text'], 'text'], richtext: [['contains', 'Any text'], 'text'], number: [['between'], 'num'], boolean: [['is'], 'bool'], date: [['between'], 'date'], select: [['is one of'], 'sel'] }[t]
const fw = FW[1] === 'bool' ? Seg([['any', 'Any'], ['yes', 'Yes'], ['no', 'No']], 'any') : FW[1] === 'sel' ? D('display:flex;gap:6px;flex-wrap:wrap', ...['Talk', 'Workshop', 'Meetup'].map((o_, i) => S('height:28px;padding:0 10px;display:flex;align-items:center;gap:6px;border:1px solid ' + (i === 1 ? 'var(--ui-primary)' : 'var(--ui-border-accented)') + ';background:' + (i === 1 ? 'var(--rc-sand)' : 'var(--ui-bg)') + ';color:' + (i === 1 ? 'var(--rc-on-sand)' : 'var(--ui-text-toned)'), i === 1 && I('check', 12), o_))) : FW[1] === 'num' || FW[1] === 'date' ? D('display:flex;gap:8px;align-items:center', F('', '', { ph: true, phText: FW[1] === 'date' ? 'From' : 'Min', ico: FW[1] === 'date' ? 'calendar' : null }), S('color:var(--ui-text-muted)', 'to'), F('', '', { ph: true, phText: FW[1] === 'date' ? 'Until' : 'Max', ico: FW[1] === 'date' ? 'calendar' : null })) : F('', '', { ph: true, phText: 'Contains…', ico: 'search' })
const FW = { media: [['has an image'], 'media'], text: [['contains', 'Any text'], 'text'], richtext: [['contains', 'Any text'], 'text'], number: [['between'], 'num'], boolean: [['is'], 'bool'], date: [['between'], 'date'], select: [['is one of'], 'sel'] }[t]
const fw = FW[1] === 'media' ? Seg([['any', 'Any'], ['yes', 'Has an image'], ['no', 'No image']], 'any') : FW[1] === 'bool' ? Seg([['any', 'Any'], ['yes', 'Yes'], ['no', 'No']], 'any') : FW[1] === 'sel' ? D('display:flex;gap:6px;flex-wrap:wrap', ...['Talk', 'Workshop', 'Meetup'].map((o_, i) => S('height:28px;padding:0 10px;display:flex;align-items:center;gap:6px;border:1px solid ' + (i === 1 ? 'var(--ui-primary)' : 'var(--ui-border-accented)') + ';background:' + (i === 1 ? 'var(--rc-sand)' : 'var(--ui-bg)') + ';color:' + (i === 1 ? 'var(--rc-on-sand)' : 'var(--ui-text-toned)'), i === 1 && I('check', 12), o_))) : FW[1] === 'num' || FW[1] === 'date' ? D('display:flex;gap:8px;align-items:center', F('', '', { ph: true, phText: FW[1] === 'date' ? 'From' : 'Min', ico: FW[1] === 'date' ? 'calendar' : null }), S('color:var(--ui-text-muted)', 'to'), F('', '', { ph: true, phText: FW[1] === 'date' ? 'Until' : 'Max', ico: FW[1] === 'date' ? 'calendar' : null })) : F('', '', { ph: true, phText: 'Contains…', ico: 'search' })
const filtCol = sec('Filter in the entry list', D('border:1px dashed var(--ui-border-accented);padding:14px;display:flex;flex-direction:column;gap:10px', D('display:flex;align-items:center;gap:8px', S('font-weight:500;color:var(--ui-text-highlighted)', L + ': ' + FW[0][0]), Later('Later')), fw, S('font-size:12px;color:var(--ui-text-muted);line-height:18px', 'Filtering on custom fields isn\'t available yet. The list only sorts by ID, created and updated.')))
const head = D('display:flex;align-items:center;gap:14px;flex-shrink:0', S('width:44px;height:44px;display:flex;align-items:center;justify-content:center;background:var(--rc-sand);color:var(--rc-on-sand)', I(FT[t][0], 22)), D('flex:1;display:flex;flex-direction:column', S('font:600 ' + (m ? 20 : 24) + 'px/32px \'IBM Plex Sans\',sans-serif;color:var(--ui-text-highlighted)', FT[t][1]), S('color:var(--ui-text-muted)', FT[t][2])), !m && S(mono + 'font-size:12px;color:var(--ui-text-toned)', 'type: "' + t + '"'))
const inspCol = !m && sec('Inspector options', card(Insp(f, { one: true })))
@@ -287,7 +312,7 @@ class Component extends DCLogic {
}
// 5 entries
const visCols = k === 'cols' ? [EV[0], EV[1], EV[2], EV[3]] : [EV[0], EV[1], EV[2], EV[3]]
const visCols = ['thumb', 'thumbcols', 'thumbtip'].includes(k) ? [EV[0], THUMB, EV[1], EV[5]] : [EV[0], EV[1], EV[2], EV[3]]
if (v === 'entries') {
shell.nav = 'content'; shell.crumbs = ['Content', 'Events']; shell.mTitle = 'Events'; shell.contentOn = k === 'notfound' ? null : 'events'
if (s.many && m) { shell.drawer = true; shell.contentOpen = true }
@@ -305,19 +330,20 @@ class Component extends DCLogic {
else if (k === 'empty') body = Empty('file-plus', 'No entries yet', 'Use New entry to add the first event. Each entry follows the fields of this content type.', 'New entry')
else {
const rows = ROWS.slice(0, size > 7 ? 7 : 5)
const gc = '48px ' + visCols.map((f, i) => i === 0 ? 'minmax(0,1.6fr)' : f.type === 'boolean' || f.type === 'number' ? '80px' : '120px').join(' ') + ' 110px 150px 130px'
const gc = '48px ' + visCols.map((f, i) => i === 0 ? 'minmax(0,1.6fr)' : f.type === 'boolean' || f.type === 'number' || f.type === 'media' ? '80px' : '120px').join(' ') + ' 110px 150px 130px'
const hdrC = (t, o = {}) => S('display:flex;align-items:center;gap:4px;' + (o.r ? 'justify-content:flex-end;' : ''), t, o.sort && I('arrow-down', 12))
const tbl = D('background:var(--ui-bg);border:1px solid var(--ui-border)', D('display:grid;grid-template-columns:' + gc + ';gap:12px;height:36px;align-items:center;padding:0 12px;background:var(--ui-bg-elevated);color:var(--ui-text-muted);font-weight:500', hdrC('ID'), ...visCols.map(f => hdrC(f.label, { r: f.type === 'number' })), hdrC('Created'), hdrC('Updated', { sort: true }), hdrC('Updated by')),
...rows.map((r, i) => D('display:grid;grid-template-columns:' + gc + ';gap:12px;height:48px;align-items:center;padding:0 12px;border-top:1px solid var(--ui-border);background:' + (i === 0 && false ? 'var(--ui-bg-elevated)' : 'transparent'), S(mono + 'font-size:12px;color:var(--ui-text-muted)', String(r.id)), ...visCols.map((f, j) => D('min-width:0;' + (j === 0 ? 'font-weight:500;color:var(--ui-text-highlighted);display:flex' : 'display:grid'), Cell(f, r[f.key]))), S('color:var(--ui-text-muted);white-space:nowrap', r.c), S('color:var(--ui-text-muted);white-space:nowrap', r.u.split(',')[0]), S('overflow:hidden;text-overflow:ellipsis;white-space:nowrap', r.by))))
const cards = D('background:var(--ui-bg);border:1px solid var(--ui-border)', ...ROWS.slice(0, 6).map((r, i) => D('display:flex;align-items:center;gap:8px;padding:12px 4px 12px 16px;border-top:' + (i ? '1px solid var(--ui-border)' : 'none') + ';min-height:68px', D('flex:1;min-width:0;display:flex;flex-direction:column;gap:4px', S('font-weight:500;font-size:15px;line-height:21px;color:var(--ui-text-highlighted);overflow:hidden;text-overflow:ellipsis;white-space:nowrap', r.title), D('display:flex;align-items:center;gap:8px;font-size:12px;color:var(--ui-text-muted)', S('', r.starts_on), r.category && Cell(EV[5], r.category), S('overflow:hidden;text-overflow:ellipsis;white-space:nowrap', '· ' + r.by))), S('width:36px;height:44px;display:flex;align-items:center;justify-content:center;color:var(--ui-text-muted)', I('chevron-right', 18)))))
const cards = D('background:var(--ui-bg);border:1px solid var(--ui-border)', ...ROWS.slice(0, 6).map((r, i) => D('display:flex;align-items:center;gap:8px;padding:12px 4px 12px 16px;border-top:' + (i ? '1px solid var(--ui-border)' : 'none') + ';min-height:68px', visCols.some(f => f.type === 'media') && cellM(r.thumbnail, 32), D('flex:1;min-width:0;display:flex;flex-direction:column;gap:4px', S('font-weight:500;font-size:15px;line-height:21px;color:var(--ui-text-highlighted);overflow:hidden;text-overflow:ellipsis;white-space:nowrap', r.title), D('display:flex;align-items:center;gap:8px;font-size:12px;color:var(--ui-text-muted)', S('', r.starts_on), r.category && Cell(EV[5], r.category), S('overflow:hidden;text-overflow:ellipsis;white-space:nowrap', '· ' + r.by))), S('width:36px;height:44px;display:flex;align-items:center;justify-content:center;color:var(--ui-text-muted)', I('chevron-right', 18)))))
const pgB = (c, on, dis) => S('width:' + bh + 'px;height:' + bh + 'px;display:flex;align-items:center;justify-content:center;border:1px solid ' + (on ? 'var(--ui-primary)' : 'var(--ui-border-accented)') + ';background:' + (on ? 'var(--rc-sand)' : 'var(--ui-bg)') + ';color:' + (on ? 'var(--rc-on-sand)' : 'var(--ui-text-highlighted)') + ';opacity:' + (dis ? 0.4 : 1) + ';font-weight:' + (on ? 500 : 400), typeof c === 'string' && c.length > 2 ? I(c, 14) : c)
const pager = !paged ? S('color:var(--ui-text-muted)', '7 entries') : m ? D('display:flex;align-items:center;justify-content:space-between;gap:8px', pgB('chevron-left', false, true), S('color:var(--ui-text-muted)', 'Page 1 of 8'), pgB('chevron-right')) : D('display:flex;align-items:center;gap:16px', S('flex:1;color:var(--ui-text-muted)', 'Showing 1–5 of 37'), D('display:flex;align-items:center;gap:8px;height:32px;padding:0 10px;border:1px solid var(--ui-border-accented);background:var(--ui-bg)', '5 per page', I('chevron-down', 14, 'color:var(--ui-text-muted)')), D('display:flex;gap:4px', pgB('chevrons-left', false, true), pgB('chevron-left', false, true), pgB('1', true), pgB('2'), pgB('3'), pgB('…'), pgB('8'), pgB('chevron-right'), pgB('chevrons-right')))
body = D('display:flex;flex-direction:column;gap:12px;min-height:0', m ? cards : tbl, pager)
}
main = Page(pad, Title('Events', 'events · 7 fields', !m && B('New entry', { k: 'primary', icon: 'plus', px: 14, dis: k === 'loading' })), ...(k === 'error' || k === 'empty' || k === 'loading' ? [k !== 'error' ? toolbar : null, body] : [toolbar, body]))
if (m && k !== 'error' && k !== 'loading') ov.push(Fab('New entry'))
if (k === 'cols') {
const items = EV.map((f, i) => [f, i < 4])
if (k === 'thumbtip' && !m) ov.push(D('position:absolute;z-index:30;left:609px;top:416px;padding:6px 8px;background:var(--ui-bg-inverted);color:var(--ui-text-inverted);font-size:12px;line-height:18px;box-shadow:var(--rc-shadow-pop);white-space:nowrap', 'Image no longer in the library'))
if (k === 'cols' || k === 'thumbcols') {
const items = k === 'thumbcols' ? [...EV, THUMB].map(f => [f, ['title', 'thumbnail', 'starts_on', 'category'].includes(f.key)]) : EV.map((f, i) => [f, i < 4])
const lst = D('display:flex;flex-direction:column', ...items.map(([f, on]) => D('display:flex;align-items:center;gap:10px;min-height:' + (m ? 48 : 36) + 'px;padding:0 8px', Chk(on), I(FT[f.type][0], 14, 'color:var(--ui-text-muted)'), S('flex:1', f.label), S(mono + 'font-size:12px;color:var(--ui-text-muted)', f.key))), D('display:flex;align-items:center;gap:10px;min-height:' + (m ? 48 : 36) + 'px;padding:0 8px;color:var(--ui-text-muted)', Chk(false), I('clock', 14), S('', 'Created and updated dates always show')))
if (m) ov.push(Sheet({ title: 'Columns', z: 45 }, [S('color:var(--ui-text-muted)', 'Choose up to 6 fields to show. 4 selected.'), lst], [B('Reset', { full: true }), B('Done', { k: 'primary', full: true })]))
else ov.push(D('position:absolute;z-index:40;left:' + (224 + 24 + 330) + 'px;top:' + (48 + 24 + 28 + 18 + 16 + 40) + 'px;width:300px;background:var(--ui-bg);border:1px solid var(--ui-border);box-shadow:var(--rc-shadow-pop);padding:8px;display:flex;flex-direction:column;gap:8px', D('display:flex;justify-content:space-between;padding:4px 8px', S('font-weight:600', 'Columns'), S('color:var(--ui-text-muted);font-size:12px', '4 of 6')), lst, D('display:flex;justify-content:flex-end;padding:4px 8px', B('Reset', { h: 28, fs: 12 }))))
@@ -327,6 +353,7 @@ class Component extends DCLogic {
// 6 entry
if (v === 'entry') {
const mk = s.m || null, mErr = mk === 'err' || mk === 'missingreq'
shell.nav = 'content'; shell.contentOn = 'events'; shell.crumbs = ['Content', 'Events', k === 'new' || k === 'required' ? 'New entry' : 'Lime plaster workshop']; shell.mTitle = k === 'new' || k === 'required' ? 'New entry' : 'Lime plaster workshop'; shell.mLead = 'arrow-left'; shell.mAction = k === 'new' || k === 'required' ? null : 'trash-2'
if (k === 'notfound') main = Center('file-x', 'Entry not found', 'It may have been deleted by someone else.', B('Back to Events', { k: 'primary', px: 16 }))
else {
@@ -338,16 +365,18 @@ class Component extends DCLogic {
if (k === 'rules') { val.title = 'Lime plaster workshop, two days of hands-on work with the whole team on site and lunch'; E.title = 'Title can be up to 80 characters.'; val.ends_on = '31/11/2026'; E.ends_on = 'Ends on must be a date, like 2026-11-21.'; val.capacity = '6000'; E.capacity = 'Capacity must be at most 5000.'; val.category = 'Seminar'; E.category = 'Choose one of: Talk, Workshop or Meetup.' }
if (k === 'unique') { val.title = 'Heat pumps: what the numbers say'; E.title = 'Another entry already uses this Title. Enter a different one.' }
const dis = k === 'saving' || k === 'changed'
const sk = k === 'dirty' ? 'dirty' : k === 'saving' ? 'saving' : k === 'saved' ? 'saved' : k === 'fail' ? 'fail' : (k === 'required' || k === 'rules' || k === 'unique') ? 'fail' : 'clean'
const chip = k === 'required' || k === 'rules' || k === 'unique' ? S('display:flex;align-items:center;gap:6px;font-size:12px;color:var(--ui-error);white-space:nowrap', I('circle-alert', 14), 'Not saved') : isNew ? S('font-size:12px;color:var(--ui-text-muted);white-space:nowrap', 'New entry') : stChip(sk)
const canSave = k === 'dirty' || k === 'fail' || k === 'new' || k === 'required' || k === 'rules' || k === 'unique'
const sk = k === 'dirty' ? 'dirty' : k === 'saving' ? 'saving' : k === 'saved' ? 'saved' : k === 'fail' ? 'fail' : (k === 'required' || k === 'rules' || k === 'unique' || mErr) ? 'fail' : 'clean'
const chip = k === 'required' || k === 'rules' || k === 'unique' || mErr ? S('display:flex;align-items:center;gap:6px;font-size:12px;color:var(--ui-error);white-space:nowrap', I('circle-alert', 14), 'Not saved') : isNew ? S('font-size:12px;color:var(--ui-text-muted);white-space:nowrap', 'New entry') : stChip(sk)
const canSave = k === 'dirty' || k === 'fail' || k === 'new' || k === 'required' || k === 'rules' || k === 'unique' || mErr
const acts = D('display:flex;align-items:center;gap:' + (m ? 8 : 12) + 'px', !m && chip, !m && !isNew && B('Delete', { k: 'del', icon: 'trash-2' }), !m && B('Cancel', { dis: dis }), !m && B(k === 'saving' ? 'Saving…' : 'Save', { k: 'primary', icon: k === 'saving' ? 'loader-circle' : null, px: 16, dis: !canSave && k !== 'saving' }))
const fieldsUI = EV.map(f => { const vv = val[f.key], e = E[f.key]; const o = { v: vv, err: e, dis, def: isNew && f.key === 'online', focus: k === 'dirty' && f.key === 'title' }; if (f.key === 'title') { const n = (vv || '').length; o.count = n + ' / 80'; o.countErr = n > 80; if (k === 'unique') o.count = n + ' / 80' } if (f.key === 'description') { o.tab = k === 'preview' ? 'preview' : 'write'; o.help = 'Markdown. Switch to Preview to check the result.' } if (f.key === 'capacity') o.help = 'Between 1 and 5000.'; if (f.key === 'title' && !e) o.help = 'Each entry needs a different title.'; return Ctl(f, o) })
const mo = { hover: { st: 'filled', hover: true }, focus: { st: 'filled', focus: true }, filled: { st: 'filled' }, err: { st: 'empty', err: 'Pick an image for Thumbnail.', ringBtn: 'pick' }, missing: { st: 'missing' }, missingreq: { st: 'missing', err: 'Pick an image for Thumbnail.', ringBtn: 'choose' } }[mk] || { st: 'empty' }
const mUI = mk && Ctl({ ...THUMB, req: ['emptyreq', 'err', 'missingreq'].includes(mk) }, { ...mo, dis })
const grid = (a, b) => D('display:grid;grid-template-columns:' + (m ? '1fr' : '1fr 1fr') + ';gap:16px', a, b)
const form = D('background:var(--ui-bg);border:1px solid var(--ui-border);padding:' + (m ? 16 : 24) + 'px;display:flex;flex-direction:column;gap:20px;max-width:760px;opacity:' + (dis ? 0.7 : 1), fieldsUI[0], grid(fieldsUI[1], fieldsUI[2]), grid(fieldsUI[3], fieldsUI[4]), fieldsUI[5], fieldsUI[6], D('border-top:1px solid var(--ui-border);padding-top:16px;display:grid;grid-template-columns:' + (m ? '1fr' : 'auto 1fr') + ';gap:6px 16px;font-size:12px;line-height:18px', S('color:var(--ui-text-muted)', 'Entry'), S('', isNew ? 'Not saved yet' : S(mono, 'events / 42')), S('color:var(--ui-text-muted)', 'Created by'), S('', isNew ? '–' : 'Inès Duarte · 12 Oct 2026, 09:14'), S('color:var(--ui-text-muted)', 'Updated by'), S('', isNew ? '–' : k === 'saved' ? 'Marta Alves · 19 Oct 2026, 11:02' : 'Marta Alves · 15 Oct 2026, 11:02')))
const ban = k === 'fail' ? Alert('error', 'circle-x', 'Couldn\'t save the entry', 'Something went wrong on our side. Your changes are still here. Try again in a moment.', 'Try again') : k === 'changed' ? Alert('warning', 'triangle-alert', 'The fields of Events changed', 'A field was removed and a new required field, Room, was added after you opened this form. Reload the form to continue. What you typed here can\'t be saved against the old fields.', 'Reload form') : k === 'unique' ? Alert('error', 'circle-x', 'Not saved', 'Another entry already uses this title. Change it and save again.') : null
const form = D('background:var(--ui-bg);border:1px solid var(--ui-border);padding:' + (m ? 16 : 24) + 'px;display:flex;flex-direction:column;gap:20px;max-width:760px;opacity:' + (dis ? 0.7 : 1), fieldsUI[0], grid(fieldsUI[1], fieldsUI[2]), grid(fieldsUI[3], fieldsUI[4]), fieldsUI[5], fieldsUI[6], mUI, D('border-top:1px solid var(--ui-border);padding-top:16px;display:grid;grid-template-columns:' + (m ? '1fr' : 'auto 1fr') + ';gap:6px 16px;font-size:12px;line-height:18px', S('color:var(--ui-text-muted)', 'Entry'), S('', isNew ? 'Not saved yet' : S(mono, 'events / 42')), S('color:var(--ui-text-muted)', 'Created by'), S('', isNew ? '–' : 'Inès Duarte · 12 Oct 2026, 09:14'), S('color:var(--ui-text-muted)', 'Updated by'), S('', isNew ? '–' : k === 'saved' ? 'Marta Alves · 19 Oct 2026, 11:02' : 'Marta Alves · 15 Oct 2026, 11:02')))
const ban = k === 'fail' ? Alert('error', 'circle-x', 'Couldn\'t save the entry', 'Something went wrong on our side. Your changes are still here. Try again in a moment.', 'Try again') : k === 'changed' && mk ? Alert('warning', 'triangle-alert', 'The fields of Events changed', 'The Thumbnail field was changed after you opened this form. Reload the form to continue. What you typed here can\'t be saved against the old fields.', 'Reload form') : k === 'changed' ? Alert('warning', 'triangle-alert', 'The fields of Events changed', 'A field was removed and a new required field, Room, was added after you opened this form. Reload the form to continue. What you typed here can\'t be saved against the old fields.', 'Reload form') : k === 'unique' ? Alert('error', 'circle-x', 'Not saved', 'Another entry already uses this title. Change it and save again.') : null
const bar = m && D('flex-shrink:0;display:flex;align-items:center;gap:8px;padding:12px 16px;border-top:1px solid var(--ui-border);background:var(--ui-bg);position:relative;z-index:1', B('Cancel', { full: true, dis }), B(k === 'saving' ? 'Saving…' : 'Save', { k: 'primary', full: true, icon: k === 'saving' ? 'loader-circle' : null, dis: !canSave && k !== 'saving' }))
main = D('flex:1;min-width:0;min-height:0;display:flex;flex-direction:column;position:relative', Page(pad, Title(isNew ? 'New entry' : 'Lime plaster workshop', isNew ? 'Events · Fields marked * are required.' : 'Events · Entry 42', acts), m && D('display:flex;align-items:center;justify-content:space-between', chip), ban, form), bar)
main = D('flex:1;min-width:0;min-height:0;display:flex;flex-direction:column;position:relative', Page(pad, Title(isNew ? 'New entry' : 'Lime plaster workshop', isNew ? 'Events · Fields marked * are required.' : 'Events · Entry 42', acts), m && D('display:flex;align-items:center;justify-content:space-between', chip), ban, mk ? D('flex:1;min-height:0;overflow:hidden', D('margin-top:' + (m ? (k === 'changed' ? -740 : -560) : -380) + 'px', form)) : form), bar)
if (k === 'delete') ov.push(Shell({ title: 'Delete this entry?', desc: '"Lime plaster workshop" will be deleted from Events. This can\'t be undone.', close: true, cancel: 'Cancel', confirm: 'Delete entry', tone: 'danger' }, []))
if (k === 'saved') ov.push(Toast('success', 'circle-check', 'Entry saved', '"Lime plaster workshop" is up to date.'))
}
+446
View File
@@ -0,0 +1,446 @@
export const tables = [
{
"title": "Media field: scope",
"tpl": "260px 140px minmax(0,1fr)",
"cols": [
"Screen or state",
"Scope",
"Note"
],
"rows": [
[
"2 Builder: media field selected, new, required",
"Available now",
"Needs the media type in the schema API."
],
[
"3 Review: refused and clean",
"Available now",
"The refusal is known to the client before the server answers."
],
[
"4 Field types: Media frame",
"Available now",
"The filter widget is Later: filtering on custom fields isn't in the API."
],
[
"5 Entry list: Thumbnail column, Columns menu, tooltip",
"Available now",
"Needs image summaries in the entry list payload."
],
[
"6 Entry editor: Media control, 10 states",
"Available now",
""
],
[
"10 Picker for fields, 8 states",
"Available now",
"Same endpoints as the article picker."
],
[
"11 Media library usage, 4 states",
"Available now",
"Needs entries in the usage endpoint."
],
[
"1 Schema list: custom type read-only view",
"Available now",
"Table only; the route is a decision, see conflicts."
],
[
"Several images in one field",
"Not drawn",
"Out of scope."
]
]
},
{
"title": "Media field: exact copy",
"tpl": "200px 200px minmax(0,1fr)",
"cols": [
"Surface",
"Element",
"Copy"
],
"rows": [
[
"Inspector",
"Hint",
"Holds one image from the media library. Entries link to the image instead of keeping a copy, so they always show its current version."
],
[
"Inspector",
"Locked type",
"Media · Can't change after saving."
],
[
"Inspector",
"Required",
"Required · An entry can't be saved with this field empty."
],
[
"Field row",
"Tag",
"Required"
],
[
"Review",
"Refusal row",
"Add Thumbnail · Can't be applied · Media, required. A media field can't have a default, so the 12 existing entries would have no image. Make Thumbnail optional to add it."
],
[
"Review",
"Clean row",
"Add Thumbnail · Media, optional. 12 entries are unaffected."
],
[
"Control",
"Empty",
"No image selected. · Pick an image"
],
[
"Control",
"Filled",
"lime-plaster-workshop.jpg · 1600 × 900 · 240 KB · Change image · Remove"
],
[
"Control",
"Help",
"One image from your library."
],
[
"Control",
"Error",
"Pick an image for Thumbnail."
],
[
"Control",
"Missing",
"This image is no longer in the library · Choose another image · Clear"
],
[
"Control",
"Missing help",
"Optional: You can still save. The entry keeps the link until you change it. Required: Thumbnail is required. Choose another image to save."
],
[
"Control",
"Announcements (live, polite)",
"Image selected: lime-plaster-workshop.jpg · Image removed from Thumbnail. · Thumbnail cleared."
],
[
"Read view",
"Rules cell",
"Optional · One image from the library"
],
[
"Gallery",
"Name, description",
"Media · One image from your media library"
],
[
"Picker",
"Title, search, row",
"Choose an image · Search by filename · No image · Leave this field empty."
],
[
"Picker",
"Badge and buttons",
"Current · Load more · Cancel · Use this image · Remove image (when No image is chosen)"
],
[
"Picker",
"States",
"Your library is empty · Images you upload appear here, ready to use in any article or entry. · Upload an image · Couldn't load your library · Check your connection and try again. · Try again"
],
[
"Entry list",
"Header, empty, missing",
"Thumbnail · – · Image no longer in the library"
],
[
"Media library",
"Badge and tooltip",
"Used in 3 · Used in entries: 3"
],
[
"Media library",
"Panel",
"Used in entries · and 2 more"
],
[
"Media library",
"Delete",
"Delete an image that's in use? · \"lime-plaster.jpg\" is used in 5 entries and 2 articles. Those entry fields will show \"This image is no longer in the library\", and the articles will show a broken image. This can't be undone. · Cancel · Delete image"
]
]
},
{
"title": "Media field: components, reused and new",
"tpl": "220px 140px minmax(0,1fr)",
"cols": [
"Component",
"Status",
"Notes"
],
"rows": [
[
"AppFrame, SchemaFrame builder rows, Insp, FRow, review dialog rows, entry form, entry list and Columns menu",
"Reused",
"The inspector hides Unique, default and limits for media, as it does for yes or no. One more type tile (seven)."
],
[
"MediaFrame: grid card, list row, detail panel, delete dialog, picker dialog",
"Reused",
"Picker gains a field mode (no alt text, no variant select, Current, No image). Panel gains a Used in entries list. Badge counts articles plus entries."
],
[
"MediaFieldControl",
"New (the only one)",
"Props: label, required, modelValue (image id or null), image (summary or missing), disabled, error. Emits update:modelValue. Opens the picker."
],
[
"Nuxt UI mapping",
"Nuxt UI v4",
"UFormField (label, help, error, required) · UButton \"Pick an image\", \"Change image\", \"Choose another image\" (outline) · UButton \"Remove\", \"Clear\" (ghost) · UModal on desktop and a bottom UDrawer on mobile for the picker, as the article picker · UTooltip in the list and on the badge · UIcon lucide:image, lucide:image-off, lucide:unlink. The thumbnail is a plain button."
]
]
},
{
"title": "Picker and field failures: status to copy",
"tpl": "160px minmax(0,1fr)",
"cols": [
"Request and status",
"Copy"
],
"rows": [
[
"GET /v1/media/ 400",
"That request wasn't valid. Check the fields and try again. (search is trimmed first, so this is rare)"
],
[
"GET /v1/media/ 401, 403",
"Global redirect, no local copy."
],
[
"GET /v1/media/ 429",
"Too many requests. Try again in a few minutes. (countdown alert as on the Media page)"
],
[
"GET /v1/media/ 500, network",
"Couldn't load your library · Check your connection and try again. · Try again (500 body: Something went wrong on our side. Nothing was changed. Try again in a moment.)"
],
[
"POST /v1/media/ 413",
"That file is too large."
],
[
"POST /v1/media/ 400",
"That request wasn't valid. Check the fields and try again."
],
[
"POST /v1/media/ 429",
"Too many requests. Try again in a few minutes."
],
[
"POST /v1/media/ 500, network",
"Something went wrong on our side. Nothing was changed. Try again in a moment."
],
[
"PUT entry 422 invalid_entry thumbnail: required",
"Pick an image for Thumbnail."
],
[
"PUT entry 422 invalid_entry thumbnail: type",
"Thumbnail must be an image from the library. (the image was deleted between the pick and the save)"
],
[
"PUT entry 409",
"This changed somewhere else. Reload and try again."
],
[
"DELETE /v1/media/{id} 404",
"That item no longer exists."
],
[
"DELETE /v1/media/{id} 500, network",
"Something went wrong on our side. Nothing was changed. Try again in a moment."
]
]
},
{
"title": "Row height with media",
"tpl": "220px minmax(0,1fr)",
"cols": [
"Surface",
"Choice and reason"
],
"rows": [
[
"Desktop table",
"The design rule is 48 px rows (56 px for the media library). The brief mentions 32 px, which the design does not use. The thumbnail is 40 px, so a 48 px row keeps 4 px above and below and does not grow. No row exceeds 48 px."
],
[
"Mobile card",
"Cards are 68 px minimum. The thumbnail is 32 px and leads the card. Cards do not grow."
],
[
"Missing image",
"Dashed square with the same 40 px (32 px) footprint, so the columns stay aligned and the row does not move."
]
]
},
{
"title": "Accessibility",
"tpl": "220px minmax(0,1fr)",
"cols": [
"Topic",
"Notes"
],
"rows": [
[
"Group and label",
"MediaFieldControl is role=\"group\" labelled by the field label. A required field adds aria-required to the control button and the * is part of the label text."
],
[
"Button names",
"Pick an image → \"Pick an image for Thumbnail\". Thumbnail button → \"Change image, lime-plaster-workshop.jpg, 1600 by 900, 240 KB\". Remove → \"Remove image from Thumbnail\". Clear → \"Clear Thumbnail\". Missing placeholder: role img, \"Image no longer in the library\". Each name starts with the visible label."
],
[
"Focus order",
"Label, thumbnail, Change image, Remove, help or error. The thumbnail duplicates Change image; if reviewers prefer one stop, make it tabindex -1 and keep the pointer shortcut."
],
[
"Announcements",
"One polite live region on the control: \"Image selected: lime-plaster-workshop.jpg\", \"Image removed from Thumbnail.\", \"Thumbnail cleared.\" No announcement when the picker opens."
],
[
"Focus after actions",
"Picker closes with Use this image: focus goes to Change image. Remove or Clear: focus goes to Pick an image. Cancel or Esc: focus returns to the button that opened it. Save refused: focus goes to the first invalid control (Pick an image or Choose another image)."
],
[
"Error",
"The error text has an id. The control button gets aria-invalid=\"true\" and aria-describedby set to the error id, then the help id. aria-invalid is not defined for group, so it sits on the focusable button."
],
[
"Picker",
"Tabs follow the existing tablist pattern. Tiles are buttons with aria-pressed and names like \"stone-steps.jpg, 310 KB\" and \", Current\". No image is a button with aria-pressed. Use this image uses aria-disabled while nothing is chosen. Load more keeps focus until new tiles arrive."
],
[
"Contrast and targets",
"Current badge is on-sand on sand (14.3). Text on selected tiles uses on-sand, never muted. The hover bar is inverted text on inverted ground (18.9). Dashed borders use border-accented (3.6). Mobile targets are 44 px."
],
[
"Motion and touch",
"No hover on mobile. Hover and focus never carry information alone."
]
]
},
{
"title": "Needs backend",
"tpl": "260px minmax(0,1fr)",
"cols": [
"Item",
"What is needed"
],
"rows": [
[
"Media field type",
"Schema API accepts type \"media\" with label, key, required only. The value is an image id or null. Writes with a missing id on a changed value return 422 invalid_entry, type."
],
[
"Image summary in entries",
"Entry and list responses include, per media field, filename, width, height, size and a small thumbnail URL, or a flag that the image is missing, so the editor and list need no extra requests."
],
[
"Usage by entries",
"GET /v1/media/{id}/usage returns articles and entries (content type name, key, entry id, title), a total count and the first few items."
],
[
"Counts for the badge and delete",
"GET /v1/media/ list items carry the combined use count. DELETE keeps working for used images; the entries keep their ids."
],
[
"Required with entries",
"The server refuses a new required media field on a type with entries with schema_incompatible. The client shows the refusal first."
]
]
},
{
"title": "Media field: conflicts with the existing design, decide before coding",
"tpl": "40px 260px minmax(0,1fr)",
"cols": [
"#",
"Brief",
"Existing design and what the board does"
],
"rows": [
[
"1",
"Rows follow a 32 px density rule.",
"Tables use 48 px rows (56 px for media) and 68 px cards. Drawn at 48 and 68; the 40 px thumbnail fits without growing a row."
],
[
"2",
"Thumbnail sits between Description and Starts on.",
"In the existing editor Description is the last field and Starts on comes second. Drawn after Description, at the end of the form, which is schema order. Moving it needs a different form order."
],
[
"3",
"\"Used in 3\" counts entries.",
"Today \"Used in N\" counts articles. Drawn as articles plus entries; the tooltip and the panel split them."
],
[
"4",
"Delete title \"Delete this image?\".",
"The existing dialog for an image in use is \"Delete an image that's in use?\" with an articles list. Kept that title and added the entries list. \"Delete this image?\" stays the unused-image title."
],
[
"5",
"\"Clear\" in the missing state.",
"The glossary says Remove detaches and the filled state uses Remove. Kept \"Clear\" as written. Suggest Remove for both."
],
[
"6",
"\"1600 x 900 - 240 KB\".",
"The design uses × and the middle dot (\"1600 × 900 · 240 KB\")."
],
[
"7",
"Refuse the required media field in the review step.",
"The review is informational and Apply changes is never disabled; the server decides. This one case is certain, so Apply is off. Alternative: leave Apply on and show the 422 refusal dialog."
],
[
"8",
"Primary button \"Use this image\".",
"The article picker says \"Insert image\". When No image is chosen the button reads \"Remove image\" (my addition). The picker keeps its existing copy for empty and failed states."
],
[
"9",
"Pick an image on empty optional fields too.",
"The brief names the button for required fields only. One name covers both."
],
[
"10",
"Read view of a custom type.",
"Only owners and admins see Schema, and they edit. No read-only route exists for custom types. Table drawn as the built-in one; the route is a decision."
],
[
"11",
"Thumbnail focus ring.",
"The thumbnail and Change image open the same picker, so there are two tab stops. See accessibility."
],
[
"12",
"Disabled look.",
"Entry form fields dim to 60% and foundations.md says 40%. The control follows the form."
],
[
"13",
"Picker page behind the dialog.",
"The existing picker frame shows the article editor. The field picker shows a stand-in for the entry form."
]
]
}
]
+45 -7
View File
@@ -1,3 +1,4 @@
import { tables as mfTables } from './media-field-tables.js'
const N = 'available now', L = 'later'
const st = (name, scope, trigger, s, copy, o = {}) => ({ name, scope, trigger, s, copy, ...o })
@@ -8,7 +9,8 @@ export const groups = [
st('Empty: no custom type yet', N, 'GET /v1/content-type returns []. Built-ins are still listed below.', { v: 'types', k: 'empty' }, 'No content types yet · Create a content type to manage your own kind of content, like events or recipes. The built-in types stay as they are. · New content type'),
st('Error', N, '500 or network failure on the list request.', { v: 'types', k: 'error' }, 'Couldn\'t load content types · GET /v1/content-type failed. Check your connection and try again. · Try again'),
st('Forbidden (403)', N, 'A user who is not owner or admin types /schema. There is no sidebar entry, so the page explains instead of redirecting.', { v: 'types', k: 'forbidden' }, 'You don\'t have access to Schema · Only owners and admins can change content types. You can still add and edit entries from the Content menu. · Go to Home'),
st('Built-in type: read-only view', N, 'Click Articles in the list. No edit, no delete, no add field.', { v: 'types', k: 'builtin' }, 'Articles · Built-in · Managed by RenewCMS · Articles is a built-in type. You can read its fields here, but you can\'t edit it, delete it or add fields. · Label · Key · Type · Rules · Entries of built-in types are managed from their own screens, like Articles and Authors.')
st('Built-in type: read-only view', N, 'Click Articles in the list. No edit, no delete, no add field.', { v: 'types', k: 'builtin' }, 'Articles · Built-in · Managed by RenewCMS · Articles is a built-in type. You can read its fields here, but you can\'t edit it, delete it or add fields. · Label · Key · Type · Rules · Entries of built-in types are managed from their own screens, like Articles and Authors.'),
st("Custom type: read-only view", N, "The fields table of a custom type with a media field. Same table as the built-in view; the Media type shows the image icon and the name \"Media\".", {"v":"types","k":"customro"}, "Events · Read only · You can read these fields here · Only an owner or admin can change a content type. · Label · Key · Type · Rules · Thumbnail · thumbnail · Media · One image from the library")
] },
{ label: '2 Schema builder', title: '2 Schema builder', route: '/schema/new, /schema/:key', api: 'POST /v1/content-type, GET/PUT /v1/content-type/{key}', auth: 'Owner or admin', note: 'One screen, three regions: type name and key on top, ordered field list on the left, field inspector on the right, collapsible API preview at the bottom. Mobile: the list is the page, the inspector is a 92% sheet, the API preview is a sheet. Field keys and types of saved fields are locked; fields added since the last save can still choose both.', states: [
st('New type', N, '/schema/new. One starter field is added because a type needs at least one.', { v: 'builder', k: 'new' }, 'New content type · Name · For example, Events · Key · events · Used in URLs and the API. Lowercase letters, digits and hyphens. It can\'t change after you save. · Fields · 1 of 50 · Add field · Field: Title · Label · Key · The name used in the API. Starts with a letter. Lowercase letters, digits and underscores. · Type · Required · An entry can\'t be saved with this field empty. · Unique values · Default value · Used when an entry is created and this field is left out. · Shortest · Longest · Counted in characters. Entries show a counter. · Save · Discard'),
@@ -26,7 +28,10 @@ export const groups = [
st('Save failed', N, '500 or network failure. Nothing was sent as saved; the edits stay.', { v: 'builder', k: 'fail' }, 'Save failed · Couldn\'t save the content type · Something went wrong on our side. Your changes are still here. Try again in a moment. · Try again'),
st('Key already taken', N, '409 content_type_key_taken on POST.', { v: 'builder', k: 'taken' }, 'The key "events" is already used by another content type. Choose a different key.'),
st('Schema incompatible', N, '422 schema_incompatible on PUT. The review dialog (group 3) closes into this state. Changes of the kinds that can cause it are marked.', { v: 'builder', k: 'incompat' }, 'Nothing was changed · Some entries don\'t fit the new fields, so the whole change was refused. RenewCMS can\'t tell which entries. The changes that can cause this are marked. · Review changes · Possible cause'),
st('Offline', N, 'navigator.onLine is false. Edits are kept; Save is disabled.', { v: 'builder', k: 'offline' }, 'You\'re offline. Changes will be saved when you reconnect. · Waiting for connection')
st('Offline', N, 'navigator.onLine is false. Edits are kept; Save is disabled.', { v: 'builder', k: 'offline' }, 'You\'re offline. Changes will be saved when you reconnect. · Waiting for connection'),
st("Media field selected", N, "Thumbnail was saved before. Key and type are locked. The inspector shows Label, Key, Type and Required only; the hint explains the field holds one image.", {"v":"builder","k":"media"}, "Thumbnail · thumbnail · Field: Thumbnail · Key · Used in the API, so it can't change. · Type · Can't change after saving · Media · One image from your media library · Required · An entry can't be saved with this field empty. · Holds one image from the media library. Entries link to the image instead of keeping a copy, so they always show its current version."),
st("New media field, seven types", N, "Add field, then Media. The type tiles show all seven types; key and type can still change.", {"v":"builder","k":"mnew"}, "New · Type · Text · Rich text · Number · Yes or no · Date · Choice · Media · One image from your media library · Key · The name used in the API. Starts with a letter. Lowercase letters, digits and underscores."),
st("Media field, required", N, "A saved required media field. The row carries the Required marker.", {"v":"builder","k":"mreq"}, "Thumbnail · thumbnail · Required (marker) · Required · An entry can't be saved with this field empty.")
] },
{ label: '3 Review and delete', title: '3 Schema change review and delete type', route: '/schema/:key (dialogs)', api: 'PUT /v1/content-type/{key}, DELETE /v1/content-type/{key}', auth: 'Owner or admin', note: 'The review opens on Save when the type already has entries (37 here). It is informational: the server decides compatibility. Destructive changes (removing a field or a choice, tightening a limit, making a field unique or required) carry a warning flag. Per-change entry counts and a full diff are later.', states: [
st('Review before saving', N, 'Save on a type that has entries.', { v: 'review', k: 'review' }, 'Review changes to Events · Apply them to save the content type. · Add 2 fields, change 1, remove 1 · Events has 37 entries. Each one is checked against the new fields when you apply. · Add Speaker · Text, optional. · Add Room · Choice, required, default "Main hall". Existing entries get the default, so they still fit. · Change Capacity · Highest value goes from 5000 to 2000. · Entries may not fit · Remove Description · Entries stop returning its values. · Removes data · Flagged changes can be refused if existing entries don\'t fit. If that happens, nothing is changed. · Back to editing · Apply changes'),
@@ -35,9 +40,11 @@ export const groups = [
st('Review with counts and diff', L, 'Per-change entry counts and a full diff need an API that does not exist yet.', { v: 'review', k: 'later' }, 'Affects 0 entries · Affects 37 entries · Affects 3 entries · Affects 31 entries · View full diff · Per-change counts and diff come later', { notNow: true }),
st('Delete type: blocked', N, 'Delete content type on a type with entries. No confirm button.', { v: 'review', k: 'blocked' }, 'You can\'t delete Events yet · A content type can only be deleted when it has no entries. · Events has 37 entries · Delete all of its entries first, then delete the content type. · Close · View entries'),
st('Delete type: confirm', N, 'Delete content type on an empty type.', { v: 'review', k: 'confirm' }, 'Delete Recipes? · Recipes has no entries. Its fields and its API routes will be deleted. This can\'t be undone. · Key: recipes · Cancel · Delete content type'),
st('Delete type: server fallback (409)', N, '409 content_type_has_entries. An entry was added after the page loaded.', { v: 'review', k: 'fallback' }, 'Recipes now has entries · Someone added an entry after this page loaded, so nothing was deleted. Delete the entries first, then try again. · Close · View entries')
st('Delete type: server fallback (409)', N, '409 content_type_has_entries. An entry was added after the page loaded.', { v: 'review', k: 'fallback' }, 'Recipes now has entries · Someone added an entry after this page loaded, so nothing was deleted. Delete the entries first, then try again. · Close · View entries'),
st("Review: required media field refused", N, "Thumbnail is required and Events has 12 entries. A media field can't have a default, so Apply is off.", {"v":"review","k":"mrefuse"}, "Review changes to Events · Apply them to save the content type. · Add 1 field · Events has 12 entries. Each one is checked against the new fields when you apply. · Add Thumbnail · Can't be applied · Media, required. A media field can't have a default, so the 12 existing entries would have no image. Make Thumbnail optional to add it. · Back to editing keeps your other changes. · Back to editing · Apply changes (disabled)"),
st("Review: optional media field", N, "Thumbnail is optional.", {"v":"review","k":"mclean"}, "Review changes to Events · Add 1 field · Events has 12 entries. Each one is checked against the new fields when you apply. · Add Thumbnail · Media, optional. 12 entries are unaffected. · Back to editing · Apply changes")
] },
{ label: '4 Field types', title: '4 Field-type gallery', route: 'reference board', api: '', auth: 'n/a', note: 'One frame per type: inspector options, the entry form control (default and open states), the list cell with its empty state, the error message for each rule, and the filter widget. Filters are later: filtering on custom fields is not in the API. Mobile drops the inspector column (the builder frames show it as a sheet).', states: ['text', 'richtext', 'number', 'boolean', 'date', 'select'].map((t, i) => st(['Text', 'Rich text', 'Number', 'Yes or no', 'Date', 'Choice'][i], N, 'type: "' + t + '"', { v: 'gallery', k: t }, ({ text: 'Text · Short text, like a title or a name · Shortest · Longest · characters · 74 / 80 · Fill in Title. · Title must be text. · Title needs at least 3 characters. · Title can be up to 80 characters. · Another entry already uses this Title. Enter a different one.', richtext: 'Rich text · Long text with formatting, written in Markdown · Write · Preview · Markdown. Switch to Preview to check the result. · 86 / 5000 · Not available for rich text. (Unique)', number: 'Number · Whole or decimal numbers · Lowest value · Highest value · Enter a number · Between 1 and 5000. · Description must be a number. · Capacity must be at least 1. · Capacity must be at most 5000.', boolean: 'Yes or no · An on or off switch · On by default · Yes or no fields have no limits. · Not available for yes or no fields. (Unique) · Choose yes or no for Online. · Online must be yes or no.', date: 'Date · A calendar day, without a time · Earliest date · Latest date · Pick a date · Pick a date for Starts on. · Starts on must be a date, like 2026-11-21. · Starts on can\'t be before 1 Jan 2026. · Starts on can\'t be after 31 Dec 2027.', select: 'Choice · One option from a list you define · Choices · Choose an option · Choose one of: Talk, Workshop or Meetup. · Another entry already uses this choice for Category.' })[t])) },
{ label: '4 Field types', title: '4 Field-type gallery', route: 'reference board', api: '', auth: 'n/a', note: 'One frame per type: inspector options, the entry form control (default and open states), the list cell with its empty state, the error message for each rule, and the filter widget. Filters are later: filtering on custom fields is not in the API. Mobile drops the inspector column (the builder frames show it as a sheet).', states: ['text', 'richtext', 'number', 'boolean', 'date', 'select', 'media'].map((t, i) => st(['Text', 'Rich text', 'Number', 'Yes or no', 'Date', 'Choice', 'Media'][i], N, 'type: "' + t + '"', { v: 'gallery', k: t }, ({ text: 'Text · Short text, like a title or a name · Shortest · Longest · characters · 74 / 80 · Fill in Title. · Title must be text. · Title needs at least 3 characters. · Title can be up to 80 characters. · Another entry already uses this Title. Enter a different one.', richtext: 'Rich text · Long text with formatting, written in Markdown · Write · Preview · Markdown. Switch to Preview to check the result. · 86 / 5000 · Not available for rich text. (Unique)', number: 'Number · Whole or decimal numbers · Lowest value · Highest value · Enter a number · Between 1 and 5000. · Description must be a number. · Capacity must be at least 1. · Capacity must be at most 5000.', boolean: 'Yes or no · An on or off switch · On by default · Yes or no fields have no limits. · Not available for yes or no fields. (Unique) · Choose yes or no for Online. · Online must be yes or no.', date: 'Date · A calendar day, without a time · Earliest date · Latest date · Pick a date · Pick a date for Starts on. · Starts on must be a date, like 2026-11-21. · Starts on can\'t be before 1 Jan 2026. · Starts on can\'t be after 31 Dec 2027.', media: 'Media · One image from your media library · Label · Key · Required · Holds one image from the media library. Entries link to the image instead of keeping a copy, so they always show its current version. · Pick an image · No image selected. · One image from your library. · Change image · Remove · lime-plaster-workshop.jpg · 1600 × 900 · 240 KB · This image is no longer in the library · Choose another image · Clear · Pick an image for Thumbnail. · Thumbnail must be an image from the library. · Not used for media. · Thumbnail: has an image (later)', select: 'Choice · One option from a list you define · Choices · Choose an option · Choose one of: Talk, Workshop or Meetup. · Another entry already uses this choice for Category.' })[t])) },
{ label: '5 Content and entry list', title: '5 Content navigation and entry list', route: '/content/:key', api: 'GET /v1/content-type/{key}, GET /v1/content-type/{key}/entry', auth: 'Any verified user', note: 'The sidebar gets a "Content" group, one item per custom type (a default icon: types have no icon in the API). With more than 5 types it shows the first 5 and the selected one, then "Show all N"; long names truncate with the full name in a tooltip. On mobile the group is one collapsed row in the drawer. List: ID, up to 6 chosen field columns (default: first 4), Created, Updated, Updated by. Sort: ID, Created, Updated, either direction (default Updated, newest first). Page size 5, 25, 50, 100 (default 25). No filter or search. URL: /content/events?page=2&size=50&sort=created_at:desc (defaults omitted). The response carries total, page, size and sort; the summary, the pager and the review dialog use them.', states: [
st('Populated', N, '/content/events. 7 entries, one page: no pager, only the count.', { v: 'entries', k: 'ok' }, 'Content · Events · events · 7 fields · New entry · Sort by · Last updated · Columns · Edit content type · ID · Title · Starts on · Ends on · Online · Created · Updated · Updated by · 7 entries'),
st('Paginated, 5 per page', N, '/content/events?size=5. 37 entries.', { v: 'entries', k: 'paged' }, 'Showing 1–5 of 37 · 5 per page · Page 1 of 8 (mobile)'),
@@ -47,7 +54,10 @@ export const groups = [
st('Empty for this type', N, 'Total is 0. The hint points to New entry.', { v: 'entries', k: 'empty' }, 'No entries yet · Use New entry to add the first event. Each entry follows the fields of this content type. · New entry'),
st('Error', N, '500 or network failure.', { v: 'entries', k: 'error' }, 'Couldn\'t load entries · GET /v1/content-type/events/entry failed. Check your connection and try again. · Try again'),
st('Forbidden (403)', N, 'The API answers 403. Unverified accounts are redirected to /register/pending before this.', { v: 'entries', k: 'forbidden', role: 'user' }, 'You don\'t have access to Events · Your account can\'t open this content right now. If you think this is a mistake, ask an owner or an admin. · Go to Home'),
st('Type not found', N, '404 content_type_not_found on /content/unknown.', { v: 'entries', k: 'notfound' }, 'Content type not found · It may have been deleted, or the address may be mistyped. · Go to Home')
st('Type not found', N, '404 content_type_not_found on /content/unknown.', { v: 'entries', k: 'notfound' }, 'Content type not found · It may have been deleted, or the address may be mistyped. · Go to Home'),
st("Thumbnail column", N, "Events list with a Thumbnail column: 40 px square thumbnails, one \"–\", one missing image. Row height stays 48 px. Mobile: 32 px thumbnail leads the card. Not sortable.", {"v":"entries","k":"thumb"}, "Thumbnail · Lime plaster workshop · Winter open day · – · Limewash masterclass · Image no longer in the library (accessible name)"),
st("Columns menu with Thumbnail", N, "Columns. Thumbnail is listed with the image icon.", {"v":"entries","k":"thumbcols"}, "Columns · 4 of 6 · Title · Description · Thumbnail · Starts on · Ends on · Online · Capacity · Category · Reset · Choose up to 6 fields to show. 4 selected."),
st("Missing image: tooltip", N, "Hover or focus on the dashed square (desktop). Mobile has no tooltip.", {"v":"entries","k":"thumbtip"}, "Image no longer in the library")
] },
{ label: '6 Entry editor', title: '6 Entry editor', route: '/content/:key/new, /content/:key/:id', api: 'POST /v1/content-type/{key}/entry, GET/PUT/DELETE /v1/content-type/{key}/entry/{id}', auth: 'Any verified user', note: 'The form is generated from the schema, one control per field in schema order. Required fields carry * and the line "Fields marked * are required." Defaults are pre-filled on create and tagged Default. Saving replaces the whole entry.', states: [
st('New entry', N, '/content/events/new. Online is pre-filled from its default.', { v: 'entry', k: 'new' }, 'New entry · Events · Fields marked * are required. · Default · Each entry needs a different title. · Between 1 and 5000. · Choose an option · Pick a date · Save · Cancel · New entry · Not saved yet'),
@@ -62,7 +72,17 @@ export const groups = [
st('Duplicate unique value (409)', N, '409 invalid_entry: title: unique.', { v: 'entry', k: 'unique' }, 'Not saved · Another entry already uses this title. Change it and save again. · Another entry already uses this Title. Enter a different one.'),
st('Entry not found', N, '404 entry_not_found, for example after a delete elsewhere.', { v: 'entry', k: 'notfound' }, 'Entry not found · It may have been deleted by someone else. · Back to Events'),
st('Schema changed since load', N, '422 invalid_entry: room: required, or unknown_field. The form is read-only until reloaded.', { v: 'entry', k: 'changed' }, 'The fields of Events changed · A field was removed and a new required field, Room, was added after you opened this form. Reload the form to continue. What you typed here can\'t be saved against the old fields. · Reload form'),
st('Delete entry: confirm', N, 'Delete.', { v: 'entry', k: 'delete' }, 'Delete this entry? · "Lime plaster workshop" will be deleted from Events. This can\'t be undone. · Cancel · Delete entry')
st('Delete entry: confirm', N, 'Delete.', { v: 'entry', k: 'delete' }, 'Delete this entry? · "Lime plaster workshop" will be deleted from Events. This can\'t be undone. · Cancel · Delete entry'),
st("Media control: empty, optional", N, "Thumbnail follows Description. Empty optional field.", {"v":"entry","k":"m","m":"empty"}, "Thumbnail · No image selected. · Pick an image · One image from your library."),
st("Media control: empty, required", N, "Field marked *.", {"v":"entry","k":"m","m":"emptyreq"}, "Thumbnail * · No image selected. · Pick an image · One image from your library."),
st("Media control: filled", N, "An image is picked.", {"v":"entry","k":"m","m":"filled"}, "Thumbnail · lime-plaster-workshop.jpg · 1600 × 900 · 240 KB · Change image · Remove · One image from your library."),
st("Media control: hover", N, "Pointer over the thumbnail (desktop). The border darkens and a bar reads Change image. Mobile shows the filled state.", {"v":"entry","k":"m","m":"hover"}, "Change image"),
st("Media control: focus", N, "Keyboard focus on the thumbnail: 2 px primary ring, 2 px offset.", {"v":"entry","k":"m","m":"focus"}, "Change image, lime-plaster-workshop.jpg (accessible name)"),
st("Media control: validation error", N, "Save with a required field empty (422 invalid_entry, required). Focus moves to Pick an image.", {"v":"entry","k":"m","m":"err"}, "Pick an image for Thumbnail. · Not saved"),
st("Media control: image no longer in the library", N, "The image was deleted. The entry keeps the link. Optional field: saving is allowed.", {"v":"entry","k":"m","m":"missing"}, "This image is no longer in the library · You can still save. The entry keeps the link until you change it. · Choose another image · Clear"),
st("Media control: missing image, required", N, "Same, on a required field. Save is refused.", {"v":"entry","k":"m","m":"missingreq"}, "This image is no longer in the library · Thumbnail is required. Choose another image to save. · Choose another image · Clear · Pick an image for Thumbnail. · Not saved"),
st("Media control: saving", N, "PUT in flight. The thumbnail and its buttons are disabled with the rest of the form.", {"v":"entry","k":"saving","m":"filled"}, "Saving…"),
st("Media control: read-only, type changed", N, "422 unknown_field. The form is read-only until reloaded.", {"v":"entry","k":"changed","m":"filled"}, "The fields of Events changed · The Thumbnail field was changed after you opened this form. Reload the form to continue. What you typed here can't be saved against the old fields. · Reload form")
] },
{ label: '7 Relations', title: '7 Relation field and picker', route: '/schema/:key, /content/:key/:id', api: 'not built', auth: 'Owner or admin (picker), any verified user (form)', note: 'All later. The model reads as two sentences, with a live preview of both sides. Three shapes: one to one, one to many, many to many.', states: [
st('Relation in the builder', L, 'A seventh type, Relation, in the type gallery.', { v: 'rel', k: 'builder' }, 'Relation · Related content type · How are they connected? · One to one · Each Event has one Venue, and each Venue has one Event. · One to many · Each Event has one Venue. A Venue has many Events. · Many to many · Each Event has many Venues, and each Venue has many Events. · Each Event has one Venue · Each Venue has many Events · shown on Venue as the field "Events"'),
@@ -77,6 +97,22 @@ export const groups = [
st('Export', L, 'Export on /schema.', { v: 'xport', k: 'export' }, 'Export schema · Download the fields of your content types as a file. Entries aren\'t included. · All content types · 3 content types · One content type · Choose which one · File name · renewcms-schema.json · Import this file on another RenewCMS site to create the same content types. · Cancel · Download file'),
st('Import preview', L, 'A file was chosen.', { v: 'xport', k: 'import' }, 'Import schema · renewcms-schema.json · 3 content types · Create 1, change 1, no change 1 · Recipes · New content type with 4 fields. · Events · Add 2 fields, remove Description. Events has 37 entries on this site. · Removes data · Press mentions · Same as on this site. · Existing entries are checked against the changes when you import. If any entry doesn\'t fit, nothing is imported. · Cancel · Import schema'),
st('Import refused', L, 'The server answers schema_incompatible.', { v: 'xport', k: 'refused' }, 'Nothing was imported · Some entries on this site don\'t fit the imported fields. RenewCMS can\'t tell which entries. The flagged change can cause this. · Try again')
] },
{ label: '10 Media picker for fields', title: '10 Image picker from the entry editor', route: '/content/events/:id (dialog)', api: 'GET /v1/media/?q=&limit=&cursor= · POST /v1/media/', auth: 'Any verified user', note: "The existing picker (Media picker and Editor picker groups of the back-office board) with Upload and Library tabs, single selection, search and Load more. Changes: the title is \"Choose an image\", the primary button reads \"Use this image\", there is no alt text and no variant select, the current image carries \"Current\" in place of \"In this article\", and \"No image\" tops the Library tab for optional fields only. Desktop dialog, mobile bottom sheet. The page behind is a stand-in for the entry editor.", states: [
st("Library: nothing chosen", N, "Change image on an optional field. Current marks the image in the field.", {"frame":"media","kind":"picker","picker":true,"field":true,"pk":{"tab":"Library","cur":1}}, "Choose an image · Upload · Library · Search by filename · No image · Leave this field empty. · Current · Newest first · 48 images · Load more · Cancel · Use this image (disabled)"),
st("Library: image chosen", N, "One tile selected (single selection). A strip shows filename, dimensions and size. No alt text field.", {"frame":"media","kind":"picker","picker":true,"field":true,"pk":{"tab":"Library","cur":1,"sel":4}}, "kitchen-before.webp · 2400 × 1600 · 1.1 MB · Cancel · Use this image"),
st("Library: No image chosen", N, "Optional fields only. The primary button changes.", {"frame":"media","kind":"picker","picker":true,"field":true,"pk":{"tab":"Library","cur":1,"sel":"none"}}, "No image · Leave this field empty. · Cancel · Remove image"),
st("Library: required field", N, "No \"No image\" row.", {"frame":"media","kind":"picker","picker":true,"field":true,"pk":{"tab":"Library","cur":1,"req":true}}, "Choose an image · Cancel · Use this image (disabled)"),
st("Library: empty", N, "Zero images. Upload an image switches to the Upload tab.", {"frame":"media","kind":"picker","picker":true,"field":true,"pk":{"tab":"Library","empty":"first"}}, "Your library is empty · Images you upload appear here, ready to use in any article or entry. · Upload an image"),
st("Library: failed to load", N, "500 or network failure. Other statuses: see the failures table.", {"frame":"media","kind":"picker","picker":true,"field":true,"pk":{"tab":"Library","error":true}}, "Couldn't load your library · Check your connection and try again. · Try again"),
st("Library: loading", N, "First open or a new search. Skeleton tiles after 150 ms.", {"frame":"media","kind":"picker","picker":true,"field":true,"pk":{"tab":"Library","loading":true}}, "(skeleton) · Use this image (disabled)"),
st("Upload tab", N, "The existing upload flow, including crop and resize. The new image lands in the library and is selected.", {"frame":"media","kind":"picker","picker":true,"field":true,"pk":{"tab":"Upload"}}, "Drop an image here, or choose a file · PNG, JPEG, WEBP, SVG · max 10 MB")
] },
{ label: '11 Media library: usage', title: '11 Media library: usage by entries', route: '/media', api: 'GET /v1/media/ · GET /v1/media/{id}/usage · DELETE /v1/media/{id}', auth: 'Verified users', note: "Same Media screens as the back-office board. Entries count as uses: the \"Used in N\" badge adds articles and entries, its tooltip splits them, and the detail panel gains a \"Used in entries\" list (up to 3 links, then \"and N more\"). Deleting an image that entries use says how many and what the fields will show.", states: [
st("Grid: usage badge tooltip", N, "Hover or focus the \"Used in 3\" badge on bathroom-tiles.png (3 entries, no article).", {"frame":"media","ent":true,"tip":10}, "Used in 3 · Used in entries: 3 · Unused"),
st("List view: usage badge", N, "List view; mobile uses the card rows.", {"frame":"media","ent":true,"view":"list"}, "Used in 3 · Used in 7 · Unused"),
st("Detail panel: used in entries", N, "Click lime-plaster.jpg (2 articles, 5 entries). Right-hand panel; full screen on mobile.", {"frame":"media","ent":true,"panel":{"id":11}}, "Used in 2 articles · Used in entries · Events · Lime plaster workshop · Events · Heritage stone walk · Events · Winter open day · and 2 more"),
st("Delete: image used by entries", N, "Delete in the panel.", {"frame":"media","ent":true,"panel":{"id":11},"modal":{"k":"delEnt"}}, "Delete an image that's in use? · \"lime-plaster.jpg\" is used in 5 entries and 2 articles. Those entry fields will show \"This image is no longer in the library\", and the articles will show a broken image. This can't be undone. · Cancel · Delete image")
] }
]
@@ -172,5 +208,7 @@ export const tables = [
['Type picker', 'A radio group. The locked state sets aria-disabled and the line "Can\'t change after saving" is read with the group.'],
['Counters', 'Character counters are polite live regions on pause, not on every key.'],
['Contrast', 'Tokens already computed in foundations.md. Muted text is never placed on sand; selected tiles use --rc-on-sand for their description.'],
['Touch', 'Controls are 44 px on mobile. The inspector, columns and API preview are bottom sheets.']] }
['Touch', 'Controls are 44 px on mobile. The inspector, columns and API preview are bottom sheets.']] },
...mfTables
]
+3
View File
@@ -104,3 +104,6 @@ Keys: a type key is 2 to 40 lowercase letters, digits and hyphens (chosen at cre
Schema changes with entries: Save opens the review ("Add 2 fields, change 1, remove 1"); Apply sends the PUT; schema_incompatible shows "Nothing was changed" and names the kind of change that likely caused it, never an entry. A type with entries cannot be deleted ("You can't delete Events yet").
Entry rules, 422 except unique (409): required, type, min, max, options, unique, unknown_field. Messages are per type and drawn in the field-type gallery (group "Field types").
## Media field (pass 5)
Copy and states are in `media-field-changes.md` (sections 2 to 6). Entry rules for a media field: required 422 "Pick an image for Thumbnail."; type 422 "Thumbnail must be an image from the library."; min, max, options and unique do not apply. A required media field added to a type with entries is refused client side in the review ("Can't be applied") and by the server as 409 schema_incompatible. Image deleted while entries use it: the control shows "This image is no longer in the library"; saving is refused only when the field is required. HTTP statuses for the picker and the field use the table above (400, 401, 403, 404, 409, 413, 429, 500, network).
+2 -2
View File
@@ -39,7 +39,7 @@ Feature: Owners and admins define custom content types, and users manage entries
And a field response has exactly the keys key, label, type, required, unique, default, min, max,
options, with null for an unset default, min and max and [] for no options
And an entry response has exactly the keys id, content_type, data, created_by, updated_by,
created_at, updated_at, where content_type is the type's key
created_at, updated_at, media, where content_type is the type's key
And errors are plain text from http.Error, and the new apperr strings are
content_type_not_found, content_type_key_taken, content_type_has_entries,
invalid_content_type_key, invalid_field, schema_incompatible, entry_not_found and invalid_entry
@@ -201,7 +201,7 @@ Feature: Owners and admins define custom content types, and users manage entries
When the client sends POST /v1/content-type/recipe/entry with body
{"data": {"title": "Pad thai", "difficulty": "easy"}}
Then the response status is 201
And the body has exactly the keys id, content_type, data, created_by, updated_by, created_at, updated_at
And the body has exactly the keys id, content_type, data, created_by, updated_by, created_at, updated_at, media
And content_type is "recipe", created_by and updated_by are 2
And data is {"title": "Pad thai", "difficulty": "easy", "servings": 4, "vegetarian": false}
And data has no "published_on" and no "notes" key
+269
View File
@@ -0,0 +1,269 @@
Feature: Media field type for custom content types
As a site owner or admin
I want a content type field that holds one image from the media library
So that entries link to the library image instead of keeping a copy
Background:
Given internal/domain/contenttype adds the field type "media" next to text, richtext, number, boolean, date and select
And a media field accepts only label, key and required; unique, default, min, max and options are refused with ErrInvalidField
And a stored media value is the id of a library image (uint32, at least 1) or null
And the entry rules required and type apply to a media field; min, max, options and unique never apply
And entry.Validate stays pure; the check that an image exists in the library is done by CreateEntry and UpdateEntry through the domain image.Repository
And CreateEntry, UpdateEntry, GetEntry and ListEntries receive image.Repository, wired only in api/dependecyInjection.go
And a changed value means a value that is not equal to the id the entry holds in the stored document for that key; on POST every non-null value is changed; on PUT the value is unchanged only when the id equals the stored one
And a changed or new non-null value must be an existing library image, else 422 "invalid_entry: <key>: type"
And an unchanged stored id whose image was deleted since passes the type check
And a required media field is never saved empty: null or absent gives 422 "invalid_entry: <key>: required", and so does an unchanged stored id whose image no longer exists
And rules are checked in field order for Validate, then library existence in field order, then unique, and the body names one field per answer
And an entry response keeps its seven keys (id, content_type, data, created_by, updated_by, created_at, updated_at) and adds the key "media"
And data keeps the image id (or null) as the value of each media field
And "media" is a JSON object keyed by media field key, always present ({} when the type has no media field or every media value is null)
And "media"[key] is {"id","filename","width","height","size","thumbnail_url"} for an existing image, with width and height null when unknown, or {"id","missing":true} when the image is gone
And thumbnail_url is the image's original path, the same value as the url of a media list item
And the same "media" object is on POST 201, PUT 200, GET one and every item of the list
And usage in the library means distinct articles, authors, sites and entries; one entry counts once however many of its media fields point at the image
And GET /v1/media/ and GET /v1/media/{id} items carry used_in = articles + authors + sites + entries, and the counts.unused filter counts entries as uses
And GET /v1/media/{id}/usage stays a JSON array and gains items of type "entry"
And an entry usage item is {"type":"entry","id":<entry id>,"fields":[<media field keys>],"content_type_key":"event","content_type_name":"Events","first_field":{"key":<key>,"type":<field type>,"value":<raw stored value or null>}}, with no "title" and no "published"
And first_field is the first field of the type in schema order and its value is the raw stored JSON value, never formatted or truncated by the server; the client formats it with the same rule as the entry list and shows "Entry N" for null
And article, author and site usage items are unchanged and keep their "title"
And usage items are ordered articles by id, authors, sites, then entries by content type name then entry id; the array has no cap and the client shows the first few and the total
And the media routes keep their access rules and their plain-text errors (404 image_not_found, 400 uint32 format)
And DELETE /v1/media/{id} stays allowed for an image used by entries and leaves their data untouched
And MergeMedia (including the purge run) repoints entry media values from every merged copy to the kept image and reports it in the existing counts
And no repository method is added: entries that reference an image are found with contenttype.Repository.List and entry.Repository.ListPage (Unpaged), filtered in Go, so the code works on SQLite, MySQL/MariaDB and PostgreSQL with no JSON operators
And schema compatibility does not consult the library
And the key set assertions of the earlier custom content type and entry features and tests are amended from seven keys to eight
And types: the library images are 7 "lime-plaster.jpg" 1600x900 240000 bytes, 8 "bathroom-tiles.png" 800x600 51200 bytes; the type "event" has title (text, required) then thumbnail (media, label "Thumbnail", optional)
And users: admin id 2 (verified) can write types; any verified user can write entries
Scenario: Creating a content type with a media field
Given a valid jwt cookie for admin 2
When the client sends POST /v1/content-type with fields title (text, required) and {"key":"thumbnail","label":"Thumbnail","type":"media","required":false,"unique":false,"default":null,"min":null,"max":null,"options":[]}
Then the response status is 201
And the thumbnail field comes back with type "media", unique false, default null, min null, max null and options []
Scenario Outline: A media field refuses options it can't have
Given a valid jwt cookie for admin 2
When the client sends POST /v1/content-type with a media field that has <option>
Then the response status is 422
And the response body is "invalid_field"
And no content type is stored
Examples:
| option |
| unique true |
| default 7 |
| default "lime" |
| min 1 |
| max 5 |
| options ["a"] |
Scenario: The type of a saved media field never changes
Given the type "event" has an entry and a saved media field "thumbnail"
When admin 2 sends PUT /v1/content-type/event turning "thumbnail" into a text field
Then the response status is 422 with invalid_field and the schema is unchanged
When admin 2 sends PUT turning the text field "title" into a media field
Then the response status is 422 with invalid_field and the schema is unchanged
Scenario Outline: Adding a media field to a type that has entries
Given the type "event" has 12 entries
When admin 2 sends PUT /v1/content-type/event adding a media field "thumbnail" that is <required>
Then the response status is <status>
And the response body is <message>
And the stored schema is <outcome>
Examples:
| required | status | message | outcome |
| required | 409 | schema_incompatible | unchanged |
| optional | 200 | | updated |
Scenario: Making a media field required
Given the type "event" has a saved optional media field "thumbnail", one entry with image 7 and one entry with null
When admin 2 sends PUT making "thumbnail" required
Then the response status is 409 with schema_incompatible
When the entry holding null is deleted and the PUT is sent again
Then the response status is 200
Scenario: Making a media field required while a stored image is gone
Given the type "event" has a saved optional media field "thumbnail" and one entry holding the id of a deleted image
When admin 2 sends PUT making "thumbnail" required
Then the response status is 200
Scenario: Creating an entry with an image
Given a valid jwt cookie for admin 2
When the client sends POST /v1/content-type/event/entry with {"data":{"title":"Lime plaster workshop","thumbnail":7}}
Then the response status is 201
And data.thumbnail is 7
And media is {"thumbnail":{"id":7,"filename":"lime-plaster.jpg","width":1600,"height":900,"size":240000,"thumbnail_url":"<the image path>"}}
Scenario Outline: An empty optional media field
When the client sends POST /v1/content-type/event/entry with <data>
Then the response status is 201
And data.thumbnail is <stored>
And media is {}
Examples:
| data | stored |
| {"data":{"title":"A","thumbnail":null}} | null |
| {"data":{"title":"A"}} | absent |
Scenario Outline: Entry values that break a media field are refused and store nothing
Given the type "event" has a media field "thumbnail" that is <required>
When the client sends POST /v1/content-type/event/entry with <data>
Then the response status is 422
And the response body is <message>
And no entry exists
Examples:
| required | data | message |
| required | {"data":{"title":"A"}} | invalid_entry: thumbnail: required |
| required | {"data":{"title":"A","thumbnail":null}} | invalid_entry: thumbnail: required |
| optional | {"data":{"title":"A","thumbnail":999}} | invalid_entry: thumbnail: type |
| optional | {"data":{"title":"A","thumbnail":"7"}} | invalid_entry: thumbnail: type |
| optional | {"data":{"title":"A","thumbnail":0}} | invalid_entry: thumbnail: type |
| optional | {"data":{"title":"A","thumbnail":-1}} | invalid_entry: thumbnail: type |
| optional | {"data":{"title":"A","thumbnail":7.5}} | invalid_entry: thumbnail: type |
| optional | {"data":{"title":"A","thumbnail":4294967296}} | invalid_entry: thumbnail: type |
| optional | {"data":{"title":"A","thumbnail":true}} | invalid_entry: thumbnail: type |
| optional | {"data":{"title":"A","thumbnail":[7]}} | invalid_entry: thumbnail: type |
Scenario: Replacing the image of an entry
Given the entry 5 of type "event" holds thumbnail 7
When a verified user sends PUT .../entry/5 with {"data":{"title":"Lime plaster workshop","thumbnail":8}}
Then the response status is 200, data.thumbnail is 8 and media.thumbnail.filename is "bathroom-tiles.png"
When the user sends PUT with thumbnail null on an optional field
Then data.thumbnail is null and media is {}
Scenario: An image deleted after the entry was saved
Given the entry 5 holds thumbnail 7
When DELETE /v1/media/7 answers 204
And the client sends GET /v1/content-type/event/entry/5
Then data.thumbnail is still 7
And media is {"thumbnail":{"id":7,"missing":true}}
Scenario: An unchanged id whose image is gone can still be saved when the field is optional
Given the entry 5 holds thumbnail 7 and the image 7 was deleted
When the user sends PUT .../entry/5 with a new title and thumbnail 7
Then the response status is 200 and data.thumbnail is 7
And media.thumbnail is {"id":7,"missing":true}
Scenario Outline: A changed value must exist even when the old one is gone
Given the entry 5 holds thumbnail 7 and the image 7 was deleted
When the user sends PUT .../entry/5 with thumbnail <value>
Then the response status is <status> and the body is <message>
Examples:
| value | status | message |
| 999 | 422 | invalid_entry: thumbnail: type |
| 8 | 200 | |
| null | 200 | |
Scenario Outline: A required media field with a missing image can't be saved as is
Given the entry 5 of a type whose "thumbnail" is required holds thumbnail 7 and the image 7 was deleted
When the user sends PUT .../entry/5 with thumbnail <value>
Then the response status is <status> and the body is <message>
And the stored entry is <outcome>
Examples:
| value | status | message | outcome |
| 7 | 422 | invalid_entry: thumbnail: required | unchanged |
| null | 422 | invalid_entry: thumbnail: required | unchanged |
| 8 | 200 | | updated |
Scenario: A create always treats the value as changed
Given the image 7 was deleted
When the client sends POST with thumbnail 7
Then the response status is 422 with invalid_entry: thumbnail: type
Scenario: Two broken fields name only one
Given a body with a required field left empty and a media field pointing at a missing image
When the client sends POST
Then the response names one field, with the required and type rules of Validate checked before the library existence
Scenario: Entry list responses carry the media object per item
Given 3 entries: one with image 7, one with image 7 deleted, one with null
When the client sends GET /v1/content-type/event/entry
Then each item keeps its seven keys and adds "media"
And the items' media are one existing object, {"thumbnail":{"id":7,"missing":true}} and {}
And items, total, page and size are unchanged
Scenario: Types without a media field are not enriched
Given the type "recipe" has no media field
When the client sends GET on a recipe entry
Then the body has the seven existing keys and "media" is {}
And the image repository is not called
Scenario: Media list items count entries as uses
Given the image 8 is used by 3 entries (one of them through two media fields) and by no article, author or site
And the image 7 is used by 2 articles and 5 entries
When the client sends GET /v1/media/
Then item 8 has used_in 3 and item 7 has used_in 7
And GET /v1/media/8 has used_in 3
And ?filter=unused does not list 8 or 7, and counts.unused does not count them
Scenario: Usage of an image lists articles and entries
Given the image 7 is used by article 12 "Heat pumps" (cover) and by entries 41, 42 and 43 of "event" and entry 9 of "workshop"
When the client sends GET /v1/media/7/usage
Then the response status is 200 and the body is a JSON array
And the article item is {"type":"article","id":12,"title":"Heat pumps","published":true,"fields":["cover"]}
And the entry items follow in the order event 41, 42, 43, then workshop 9 (content type name, then id), each with exactly type, id, fields ["thumbnail"], content_type_key, content_type_name and first_field, and no title and no published
And a client counts the array for the total
Scenario Outline: The raw first field in usage
Given an entry whose first field "<key>" is of type <type> and holds <stored>
When the client reads the usage of an image the entry uses
Then the entry item first_field is {"key":"<key>","type":"<type>","value":<value>}
And no string is built by the server and the item has no "title" key
Examples:
| key | type | stored | value |
| title | text | "Lime plaster workshop" | "Lime plaster workshop" |
| body | richtext | "\n\nFirst line\n\nSecond" | "\n\nFirst line\n\nSecond" |
| seats | number | 18 | 18 |
| category | select | "Talk" | "Talk" |
| online | boolean | false | false |
| starts_on | date | "2026-11-21" | "2026-11-21" |
| title | text | null | null |
| title | text | the key absent | null |
| cover | media | 7 | 7 |
Scenario: Usage of an unused or unknown image
When the client sends GET /v1/media/8/usage with no use
Then the body is []
When the client sends GET /v1/media/999/usage
Then the response status is 404 with apperr.ImageNotFoundErrorMessage
When the client sends GET /v1/media/abc/usage
Then the response status is 400 with apperr.IdUint32ErrorMessage
Scenario: Deleting an image used by entries is allowed
Given the image 7 is used by 5 entries and 2 articles
When the client sends DELETE /v1/media/7
Then the response status is 204
And the 2 articles lose the image reference as today
And the 5 entries still hold data.thumbnail 7 and are not modified (updated_at and updated_by unchanged)
Scenario: Merging duplicates repoints entry media
Given the images 7 and 9 share the same sha256 and entries 41 and 42 point at 9
When the client sends POST /v1/media/merge with keep_id 7 and merge_ids [9]
Then the response status is 200
And entries 41 and 42 hold thumbnail 7, with created_by, updated_by and updated_at unchanged
And image 9 no longer exists
Scenario: A failure while repointing entries stops the merge
Given the entry repository fails on the second Update
When the client sends POST /v1/media/merge
Then the response status is 500, the entries already repointed are restored, and no image is removed
Scenario: The purge plan counts entries as uses
Given the duplicate group 7, 9 where only 9 is used (by 1 entry)
When the purge preview and the purge run
Then 9 is the kept image and 7 is the merged copy
Scenario: Use case level
Given fake contenttype, entry and image repositories
Then entry.Validate returns an error satisfying errors.Is(err, entry.ErrInvalidEntry) with Key "thumbnail" and Rule "required" or "type" for the shapes above
And CreateEntry and UpdateEntry return the same for a missing library image and perform no Create or Update
And UpdateContentType returns contenttype.ErrSchemaIncompatible for a new required media field and does not call Update
And contenttype.ValidateFields returns contenttype.ErrInvalidField for a media field with unique, default, min, max or options
+59
View File
@@ -0,0 +1,59 @@
# QA procedure: media field type (slice A, API only)
Package: `test` (black-box). No live server, no real SQLite file, no real SMTP, no SPA.
## Setup shared by every case
1. Call `validator.InitValidator()` once per test.
2. Reuse the fakes of the custom content type pair (`mockContentTypeRepo`, `mockEntryRepo`) and of the media tests (image, article, site, author, variant file, storage, recorder fakes). Name any new fake uniquely across the package, for example `mockMediaFieldImageRepo`. The image fake must expose `Get`, a `getCalls` counter and a `delete(id)` helper.
3. `mockEntryRepo` needs no new method (no repository method is added). Give it an `updateCalls` counter and a `failUpdateOn(n)` switch for the merge compensation case.
4. Build `NewHandler(...)` for the entry, content type and media handlers over use cases wired to the fakes (the entry use cases now take the image fake). Mount them on a fresh `chi.NewRouter()` mirroring api/router.go: `/v1/content-type` and `/v1/media`, with `jwtauth.Verifier`, `jwtauth.Authenticator` and a test `jwtauth.New("HS256", []byte("test-secret"), nil)`. Add `RequireOwnerOrAdmin` on the content type write routes. If `api.InitBackendRoutes` with a partial `*api.UseCases` works, prefer it.
5. Seed users: admin 2 and a plain verified user. Seed images 7 "lime-plaster.jpg" (1600x900, 240000 bytes) and 8 "bathroom-tiles.png" (800x600, 51200 bytes), with distinct paths. Seed the type "event" (title text required, thumbnail media optional) and a variant with thumbnail required.
6. Inject a fake clock so `updated_at` > `created_at`.
7. Decode entry and list bodies into `map[string]any`; compare numbers as `float64`.
## Schema
8. POST a media field with the allowed shape -> 201; the field has type "media", unique false, default/min/max null, options [].
9. Table of refused options (unique true, default 7, default "lime", min 1, max 5, options ["a"]) -> 422 `invalid_field`, repo empty. Assert separately that `default: null` is accepted.
10. Type change in both directions on a type with entries -> 422 `invalid_field`, schema byte-identical. On a type with no entries the existing free type change still applies.
11. Add a media field to a type with 12 entries: required -> 409 `schema_incompatible`, schema unchanged; optional -> 200, existing entries still readable and `media` is `{}`. Make an optional media field required: 409 while an entry holds null, 200 once none does. Making it required while an entry holds an id of a deleted image -> 200 (compatibility does not consult the library).
## Entry writes
12. POST with image 7 -> 201; `data.thumbnail` is 7 and `media.thumbnail` has exactly `id`, `filename`, `width`, `height`, `size`, `thumbnail_url`; the key set of the entry is the seven existing keys plus `media`.
13. POST with null and with the key absent on an optional field -> 201, `media` is `{}` (assert JSON `{}`, not null).
14. Refusal table (required: absent, null; any: 999, "7", 0, -1, 7.5, 4294967296, true, [7]): status 422, exact body `invalid_entry: thumbnail: <rule>`, `createCalls == 0`.
15. PUT replace 7 -> 8: 200, filename "bathroom-tiles.png". PUT to null on optional: 200, `media` is `{}`.
16. After `delete(7)` on the image fake: GET entry 5 -> `data.thumbnail` 7 and `media.thumbnail` equals `{"id":7,"missing":true}` (no other key). PUT with the same 7 on an optional field -> 200, still 7 and still missing. PUT 999 -> 422 type, PUT 8 or null -> 200.
17. Required field, image 7 deleted: PUT 7 -> 422 `required`, PUT null -> 422 `required`, entry unchanged; PUT 8 -> 200.
18. POST with a deleted id 7 -> 422 `type` (create is always a changed value).
19. Ordering: a body with two bad fields names one only: Validate rules first in field order, then the existence check.
## Reads
20. List: 3 entries (existing image, deleted image, null) -> each item has the seven keys plus `media`; values as in the feature; `total`, `page` and `size` unchanged; `items` is `[]` for an empty type.
21. A type without a media field: `media` is `{}` and `getCalls == 0` on the image fake. A list of 100 entries pointing at the same image calls `Get` at most once for that id.
## Media library counts
22. Seed: image 8 used by 3 entries (one through two media fields) and no other use; image 7 used by 2 articles and 5 entries. `GET /v1/media/` -> `used_in` 3 and 7; `GET /v1/media/8` -> 3; `?filter=unused` omits both; `counts.unused` excludes both; an image with no use is still counted unused.
23. Unchanged existing cases: article, author and site usage counts and the unused counts still pass with no entries in the fake.
## Usage endpoint
24. Image 7 with article 12 (cover), entries 41, 42, 43 of "event" and entry 9 of "workshop": status 200, a JSON array, article item unchanged (keys type, id, title, published, fields). Entry items have exactly the keys `type`, `id`, `fields`, `content_type_key`, `content_type_name`, `first_field`, and no `title` and no `published`. Order: article, then event 41, 42, 43, then workshop 9.
25. Raw first-field table (text, richtext with leading blank lines, number 18, select, boolean false, date, text null, key absent, media 7). Assert `first_field` is exactly `{key, type, value}` with the value byte-equal to the stored JSON (richtext unmodified, number as a JSON number, null as JSON `null`). Assert the entry item JSON has no `title` key.
26. Unused image -> `[]`; unknown -> 404 `image_not_found` text; `abc` -> 400 `apperr.IdUint32ErrorMessage`.
## Delete and merge
27. DELETE /v1/media/7 used by 5 entries and 2 articles -> 204; articles cleared as before; the fake entry repo records no Update; the 5 entries are byte-identical.
28. Merge keep 7, merge [9] with equal sha256 and two entries on 9 -> 200; the entries hold 7; `created_by`, `updated_by` and `updated_at` are unchanged; image 9 is gone. Entries pointing at other images are untouched.
29. Merge with `failUpdateOn(2)` -> 500, the first repointed entry is restored to 9, no image deleted, articles/sites/authors repointing rolled back as today.
30. Purge preview and run on a duplicate group where only the copy is used by an entry: the used copy is the kept one; the fingerprint changes accordingly.
## Use case level (no HTTP)
31. `contenttype.ValidateFields` -> `ErrInvalidField` for each refused option. `entry.Validate` rows -> `errors.Is(err, entry.ErrInvalidEntry)` with the right key and rule. `CreateEntry`/`UpdateEntry` with a missing library image -> same error and no write. `UpdateContentType` with a new required media field -> `ErrSchemaIncompatible`, no `Update`.
## Existing tests to amend
32. Amend the existing key-set assertions from seven to eight keys in the earlier custom content type and entry feature, spec and test files (decision: `media` is always present). The coder owns this.
## Manual verification (not exercised by the Go tests)
- Real SQLite, then MySQL/MariaDB and PostgreSQL via the driver tasks: create a type with a media field, upload an image, save an entry, delete the image, reload the entry and confirm the id stays and `media` is `{missing:true}`.
- Merge duplicates with entries on a copy against real storage and confirm the entries repoint and the file is removed.
- Time `GET /v1/media/` with 1,000 entries across a type with a media field (usage lookup loads the entries of such types).
- The SPA (builder, editor control, picker, list cell, library badge and detail panel) is slices B and C and is not checked here.
@@ -25,6 +25,7 @@ const (
TypeBoolean FieldType = "boolean"
TypeDate FieldType = "date"
TypeSelect FieldType = "select"
TypeMedia FieldType = "media"
)
const (
+30
View File
@@ -20,6 +20,36 @@ var kinds = map[FieldType]kind{
TypeBoolean: {accepts: isBoolean},
TypeDate: {accepts: isDate, measure: dateDays, bound: dateDays, unique: true},
TypeSelect: {accepts: isString, unique: true},
TypeMedia: {accepts: isMediaID},
}
func MediaID(value any) (uint32, bool) {
switch typed := value.(type) {
case uint32:
return typed, typed >= 1
case int:
return mediaIDFromInt(int64(typed))
case int64:
return mediaIDFromInt(typed)
case float64:
if typed != math.Trunc(typed) || typed < 1 || typed > math.MaxUint32 {
return 0, false
}
return uint32(typed), true
}
return 0, false
}
func mediaIDFromInt(number int64) (uint32, bool) {
if number < 1 || number > math.MaxUint32 {
return 0, false
}
return uint32(number), true
}
func isMediaID(value any) bool {
_, ok := MediaID(value)
return ok
}
func isString(value any) bool {
@@ -109,5 +109,18 @@ func (f Field) validDefault() bool {
if f.Default == nil {
return true
}
if f.Type == TypeMedia {
return false
}
return !f.Unique && f.Violation(f.Default) == ""
}
func MediaFields(fields []Field) []Field {
var media []Field
for _, field := range fields {
if field.Type == TypeMedia {
media = append(media, field)
}
}
return media
}
+10
View File
@@ -88,3 +88,13 @@ func UniqueValues(fields []contenttype.Field, data map[string]any) []UniqueValue
}
return values
}
func MediaIDs(fields []contenttype.Field, data map[string]any) map[string]uint32 {
ids := map[string]uint32{}
for _, field := range contenttype.MediaFields(fields) {
if id, ok := contenttype.MediaID(data[field.Key]); ok {
ids[field.Key] = id
}
}
return ids
}
+4
View File
@@ -59,6 +59,10 @@ func invalidField(key string, rule string) error {
return FieldError{Key: key, Rule: rule, Cause: ErrInvalidEntry}
}
func InvalidField(key string, rule string) error {
return invalidField(key, rule)
}
func UniqueViolation(key string) error {
return FieldError{Key: key, Rule: RuleUnique, Cause: ErrUniqueViolation}
}
@@ -3,12 +3,14 @@ package useCases
import (
"RenewCMS/internal/domain/contenttype"
"RenewCMS/internal/domain/entry"
"RenewCMS/internal/domain/image"
"time"
)
type CreateEntryUseCase struct {
contentTypes contenttype.Repository
entries entry.Repository
images image.Repository
now func() time.Time
}
@@ -18,8 +20,8 @@ type CreateEntryCommand struct {
UserID uint32
}
func NewCreateEntryUseCase(contentTypes contenttype.Repository, entries entry.Repository, now func() time.Time) *CreateEntryUseCase {
return &CreateEntryUseCase{contentTypes, entries, now}
func NewCreateEntryUseCase(contentTypes contenttype.Repository, entries entry.Repository, images image.Repository, now func() time.Time) *CreateEntryUseCase {
return &CreateEntryUseCase{contentTypes, entries, images, now}
}
func (u *CreateEntryUseCase) Create(command CreateEntryCommand) (TypedEntry, error) {
@@ -31,6 +33,9 @@ func (u *CreateEntryUseCase) Create(command CreateEntryCommand) (TypedEntry, err
if err := entry.Validate(owner.Fields, data); err != nil {
return TypedEntry{}, err
}
if err := ensureMediaExists(u.images, owner, data, nil); err != nil {
return TypedEntry{}, err
}
if err := ensureUnique(u.entries, owner, data, 0); err != nil {
return TypedEntry{}, err
}
@@ -46,5 +51,5 @@ func (u *CreateEntryUseCase) Create(command CreateEntryCommand) (TypedEntry, err
if err != nil {
return TypedEntry{}, err
}
return typedEntry(owner, stored), nil
return typedEntry(owner, stored, newMediaResolver(u.images))
}
+5 -3
View File
@@ -3,15 +3,17 @@ package useCases
import (
"RenewCMS/internal/domain/contenttype"
"RenewCMS/internal/domain/entry"
"RenewCMS/internal/domain/image"
)
type GetEntryUseCase struct {
contentTypes contenttype.Repository
entries entry.Repository
images image.Repository
}
func NewGetEntryUseCase(contentTypes contenttype.Repository, entries entry.Repository) *GetEntryUseCase {
return &GetEntryUseCase{contentTypes, entries}
func NewGetEntryUseCase(contentTypes contenttype.Repository, entries entry.Repository, images image.Repository) *GetEntryUseCase {
return &GetEntryUseCase{contentTypes, entries, images}
}
func (u *GetEntryUseCase) Get(contentTypeKey string, id uint32) (TypedEntry, error) {
@@ -23,5 +25,5 @@ func (u *GetEntryUseCase) Get(contentTypeKey string, id uint32) (TypedEntry, err
if err != nil {
return TypedEntry{}, err
}
return typedEntry(owner, found), nil
return typedEntry(owner, found, newMediaResolver(u.images))
}
@@ -3,6 +3,8 @@ package useCases
import (
"RenewCMS/internal/domain/article"
"RenewCMS/internal/domain/author"
"RenewCMS/internal/domain/contenttype"
"RenewCMS/internal/domain/entry"
"RenewCMS/internal/domain/image"
"RenewCMS/internal/domain/site"
"slices"
@@ -13,6 +15,7 @@ const (
UsageTypeArticle = "article"
UsageTypeAuthor = "author"
UsageTypeSite = "site"
UsageTypeEntry = "entry"
UsageFieldBody = "body"
UsageFieldCover = "cover"
@@ -27,6 +30,16 @@ type MediaUsage struct {
Title string
Published *bool
Fields []string
ContentTypeKey string
ContentTypeName string
FirstField *UsageFirstField
}
type UsageFirstField struct {
Key string
Type contenttype.FieldType
Value any
}
type GetMediaUsageUseCase struct {
@@ -34,10 +47,11 @@ type GetMediaUsageUseCase struct {
articleRepository article.Repository
sites site.Repository
authors author.Repository
entries *entryMediaScanner
}
func NewGetMediaUsageUseCase(imageRepository image.Repository, articleRepository article.Repository, sites site.Repository, authors author.Repository) *GetMediaUsageUseCase {
return &GetMediaUsageUseCase{imageRepository: imageRepository, articleRepository: articleRepository, sites: sites, authors: authors}
func NewGetMediaUsageUseCase(imageRepository image.Repository, articleRepository article.Repository, sites site.Repository, authors author.Repository, contentTypes contenttype.Repository, entries entry.Repository) *GetMediaUsageUseCase {
return &GetMediaUsageUseCase{imageRepository: imageRepository, articleRepository: articleRepository, sites: sites, authors: authors, entries: newEntryMediaScanner(contentTypes, entries)}
}
func (u *GetMediaUsageUseCase) Usage(id uint32) ([]MediaUsage, error) {
@@ -57,7 +71,32 @@ func (u *GetMediaUsageUseCase) Usage(id uint32) ([]MediaUsage, error) {
if err != nil {
return nil, err
}
return slices.Concat(usages, authorUsages, siteUsages), nil
entryUsages, err := u.entryUsages(img)
if err != nil {
return nil, err
}
return slices.Concat(usages, authorUsages, siteUsages, entryUsages), nil
}
func (u *GetMediaUsageUseCase) entryUsages(img image.Image) ([]MediaUsage, error) {
referencing, err := u.entries.referencing(img.ID)
if err != nil {
return nil, err
}
targets := map[uint32]bool{img.ID: true}
usages := make([]MediaUsage, 0, len(referencing))
for _, found := range referencing {
first := found.owner.Fields[0]
usages = append(usages, MediaUsage{
Type: UsageTypeEntry,
ID: found.record.ID,
Fields: found.keysPointingAt(targets),
ContentTypeKey: found.owner.Key,
ContentTypeName: found.owner.Name,
FirstField: &UsageFirstField{Key: first.Key, Type: first.Type, Value: found.record.Data[first.Key]},
})
}
return usages, nil
}
func (u *GetMediaUsageUseCase) articleUsages(img image.Image) ([]MediaUsage, error) {
@@ -3,11 +3,13 @@ package useCases
import (
"RenewCMS/internal/domain/contenttype"
"RenewCMS/internal/domain/entry"
"RenewCMS/internal/domain/image"
)
type ListEntriesUseCase struct {
contentTypes contenttype.Repository
entries entry.Repository
images image.Repository
}
type ListEntriesCommand struct {
@@ -24,8 +26,8 @@ type EntryPage struct {
Size int
}
func NewListEntriesUseCase(contentTypes contenttype.Repository, entries entry.Repository) *ListEntriesUseCase {
return &ListEntriesUseCase{contentTypes, entries}
func NewListEntriesUseCase(contentTypes contenttype.Repository, entries entry.Repository, images image.Repository) *ListEntriesUseCase {
return &ListEntriesUseCase{contentTypes, entries, images}
}
func (u *ListEntriesUseCase) ListPage(command ListEntriesCommand) (EntryPage, error) {
@@ -44,8 +46,13 @@ func (u *ListEntriesUseCase) ListPage(command ListEntriesCommand) (EntryPage, er
return EntryPage{}, err
}
items := make([]TypedEntry, 0, len(found.Items))
resolver := newMediaResolver(u.images)
for _, record := range found.Items {
items = append(items, typedEntry(owner, record))
typed, err := typedEntry(owner, record, resolver)
if err != nil {
return EntryPage{}, err
}
items = append(items, typed)
}
return EntryPage{Items: items, Total: found.Total, Page: command.Page, Size: command.Size}, nil
}
@@ -3,6 +3,8 @@ package useCases
import (
"RenewCMS/internal/domain/article"
"RenewCMS/internal/domain/author"
"RenewCMS/internal/domain/contenttype"
"RenewCMS/internal/domain/entry"
"RenewCMS/internal/domain/image"
"RenewCMS/internal/domain/site"
"RenewCMS/internal/domain/user"
@@ -41,10 +43,11 @@ type ListMediaUseCase struct {
variantFiles image.VariantFileRepository
sites site.Repository
authors author.Repository
entries *entryMediaScanner
}
func NewListMediaUseCase(imageRepository image.Repository, articleRepository article.Repository, userRepository user.Repository, variantFiles image.VariantFileRepository, sites site.Repository, authors author.Repository) *ListMediaUseCase {
return &ListMediaUseCase{imageRepository: imageRepository, articleRepository: articleRepository, userRepository: userRepository, variantFiles: variantFiles, sites: sites, authors: authors}
func NewListMediaUseCase(imageRepository image.Repository, articleRepository article.Repository, userRepository user.Repository, variantFiles image.VariantFileRepository, sites site.Repository, authors author.Repository, contentTypes contenttype.Repository, entries entry.Repository) *ListMediaUseCase {
return &ListMediaUseCase{imageRepository: imageRepository, articleRepository: articleRepository, userRepository: userRepository, variantFiles: variantFiles, sites: sites, authors: authors, entries: newEntryMediaScanner(contentTypes, entries)}
}
func (l *ListMediaUseCase) List(query image.ListQuery) (MediaPage, error) {
@@ -118,7 +121,7 @@ func (l *ListMediaUseCase) Describe(img image.Image) (MediaItem, error) {
if err != nil {
return MediaItem{}, err
}
siteUsage, err := imageUsageCount(l.sites, l.authors)
siteUsage, err := imageUsageCount(l.sites, l.authors, l.entries)
if err != nil {
return MediaItem{}, err
}
@@ -169,7 +172,7 @@ func (l *ListMediaUseCase) usageCounter() (func(image.Image) int, error) {
if err != nil {
return nil, err
}
siteUsage, err := imageUsageCount(l.sites, l.authors)
siteUsage, err := imageUsageCount(l.sites, l.authors, l.entries)
if err != nil {
return nil, err
}
+13 -3
View File
@@ -4,6 +4,8 @@ import (
"RenewCMS/internal/domain/article"
"RenewCMS/internal/domain/audit"
"RenewCMS/internal/domain/author"
"RenewCMS/internal/domain/contenttype"
"RenewCMS/internal/domain/entry"
"RenewCMS/internal/domain/image"
"RenewCMS/internal/domain/site"
"cmp"
@@ -19,6 +21,7 @@ type MergeMediaResult struct {
Merged int
SitesUpdated int
AuthorsUpdated int
EntriesUpdated int
UpdatedArticleIDs []uint32
}
@@ -29,10 +32,11 @@ type MergeMediaUseCase struct {
recorder audit.Recorder
sites site.Repository
authors author.Repository
entries *entryMediaScanner
}
func NewMergeMediaUseCase(imageRepository image.Repository, articleRepository article.Repository, storage image.Storage, variantFiles image.VariantFileRepository, recorder audit.Recorder, sites site.Repository, authors author.Repository) *MergeMediaUseCase {
return &MergeMediaUseCase{imageRepository: imageRepository, articleRepository: articleRepository, remover: newMediaRemover(imageRepository, storage, variantFiles), recorder: recorder, sites: sites, authors: authors}
func NewMergeMediaUseCase(imageRepository image.Repository, articleRepository article.Repository, storage image.Storage, variantFiles image.VariantFileRepository, recorder audit.Recorder, sites site.Repository, authors author.Repository, contentTypes contenttype.Repository, entries entry.Repository) *MergeMediaUseCase {
return &MergeMediaUseCase{imageRepository: imageRepository, articleRepository: articleRepository, remover: newMediaRemover(imageRepository, storage, variantFiles), recorder: recorder, sites: sites, authors: authors, entries: newEntryMediaScanner(contentTypes, entries)}
}
func copyIdsOf(copies []image.Image) []uint32 {
@@ -118,6 +122,12 @@ func (u *MergeMediaUseCase) merge(keepId uint32, mergeIds []uint32) (MergeMediaR
return MergeMediaResult{}, err
}
repointedEntries, err := u.entries.repoint(copyIdsOf(copies), kept.ID)
if err != nil {
u.restoreBodies(rewrites)
return MergeMediaResult{}, err
}
for _, duplicate := range copies {
if err := u.remover.remove(duplicate); err != nil {
return MergeMediaResult{}, err
@@ -125,7 +135,7 @@ func (u *MergeMediaUseCase) merge(keepId uint32, mergeIds []uint32) (MergeMediaR
}
updatedIds := updatedArticleIds(rewrites, repointedArticles)
return MergeMediaResult{ArticlesUpdated: len(updatedIds), Merged: len(copies), SitesUpdated: sitesUpdated, AuthorsUpdated: authorsUpdated, UpdatedArticleIDs: updatedIds}, nil
return MergeMediaResult{ArticlesUpdated: len(updatedIds), Merged: len(copies), SitesUpdated: sitesUpdated, AuthorsUpdated: authorsUpdated, EntriesUpdated: len(repointedEntries), UpdatedArticleIDs: updatedIds}, nil
}
func updatedArticleIds(rewrites []bodyRewrite, repointed []uint32) []uint32 {
@@ -3,6 +3,8 @@ package useCases
import (
"RenewCMS/internal/domain/article"
"RenewCMS/internal/domain/author"
"RenewCMS/internal/domain/contenttype"
"RenewCMS/internal/domain/entry"
"RenewCMS/internal/domain/image"
"RenewCMS/internal/domain/site"
)
@@ -30,8 +32,8 @@ type PreviewPurgeUseCase struct {
planner *purgePlanner
}
func NewPreviewPurgeUseCase(imageRepository image.Repository, articleRepository article.Repository, sites site.Repository, authors author.Repository) *PreviewPurgeUseCase {
return &PreviewPurgeUseCase{&purgePlanner{imageRepository: imageRepository, articleRepository: articleRepository, sites: sites, authors: authors}}
func NewPreviewPurgeUseCase(imageRepository image.Repository, articleRepository article.Repository, sites site.Repository, authors author.Repository, contentTypes contenttype.Repository, entries entry.Repository) *PreviewPurgeUseCase {
return &PreviewPurgeUseCase{&purgePlanner{imageRepository: imageRepository, articleRepository: articleRepository, sites: sites, authors: authors, entries: newEntryMediaScanner(contentTypes, entries)}}
}
func (u *PreviewPurgeUseCase) Preview() (PurgePreview, error) {
+1 -1
View File
@@ -26,7 +26,7 @@ type RunPurgeUseCase struct {
func NewRunPurgeUseCase(imageRepository image.Repository, articleRepository article.Repository, merge *MergeMediaUseCase, repository purge.Repository, now func() time.Time, logger *log.Logger, recorder audit.Recorder, sites site.Repository, authors author.Repository) *RunPurgeUseCase {
return &RunPurgeUseCase{
planner: &purgePlanner{imageRepository: imageRepository, articleRepository: articleRepository, sites: sites, authors: authors},
planner: &purgePlanner{imageRepository: imageRepository, articleRepository: articleRepository, sites: sites, authors: authors, entries: merge.entries},
merge: merge,
repository: repository,
now: now,
@@ -3,12 +3,14 @@ package useCases
import (
"RenewCMS/internal/domain/contenttype"
"RenewCMS/internal/domain/entry"
"RenewCMS/internal/domain/image"
"time"
)
type UpdateEntryUseCase struct {
contentTypes contenttype.Repository
entries entry.Repository
images image.Repository
now func() time.Time
}
@@ -19,8 +21,8 @@ type UpdateEntryCommand struct {
UserID uint32
}
func NewUpdateEntryUseCase(contentTypes contenttype.Repository, entries entry.Repository, now func() time.Time) *UpdateEntryUseCase {
return &UpdateEntryUseCase{contentTypes, entries, now}
func NewUpdateEntryUseCase(contentTypes contenttype.Repository, entries entry.Repository, images image.Repository, now func() time.Time) *UpdateEntryUseCase {
return &UpdateEntryUseCase{contentTypes, entries, images, now}
}
func (u *UpdateEntryUseCase) Update(command UpdateEntryCommand) (TypedEntry, error) {
@@ -35,6 +37,9 @@ func (u *UpdateEntryUseCase) Update(command UpdateEntryCommand) (TypedEntry, err
if err := entry.Validate(owner.Fields, command.Data); err != nil {
return TypedEntry{}, err
}
if err := ensureMediaExists(u.images, owner, command.Data, current.Data); err != nil {
return TypedEntry{}, err
}
if err := ensureUnique(u.entries, owner, command.Data, current.ID); err != nil {
return TypedEntry{}, err
}
@@ -45,5 +50,5 @@ func (u *UpdateEntryUseCase) Update(command UpdateEntryCommand) (TypedEntry, err
if err != nil {
return TypedEntry{}, err
}
return typedEntry(owner, stored), nil
return typedEntry(owner, stored, newMediaResolver(u.images))
}
@@ -0,0 +1,190 @@
package useCases
import (
"RenewCMS/internal/domain/contenttype"
"RenewCMS/internal/domain/entry"
"RenewCMS/internal/domain/image"
"cmp"
"errors"
"slices"
)
type EntryMedia struct {
ID uint32
Missing bool
Filename string
Width *int
Height *int
Size int64
ThumbnailURL string
}
type mediaResolver struct {
images image.Repository
cache map[uint32]EntryMedia
}
func newMediaResolver(images image.Repository) *mediaResolver {
return &mediaResolver{images: images, cache: map[uint32]EntryMedia{}}
}
func (r *mediaResolver) resolve(owner contenttype.ContentType, record entry.Entry) (map[string]EntryMedia, error) {
resolved := map[string]EntryMedia{}
for _, field := range contenttype.MediaFields(owner.Fields) {
id, set := contenttype.MediaID(record.Data[field.Key])
if !set {
continue
}
media, err := r.lookup(id)
if err != nil {
return nil, err
}
resolved[field.Key] = media
}
return resolved, nil
}
func (r *mediaResolver) lookup(id uint32) (EntryMedia, error) {
if cached, found := r.cache[id]; found {
return cached, nil
}
found, err := r.images.Get(id)
if errors.Is(err, image.ErrImageNotFound) {
r.cache[id] = EntryMedia{ID: id, Missing: true}
return r.cache[id], nil
}
if err != nil {
return EntryMedia{}, err
}
media := EntryMedia{ID: found.ID, Filename: found.Filename, Width: knownDimension(found.Width), Height: knownDimension(found.Height), Size: found.Size, ThumbnailURL: found.Path}
r.cache[id] = media
return media, nil
}
func knownDimension(value int) *int {
if value <= 0 {
return nil
}
return &value
}
type mediaEntry struct {
owner contenttype.ContentType
record entry.Entry
}
type entryMediaScanner struct {
contentTypes contenttype.Repository
entries entry.Repository
}
func newEntryMediaScanner(contentTypes contenttype.Repository, entries entry.Repository) *entryMediaScanner {
return &entryMediaScanner{contentTypes: contentTypes, entries: entries}
}
func (s *entryMediaScanner) scan() ([]mediaEntry, error) {
types, err := s.contentTypes.List()
if err != nil {
return nil, err
}
var found []mediaEntry
for _, owner := range types {
if len(contenttype.MediaFields(owner.Fields)) == 0 {
continue
}
page, err := s.entries.ListPage(entry.Filters{ContentTypeID: owner.ID, Unpaged: true, Sort: entry.DefaultSort()})
if err != nil {
return nil, err
}
for _, record := range page.Items {
found = append(found, mediaEntry{owner: owner, record: record})
}
}
slices.SortFunc(found, func(a, b mediaEntry) int {
return cmp.Or(cmp.Compare(a.owner.Name, b.owner.Name), cmp.Compare(a.owner.ID, b.owner.ID), cmp.Compare(a.record.ID, b.record.ID))
})
return found, nil
}
func (m mediaEntry) keysPointingAt(ids map[uint32]bool) []string {
keys := []string{}
for _, field := range contenttype.MediaFields(m.owner.Fields) {
if id, set := contenttype.MediaID(m.record.Data[field.Key]); set && ids[id] {
keys = append(keys, field.Key)
}
}
return keys
}
func (s *entryMediaScanner) usageCounts() (map[uint32]int, error) {
found, err := s.scan()
if err != nil {
return nil, err
}
counts := map[uint32]int{}
for _, candidate := range found {
distinct := map[uint32]bool{}
for _, id := range entry.MediaIDs(candidate.owner.Fields, candidate.record.Data) {
distinct[id] = true
}
for id := range distinct {
counts[id]++
}
}
return counts, nil
}
func (s *entryMediaScanner) referencing(imageID uint32) ([]mediaEntry, error) {
found, err := s.scan()
if err != nil {
return nil, err
}
targets := map[uint32]bool{imageID: true}
return slices.DeleteFunc(found, func(candidate mediaEntry) bool {
return len(candidate.keysPointingAt(targets)) == 0
}), nil
}
type entryRepoint struct {
original entry.Entry
updated entry.Entry
}
func (s *entryMediaScanner) repoint(copyIDs []uint32, keptID uint32) ([]entryRepoint, error) {
found, err := s.scan()
if err != nil {
return nil, err
}
copies := map[uint32]bool{}
for _, id := range copyIDs {
copies[id] = true
}
applied := []entryRepoint{}
for _, candidate := range found {
keys := candidate.keysPointingAt(copies)
if len(keys) == 0 {
continue
}
change := entryRepoint{original: candidate.record, updated: candidate.record}
change.updated.Data = make(map[string]any, len(candidate.record.Data))
for key, value := range candidate.record.Data {
change.updated.Data[key] = value
}
for _, key := range keys {
change.updated.Data[key] = float64(keptID)
}
if _, err := s.entries.Update(change.updated); err != nil {
s.restore(applied)
return nil, err
}
applied = append(applied, change)
}
return applied, nil
}
func (s *entryMediaScanner) restore(applied []entryRepoint) {
for _, change := range applied {
_, err := s.entries.Update(change.original)
logCompensation("restore entry media", err)
}
}
@@ -3,16 +3,57 @@ package useCases
import (
"RenewCMS/internal/domain/contenttype"
"RenewCMS/internal/domain/entry"
"RenewCMS/internal/domain/image"
"errors"
)
type TypedEntry struct {
entry.Entry
ContentTypeKey string
Media map[string]EntryMedia
}
func typedEntry(owner contenttype.ContentType, record entry.Entry) TypedEntry {
func typedEntry(owner contenttype.ContentType, record entry.Entry, resolver *mediaResolver) (TypedEntry, error) {
record.Data = entry.Project(owner.Fields, record.Data)
return TypedEntry{Entry: record, ContentTypeKey: owner.Key}
media, err := resolver.resolve(owner, record)
if err != nil {
return TypedEntry{}, err
}
return TypedEntry{Entry: record, ContentTypeKey: owner.Key, Media: media}, nil
}
func ensureMediaExists(images image.Repository, owner contenttype.ContentType, data map[string]any, stored map[string]any) error {
storedIDs := entry.MediaIDs(owner.Fields, stored)
for _, field := range contenttype.MediaFields(owner.Fields) {
id, set := contenttype.MediaID(data[field.Key])
if !set {
continue
}
unchanged := stored != nil && storedIDs[field.Key] == id
if unchanged && !field.Required {
continue
}
exists, err := imageExists(images, id)
if err != nil {
return err
}
if exists {
continue
}
if unchanged {
return entry.InvalidField(field.Key, entry.RuleRequired)
}
return entry.InvalidField(field.Key, contenttype.RuleType)
}
return nil
}
func imageExists(images image.Repository, id uint32) (bool, error) {
_, err := images.Get(id)
if errors.Is(err, image.ErrImageNotFound) {
return false, nil
}
return err == nil, err
}
func ensureUnique(entries entry.Repository, owner contenttype.ContentType, data map[string]any, excludeID uint32) error {
@@ -30,6 +30,7 @@ type purgePlanner struct {
articleRepository article.Repository
sites site.Repository
authors author.Repository
entries *entryMediaScanner
}
func (p *purgePlanner) plan() (purgePlan, error) {
@@ -42,7 +43,7 @@ func (p *purgePlanner) plan() (purgePlan, error) {
return purgePlan{}, err
}
siteUsage, err := imageUsageCount(p.sites, p.authors)
siteUsage, err := imageUsageCount(p.sites, p.authors, p.entries)
if err != nil {
return purgePlan{}, err
}
@@ -19,7 +19,7 @@ func siteImageUsage(sites site.Repository) (map[uint32]int, error) {
return usage, nil
}
func imageUsageCount(sites site.Repository, authors author.Repository) (map[uint32]int, error) {
func imageUsageCount(sites site.Repository, authors author.Repository, entries *entryMediaScanner) (map[uint32]int, error) {
usage, err := siteImageUsage(sites)
if err != nil {
return nil, err
@@ -31,5 +31,12 @@ func imageUsageCount(sites site.Repository, authors author.Repository) (map[uint
for imageID, total := range avatars {
usage[imageID] += total
}
entryCounts, err := entries.usageCounts()
if err != nil {
return nil, err
}
for imageID, total := range entryCounts {
usage[imageID] += total
}
return usage, nil
}
+1 -1
View File
@@ -383,7 +383,7 @@ func TestActivityLogProducersScheduledPurge(t *testing.T) {
images := &producerBlockingImageRepo{mockImageRepo: newMockImageRepo(), entered: make(chan struct{}, 2), release: make(chan struct{})}
articles := newMockArticleRepo()
storage := newMockImageStorage()
merge := useCases.NewMergeMediaUseCase(images, articles, storage, newMockVariantFileRepo(), h.recorder, plainSites(), plainAuthors())
merge := useCases.NewMergeMediaUseCase(images, articles, storage, newMockVariantFileRepo(), h.recorder, plainSites(), plainAuthors(), newMockContentTypeRepo(), newMockEntryRepo())
run := useCases.NewRunPurgeUseCase(images, articles, merge, newMockPurgeSettingsRepo(), func() time.Time { return now }, log.New(io.Discard, "", 0), h.recorder, plainSites(), plainAuthors())
finished := make(chan struct{})
+3 -3
View File
@@ -100,7 +100,7 @@ func newAPIKeyEnvRecording(t *testing.T, recorder audit.Recorder) *apiKeyEnv {
mail := newMockMailRepo()
env.mail = mail
renderer := &fakeBodyRenderer{}
mergeMedia := useCases.NewMergeMediaUseCase(env.images, env.articles, newMockImageStorage(), newMockVariantFileRepo(), recorder, plainSites(), plainAuthors())
mergeMedia := useCases.NewMergeMediaUseCase(env.images, env.articles, newMockImageStorage(), newMockVariantFileRepo(), recorder, plainSites(), plainAuthors(), newMockContentTypeRepo(), newMockEntryRepo())
purgeSettings := newMockPurgeSettingsRepo()
restartJobs := &fakeJobStore{}
env.container = &api.UseCases{
@@ -127,13 +127,13 @@ func newAPIKeyEnvRecording(t *testing.T, recorder audit.Recorder) *apiKeyEnv {
AcceptInviteUseCase: useCases.NewAcceptInviteUseCase(env.users, env.invites, hasher, recorder),
CreateImageUseCase: useCases.NewCreateImageUseCase(env.images, newMockImageStorage(), recorder),
GenerateVariantsOnUploadUseCase: newInertGenerateOnUploadUseCase(),
ListMediaUseCase: useCases.NewListMediaUseCase(env.images, env.articles, env.users, newMockVariantFileRepo(), plainSites(), plainAuthors()),
ListMediaUseCase: useCases.NewListMediaUseCase(env.images, env.articles, env.users, newMockVariantFileRepo(), plainSites(), plainAuthors(), newMockContentTypeRepo(), newMockEntryRepo()),
RenameMediaUseCase: useCases.NewRenameMediaUseCase(env.images, recorder),
DeleteMediaUseCase: useCases.NewDeleteMediaUseCase(env.images, newMockImageStorage(), newMockVariantFileRepo(), recorder, plainSites(), plainAuthors(), env.articles),
MergeMediaUseCase: mergeMedia,
RunPurgeUseCase: useCases.NewRunPurgeUseCase(env.images, env.articles, mergeMedia, purgeSettings, clock, log.New(io.Discard, "", 0), recorder, plainSites(), plainAuthors()),
RequestRestartUseCase: useCases.NewRequestRestartUseCase(env.updates, restartJobs, &fakeHelperDetector{installed: true}, &fakeResultStore{}, &fakeRestartRequestStore{}, apiKeyRunningVersion, clock, recorder),
GetMediaUsageUseCase: useCases.NewGetMediaUsageUseCase(env.images, env.articles, plainSites(), plainAuthors()),
GetMediaUsageUseCase: useCases.NewGetMediaUsageUseCase(env.images, env.articles, plainSites(), plainAuthors(), newMockContentTypeRepo(), newMockEntryRepo()),
GetSettingsUseCase: useCases.NewGetSettingsUseCase(apiKeyRunningVersion),
GetActivityRetentionUseCase: useCases.NewGetActivityRetentionUseCase(newActivitySettingsFake(), newSizeEvents(t), time.Now),
GetUpdateStatusUseCase: newUpdateStatusUseCase(env.updates, &fakeJobStore{}, &fakeHelperDetector{}, apiKeyRunningVersion),
+3 -3
View File
@@ -355,14 +355,14 @@ func newAuthorEnv(t *testing.T) *authorEnv {
sites := plainSites()
recorder := p.audit.recorder
renderer := &fakeBodyRenderer{}
mergeMedia := useCases.NewMergeMediaUseCase(p.images, p.articles, newMockImageStorage(), newMockVariantFileRepo(), recorder, sites, authors)
mergeMedia := useCases.NewMergeMediaUseCase(p.images, p.articles, newMockImageStorage(), newMockVariantFileRepo(), recorder, sites, authors, newMockContentTypeRepo(), newMockEntryRepo())
c := p.container
c.CreateArticleUseCase = useCases.NewCreateArticleUseCase(p.articles, renderer, recorder, sites, authors)
c.UpdateArticleUseCase = useCases.NewUpdateArticleUseCase(p.articles, renderer, recorder, sites, authors, p.images)
c.ListMediaUseCase = useCases.NewListMediaUseCase(p.images, p.articles, p.users, newMockVariantFileRepo(), sites, authors)
c.ListMediaUseCase = useCases.NewListMediaUseCase(p.images, p.articles, p.users, newMockVariantFileRepo(), sites, authors, newMockContentTypeRepo(), newMockEntryRepo())
c.DeleteMediaUseCase = useCases.NewDeleteMediaUseCase(p.images, newMockImageStorage(), newMockVariantFileRepo(), recorder, sites, authors, p.articles)
c.MergeMediaUseCase = mergeMedia
c.GetMediaUsageUseCase = useCases.NewGetMediaUsageUseCase(p.images, p.articles, sites, authors)
c.GetMediaUsageUseCase = useCases.NewGetMediaUsageUseCase(p.images, p.articles, sites, authors, newMockContentTypeRepo(), newMockEntryRepo())
c.RunPurgeUseCase = useCases.NewRunPurgeUseCase(p.images, p.articles, mergeMedia, newMockPurgeSettingsRepo(), func() time.Time { return p.now }, log.New(io.Discard, "", 0), recorder, sites, authors)
c.ListActivityUseCase = useCases.NewListActivityUseCase(p.audit.store, p.users, p.articles, p.images, p.keys, p.audit.clock, sites, authors)
c.ListAuthorsUseCase = useCases.NewListAuthorsUseCase(authors, p.users)
@@ -424,7 +424,7 @@ func TestBuiltinTypeHTTP(t *testing.T) {
ListBuiltinTypesUseCase: useCases.NewListBuiltinTypesUseCase(),
GetBuiltinTypeUseCase: useCases.NewGetBuiltinTypeUseCase(),
CreateContentTypeUseCase: useCases.NewCreateContentTypeUseCase(panickingContentTypeRepo{}, now),
CreateEntryUseCase: useCases.NewCreateEntryUseCase(panickingContentTypeRepo{}, panickingEntryRepo{}, now),
CreateEntryUseCase: useCases.NewCreateEntryUseCase(panickingContentTypeRepo{}, panickingEntryRepo{}, newMockImageRepo(), now),
}
router := chi.NewRouter()
router.Mount("/v1", api.InitBackendRoutes(container, config.Settings{}))
+15 -7
View File
@@ -213,6 +213,8 @@ func (m *mockEntryRepo) FindByFieldValue(contentTypeID uint32, fieldKey string,
type contentTypeEnv struct {
types *mockContentTypeRepo
entries *mockEntryRepo
images *mockImageRepo
container *api.UseCases
users *mockUserRepo
keys *mockAPIKeyRepo
generator *hashing.SHA256KeyGenerator
@@ -228,6 +230,7 @@ func newContentTypeEnv(t *testing.T) *contentTypeEnv {
env := &contentTypeEnv{
types: newMockContentTypeRepo(),
entries: entries,
images: newMockImageRepo(),
users: newMockUserRepo(),
keys: newMockAPIKeyRepo(),
generator: hashing.NewSHA256KeyGenerator(),
@@ -253,18 +256,23 @@ func newContentTypeEnv(t *testing.T) *contentTypeEnv {
ListBuiltinTypesUseCase: useCases.NewListBuiltinTypesUseCase(),
GetBuiltinTypeUseCase: useCases.NewGetBuiltinTypeUseCase(),
LookupUserNamesUseCase: useCases.NewLookupUserNamesUseCase(env.users),
CreateEntryUseCase: useCases.NewCreateEntryUseCase(env.types, env.entries, now),
GetEntryUseCase: useCases.NewGetEntryUseCase(env.types, env.entries),
ListEntriesUseCase: useCases.NewListEntriesUseCase(env.types, env.entries),
UpdateEntryUseCase: useCases.NewUpdateEntryUseCase(env.types, env.entries, now),
CreateEntryUseCase: useCases.NewCreateEntryUseCase(env.types, env.entries, env.images, now),
GetEntryUseCase: useCases.NewGetEntryUseCase(env.types, env.entries, env.images),
ListEntriesUseCase: useCases.NewListEntriesUseCase(env.types, env.entries, env.images),
UpdateEntryUseCase: useCases.NewUpdateEntryUseCase(env.types, env.entries, env.images, now),
DeleteEntryUseCase: useCases.NewDeleteEntryUseCase(env.types, env.entries),
}
router := chi.NewRouter()
router.Mount("/v1", api.InitBackendRoutes(container, config.Settings{}))
env.router = router
env.container = container
env.mountRouter()
return env
}
func (e *contentTypeEnv) mountRouter() {
router := chi.NewRouter()
router.Mount("/v1", api.InitBackendRoutes(e.container, config.Settings{}))
e.router = router
}
func (e *contentTypeEnv) request(t *testing.T, method string, path string, body string, mutate func(*http.Request)) *httptest.ResponseRecorder {
t.Helper()
req := httptest.NewRequest(method, path, strings.NewReader(body))
+1 -1
View File
@@ -13,7 +13,7 @@ import (
var (
contentTypeKeys = []string{"created_at", "fields", "icon", "id", "key", "name", "updated_at"}
fieldKeys = []string{"default", "key", "label", "max", "min", "options", "required", "type", "unique"}
entryKeys = []string{"content_type", "created_at", "created_by", "data", "id", "updated_at", "updated_by"}
entryKeys = []string{"content_type", "created_at", "created_by", "data", "id", "media", "updated_at", "updated_by"}
)
func TestCreatingAContentType(t *testing.T) {
+4 -4
View File
@@ -64,7 +64,7 @@ func TestCreateEntryUseCase(t *testing.T) {
}
for _, data := range breaking {
fixture, _ := newContentTypeFixture(t)
create := useCases.NewCreateEntryUseCase(fixture.types, fixture.entries, fixture.now)
create := useCases.NewCreateEntryUseCase(fixture.types, fixture.entries, newMockImageRepo(), fixture.now)
_, err := create.Create(useCases.CreateEntryCommand{ContentTypeKey: "recipe", Data: data, UserID: 2})
@@ -76,7 +76,7 @@ func TestCreateEntryUseCase(t *testing.T) {
t.Run("Use case: a duplicate unique value returns ErrUniqueViolation", func(t *testing.T) {
fixture, _ := newContentTypeFixture(t)
create := useCases.NewCreateEntryUseCase(fixture.types, fixture.entries, fixture.now)
create := useCases.NewCreateEntryUseCase(fixture.types, fixture.entries, newMockImageRepo(), fixture.now)
data := func() map[string]any { return map[string]any{"title": "Pad thai", "difficulty": "easy"} }
if _, err := create.Create(useCases.CreateEntryCommand{ContentTypeKey: "recipe", Data: data(), UserID: 2}); err != nil {
t.Fatalf("first create: %v", err)
@@ -91,7 +91,7 @@ func TestCreateEntryUseCase(t *testing.T) {
t.Run("Use case: the injected clock stamps the entry", func(t *testing.T) {
fixture, _ := newContentTypeFixture(t)
create := useCases.NewCreateEntryUseCase(fixture.types, fixture.entries, fixture.now)
create := useCases.NewCreateEntryUseCase(fixture.types, fixture.entries, newMockImageRepo(), fixture.now)
created, err := create.Create(useCases.CreateEntryCommand{ContentTypeKey: "recipe", Data: map[string]any{"title": "Pad thai", "difficulty": "easy"}, UserID: 2})
@@ -551,7 +551,7 @@ func TestEntrySortRules(t *testing.T) {
func TestEntryPagingAndEquality(t *testing.T) {
t.Run("Pages beyond the maximum are refused by the use case", func(t *testing.T) {
fixture, _ := newContentTypeFixture(t)
list := useCases.NewListEntriesUseCase(fixture.types, fixture.entries)
list := useCases.NewListEntriesUseCase(fixture.types, fixture.entries, newMockImageRepo())
cases := []struct {
page, size int
sort entry.Sort
+3 -3
View File
@@ -115,7 +115,7 @@ func (e *variantEnv) container(limits useCases.ServeVariantLimits) *api.UseCases
GetMyAuthorUseCase: useCases.NewGetMyAuthorUseCase(plainAuthors()),
OpenMediaUseCase: useCases.NewOpenMediaUseCase(e.storage),
DeleteMediaUseCase: useCases.NewDeleteMediaUseCase(e.images, e.storage, e.files, recorder, plainSites(), plainAuthors(), e.articles),
MergeMediaUseCase: useCases.NewMergeMediaUseCase(e.images, e.articles, e.storage, e.files, recorder, plainSites(), plainAuthors()),
MergeMediaUseCase: useCases.NewMergeMediaUseCase(e.images, e.articles, e.storage, e.files, recorder, plainSites(), plainAuthors(), newMockContentTypeRepo(), newMockEntryRepo()),
ListVariantsUseCase: useCases.NewListVariantsUseCase(e.variants, e.files),
CreateVariantUseCase: useCases.NewCreateVariantUseCase(e.variants, e.renderer, clock, recorder),
UpdateVariantUseCase: useCases.NewUpdateVariantUseCase(e.variants, e.files, e.storage, e.renderer, clock, recorder),
@@ -129,9 +129,9 @@ func (e *variantEnv) container(limits useCases.ServeVariantLimits) *api.UseCases
VariantUsageTracker: e.tracker,
CreateImageUseCase: useCases.NewCreateImageUseCase(e.images, e.storage, recorder),
ListMediaUseCase: useCases.NewListMediaUseCase(e.images, e.articles, e.users, e.files, plainSites(), plainAuthors()),
ListMediaUseCase: useCases.NewListMediaUseCase(e.images, e.articles, e.users, e.files, plainSites(), plainAuthors(), newMockContentTypeRepo(), newMockEntryRepo()),
RenameMediaUseCase: useCases.NewRenameMediaUseCase(e.images, recorder),
GetMediaUsageUseCase: useCases.NewGetMediaUsageUseCase(e.images, e.articles, plainSites(), plainAuthors()),
GetMediaUsageUseCase: useCases.NewGetMediaUsageUseCase(e.images, e.articles, plainSites(), plainAuthors(), newMockContentTypeRepo(), newMockEntryRepo()),
ListImageVariantsUseCase: useCases.NewListImageVariantsUseCase(e.images, e.variants, e.files, e.renderer),
GenerateImageVariantUseCase: useCases.NewGenerateImageVariantUseCase(e.images, e.variants, e.files, e.renderer, serve),
+1 -1
View File
@@ -25,7 +25,7 @@ func TestMediaMergeRewritesArticlesInIdOrder(t *testing.T) {
env.seedArticle(id, "Article", true, env.urlOf(3))
}
recorder := &mediaOrderRecordingArticleRepo{mockArticleRepo: env.articles}
uc := useCases.NewMergeMediaUseCase(env.images, recorder, env.storage, newMockVariantFileRepo(), discardRecorder, plainSites(), plainAuthors())
uc := useCases.NewMergeMediaUseCase(env.images, recorder, env.storage, newMockVariantFileRepo(), discardRecorder, plainSites(), plainAuthors(), newMockContentTypeRepo(), newMockEntryRepo())
if _, err := uc.Merge(testCtx, 2, []uint32{3}); err != nil {
t.Fatalf("unexpected error: %v", err)
+4 -4
View File
@@ -62,7 +62,7 @@ func newMediaEnv(t *testing.T) *mediaEnv {
env.users.users[mediaUnverifiedUserId] = user.User{ID: 3, Username: "pending", IsVerified: false}
env.users.users[mediaStaleUserId] = user.User{ID: 4, Username: "stale", IsVerified: true, TokenVersion: 1}
merge := useCases.NewMergeMediaUseCase(env.images, env.articles, env.storage, newMockVariantFileRepo(), discardRecorder, plainSites(), plainAuthors())
merge := useCases.NewMergeMediaUseCase(env.images, env.articles, env.storage, newMockVariantFileRepo(), discardRecorder, plainSites(), plainAuthors(), newMockContentTypeRepo(), newMockEntryRepo())
now := func() time.Time { return env.clock }
container := &api.UseCases{
Token: env.token,
@@ -75,14 +75,14 @@ func newMediaEnv(t *testing.T) *mediaEnv {
GetMyAuthorUseCase: useCases.NewGetMyAuthorUseCase(plainAuthors()),
CreateImageUseCase: useCases.NewCreateImageUseCase(env.images, env.storage, discardRecorder),
GenerateVariantsOnUploadUseCase: newInertGenerateOnUploadUseCase(),
ListMediaUseCase: useCases.NewListMediaUseCase(env.images, env.articles, env.users, env.variants, plainSites(), plainAuthors()),
ListMediaUseCase: useCases.NewListMediaUseCase(env.images, env.articles, env.users, env.variants, plainSites(), plainAuthors(), newMockContentTypeRepo(), newMockEntryRepo()),
RenameMediaUseCase: useCases.NewRenameMediaUseCase(env.images, discardRecorder),
DeleteMediaUseCase: useCases.NewDeleteMediaUseCase(env.images, env.storage, newMockVariantFileRepo(), discardRecorder, plainSites(), plainAuthors(), env.articles),
MergeMediaUseCase: merge,
GetMediaUsageUseCase: useCases.NewGetMediaUsageUseCase(env.images, env.articles, plainSites(), plainAuthors()),
GetMediaUsageUseCase: useCases.NewGetMediaUsageUseCase(env.images, env.articles, plainSites(), plainAuthors(), newMockContentTypeRepo(), newMockEntryRepo()),
GetPurgeSettingsUseCase: useCases.NewGetPurgeSettingsUseCase(env.purgeSettings),
UpdatePurgeSettingsUseCase: useCases.NewUpdatePurgeSettingsUseCase(env.purgeSettings, now),
PreviewPurgeUseCase: useCases.NewPreviewPurgeUseCase(env.images, env.articles, plainSites(), plainAuthors()),
PreviewPurgeUseCase: useCases.NewPreviewPurgeUseCase(env.images, env.articles, plainSites(), plainAuthors(), newMockContentTypeRepo(), newMockEntryRepo()),
RunPurgeUseCase: useCases.NewRunPurgeUseCase(env.images, env.articles, merge, env.purgeSettings, now, log.New(env.logs, "", 0), discardRecorder, plainSites(), plainAuthors()),
}
router := chi.NewRouter()
+632
View File
@@ -0,0 +1,632 @@
package test
import (
"RenewCMS/api/pkg/apperr"
"RenewCMS/internal/domain/entry"
"net/http"
"reflect"
"strconv"
"strings"
"testing"
)
func limeMedia() map[string]any {
return map[string]any{"id": float64(mfLimeID), "filename": "lime-plaster.jpg", "width": float64(1600), "height": float64(900), "size": float64(240000), "thumbnail_url": mfImagePath}
}
func missingMedia(id int) map[string]any {
return map[string]any{"id": float64(id), "missing": true}
}
func entryPath(id uint32) string {
return "/v1/content-type/event/entry/" + strconv.Itoa(int(id))
}
func (e *mediaFieldEnv) storedFieldsJSON(t *testing.T, key string) string {
t.Helper()
stored, err := e.types.GetByKey(key)
if err != nil {
t.Fatalf("stored type %s: %v", key, err)
}
return jsonOf(t, stored.Fields)
}
func TestMediaFieldTypeContentTypes(t *testing.T) {
t.Run("Creating a content type with a media field", func(t *testing.T) {
env := newMediaFieldEnv(t)
rec := env.admin(t, http.MethodPost, "/v1/content-type", typeBody("event", "Events", eventFields(false)))
if rec.Code != http.StatusCreated {
t.Fatalf("status %d %s", rec.Code, rec.Body.String())
}
fields := decodeContentObject(t, rec)["fields"].([]any)
thumbnail := fields[1].(map[string]any)
if thumbnail["type"] != "media" || thumbnail["unique"] != false || thumbnail["default"] != nil || thumbnail["min"] != nil || thumbnail["max"] != nil || !reflect.DeepEqual(thumbnail["options"], []any{}) {
t.Errorf("unexpected field %v", thumbnail)
}
})
t.Run("A media field refuses options it can't have", func(t *testing.T) {
options := map[string]map[string]any{"unique true": map[string]any{"unique": true}, "default 7": map[string]any{"default": 7}, "default lime": map[string]any{"default": "lime"}, "min 1": map[string]any{"min": 1}, "max 5": map[string]any{"max": 5}, "options a": map[string]any{"options": []string{"a"}}}
for name, override := range options {
t.Run(name, func(t *testing.T) {
env := newMediaFieldEnv(t)
field := mediaField("thumbnail", false)
for key, value := range override {
field[key] = value
}
rec := env.admin(t, http.MethodPost, "/v1/content-type", typeBody("event", "Events", []map[string]any{{"key": "title", "label": "Title", "type": "text", "required": true}, field}))
expectStatusAndBody(t, rec, http.StatusUnprocessableEntity, "invalid_field")
if env.types.createCalls != 0 {
t.Errorf("a content type was stored")
}
})
}
})
t.Run("The type of a saved media field never changes", func(t *testing.T) {
env := newMediaFieldEnv(t)
env.createEventType(t, false)
env.seedEntry(t, "event", map[string]any{"title": "A"})
before := env.storedFieldsJSON(t, "event")
toText := []map[string]any{{"key": "title", "label": "Title", "type": "text", "required": true}, {"key": "thumbnail", "label": "Thumbnail", "type": "text"}}
toMedia := []map[string]any{{"key": "title", "label": "Title", "type": "media"}, mediaField("thumbnail", false)}
for _, fields := range [][]map[string]any{toText, toMedia} {
rec := env.admin(t, http.MethodPut, "/v1/content-type/event", typeBody("event", "Events", fields))
expectStatusAndBody(t, rec, http.StatusUnprocessableEntity, "invalid_field")
if env.storedFieldsJSON(t, "event") != before {
t.Errorf("schema changed")
}
}
})
t.Run("Adding a media field to a type that has entries", func(t *testing.T) {
examples := []struct {
name string
required bool
status int
message string
updated bool
}{{"required", true, http.StatusConflict, "schema_incompatible", false}, {"optional", false, http.StatusOK, "", true}}
for _, example := range examples {
t.Run(example.name, func(t *testing.T) {
env := newMediaFieldEnv(t)
env.createType(t, "event", []map[string]any{{"key": "title", "label": "Title", "type": "text", "required": true}})
for range 12 {
env.seedEntry(t, "event", map[string]any{"title": "A"})
}
before := env.storedFieldsJSON(t, "event")
rec := env.admin(t, http.MethodPut, "/v1/content-type/event", typeBody("event", "Events", eventFields(example.required)))
if rec.Code != example.status || (example.message != "" && strings.TrimSpace(rec.Body.String()) != example.message) {
t.Errorf("status %d body %q", rec.Code, rec.Body.String())
}
if (env.storedFieldsJSON(t, "event") != before) != example.updated {
t.Errorf("stored schema updated mismatch")
}
})
}
})
t.Run("Making a media field required", func(t *testing.T) {
env := newMediaFieldEnv(t)
env.createEventType(t, false)
env.seedEntry(t, "event", map[string]any{"title": "A", "thumbnail": float64(mfLimeID)})
nullEntry := env.seedEntry(t, "event", map[string]any{"title": "B", "thumbnail": nil})
rec := env.admin(t, http.MethodPut, "/v1/content-type/event", typeBody("event", "Events", eventFields(true)))
expectStatusAndBody(t, rec, http.StatusConflict, "schema_incompatible")
env.admin(t, http.MethodDelete, entryPath(nullEntry.ID), "")
rec = env.admin(t, http.MethodPut, "/v1/content-type/event", typeBody("event", "Events", eventFields(true)))
expectStatusAndBody(t, rec, http.StatusOK, "")
})
t.Run("Making a media field required while a stored image is gone", func(t *testing.T) {
env := newMediaFieldEnv(t)
env.createEventType(t, false)
env.seedEntry(t, "event", map[string]any{"title": "A", "thumbnail": float64(999)})
rec := env.admin(t, http.MethodPut, "/v1/content-type/event", typeBody("event", "Events", eventFields(true)))
expectStatusAndBody(t, rec, http.StatusOK, "")
})
}
func TestMediaFieldTypeEntries(t *testing.T) {
t.Run("Creating an entry with an image", func(t *testing.T) {
env := newMediaFieldEnv(t)
env.createEventType(t, false)
rec := env.createEntry(t, "event", ctAdminId, `{"title":"Lime plaster workshop","thumbnail":7}`)
if rec.Code != http.StatusCreated {
t.Fatalf("status %d %s", rec.Code, rec.Body.String())
}
body := decodeContentObject(t, rec)
if body["data"].(map[string]any)["thumbnail"] != float64(mfLimeID) || !reflect.DeepEqual(body["media"], map[string]any{"thumbnail": limeMedia()}) {
t.Errorf("unexpected %v", body)
}
})
t.Run("An empty optional media field", func(t *testing.T) {
examples := map[string]string{`null`: `{"title":"A","thumbnail":null}`, `absent`: `{"title":"A"}`}
for name, data := range examples {
t.Run(name, func(t *testing.T) {
env := newMediaFieldEnv(t)
env.createEventType(t, false)
rec := env.createEntry(t, "event", ctAdminId, data)
body := decodeContentObject(t, rec)
stored, present := body["data"].(map[string]any)["thumbnail"]
if rec.Code != http.StatusCreated || !reflect.DeepEqual(body["media"], map[string]any{}) || (name == "null" && (!present || stored != nil)) || (name == "absent" && present) {
t.Errorf("status %d body %v", rec.Code, body)
}
})
}
})
t.Run("Entry values that break a media field are refused and store nothing", func(t *testing.T) {
examples := []struct {
required bool
data string
message string
}{
{true, `{"title":"A"}`, "invalid_entry: thumbnail: required"},
{true, `{"title":"A","thumbnail":null}`, "invalid_entry: thumbnail: required"},
{false, `{"title":"A","thumbnail":999}`, "invalid_entry: thumbnail: type"},
{false, `{"title":"A","thumbnail":"7"}`, "invalid_entry: thumbnail: type"},
{false, `{"title":"A","thumbnail":0}`, "invalid_entry: thumbnail: type"},
{false, `{"title":"A","thumbnail":-1}`, "invalid_entry: thumbnail: type"},
{false, `{"title":"A","thumbnail":7.5}`, "invalid_entry: thumbnail: type"},
{false, `{"title":"A","thumbnail":4294967296}`, "invalid_entry: thumbnail: type"},
{false, `{"title":"A","thumbnail":true}`, "invalid_entry: thumbnail: type"},
{false, `{"title":"A","thumbnail":[7]}`, "invalid_entry: thumbnail: type"},
}
for _, example := range examples {
t.Run(example.data, func(t *testing.T) {
env := newMediaFieldEnv(t)
env.createEventType(t, example.required)
rec := env.createEntry(t, "event", ctAdminId, example.data)
expectStatusAndBody(t, rec, http.StatusUnprocessableEntity, example.message)
if len(env.entries.entries) != 0 {
t.Errorf("an entry was stored")
}
})
}
})
t.Run("Replacing the image of an entry", func(t *testing.T) {
env := newMediaFieldEnv(t)
env.createEventType(t, false)
stored := env.seedEntry(t, "event", map[string]any{"title": "Lime plaster workshop", "thumbnail": float64(mfLimeID)})
rec := env.member(t, http.MethodPut, entryPath(stored.ID), `{"data":{"title":"Lime plaster workshop","thumbnail":8}}`)
body := decodeContentObject(t, rec)
thumbnail, _ := body["media"].(map[string]any)["thumbnail"].(map[string]any)
if rec.Code != http.StatusOK || body["data"].(map[string]any)["thumbnail"] != float64(mfBathroomID) || thumbnail["filename"] != "bathroom-tiles.png" {
t.Errorf("status %d body %v", rec.Code, body)
}
rec = env.member(t, http.MethodPut, entryPath(stored.ID), `{"data":{"title":"Lime plaster workshop","thumbnail":null}}`)
body = decodeContentObject(t, rec)
if rec.Code != http.StatusOK || body["data"].(map[string]any)["thumbnail"] != nil || !reflect.DeepEqual(body["media"], map[string]any{}) {
t.Errorf("status %d body %v", rec.Code, body)
}
})
t.Run("An image deleted after the entry was saved", func(t *testing.T) {
env := newMediaFieldEnv(t)
env.createEventType(t, false)
stored := env.seedEntry(t, "event", map[string]any{"title": "A", "thumbnail": float64(mfLimeID)})
deleted := env.member(t, http.MethodDelete, "/v1/media/7", "")
rec := env.member(t, http.MethodGet, entryPath(stored.ID), "")
body := decodeContentObject(t, rec)
if deleted.Code != http.StatusNoContent || body["data"].(map[string]any)["thumbnail"] != float64(mfLimeID) || !reflect.DeepEqual(body["media"], map[string]any{"thumbnail": missingMedia(mfLimeID)}) {
t.Errorf("delete %d body %v", deleted.Code, body)
}
})
t.Run("An unchanged id whose image is gone can still be saved when the field is optional", func(t *testing.T) {
env := newMediaFieldEnv(t)
env.createEventType(t, false)
stored := env.seedEntry(t, "event", map[string]any{"title": "A", "thumbnail": float64(mfLimeID)})
delete(env.images.images, mfLimeID)
rec := env.member(t, http.MethodPut, entryPath(stored.ID), `{"data":{"title":"New title","thumbnail":7}}`)
body := decodeContentObject(t, rec)
if rec.Code != http.StatusOK || body["data"].(map[string]any)["thumbnail"] != float64(mfLimeID) || !reflect.DeepEqual(body["media"], map[string]any{"thumbnail": missingMedia(mfLimeID)}) {
t.Errorf("status %d body %v", rec.Code, body)
}
})
t.Run("A changed value must exist even when the old one is gone", func(t *testing.T) {
examples := []struct {
value string
status int
message string
}{{"999", http.StatusUnprocessableEntity, "invalid_entry: thumbnail: type"}, {"8", http.StatusOK, ""}, {"null", http.StatusOK, ""}}
for _, example := range examples {
t.Run(example.value, func(t *testing.T) {
env := newMediaFieldEnv(t)
env.createEventType(t, false)
stored := env.seedEntry(t, "event", map[string]any{"title": "A", "thumbnail": float64(mfLimeID)})
delete(env.images.images, mfLimeID)
rec := env.member(t, http.MethodPut, entryPath(stored.ID), `{"data":{"title":"A","thumbnail":`+example.value+`}}`)
expectStatusAndBody(t, rec, example.status, example.message)
})
}
})
t.Run("A required media field with a missing image can't be saved as is", func(t *testing.T) {
examples := []struct {
value string
status int
message string
updated bool
}{{"7", http.StatusUnprocessableEntity, "invalid_entry: thumbnail: required", false}, {"null", http.StatusUnprocessableEntity, "invalid_entry: thumbnail: required", false}, {"8", http.StatusOK, "", true}}
for _, example := range examples {
t.Run(example.value, func(t *testing.T) {
env := newMediaFieldEnv(t)
env.createEventType(t, true)
stored := env.seedEntry(t, "event", map[string]any{"title": "A", "thumbnail": float64(mfLimeID)})
delete(env.images.images, mfLimeID)
rec := env.member(t, http.MethodPut, entryPath(stored.ID), `{"data":{"title":"A","thumbnail":`+example.value+`}}`)
expectStatusAndBody(t, rec, example.status, example.message)
if (env.entries.updateCalls == 1) != example.updated {
t.Errorf("updates %d", env.entries.updateCalls)
}
})
}
})
t.Run("A create always treats the value as changed", func(t *testing.T) {
env := newMediaFieldEnv(t)
env.createEventType(t, false)
delete(env.images.images, mfLimeID)
rec := env.createEntry(t, "event", ctAdminId, `{"title":"A","thumbnail":7}`)
expectStatusAndBody(t, rec, http.StatusUnprocessableEntity, "invalid_entry: thumbnail: type")
})
t.Run("Two broken fields name only one", func(t *testing.T) {
env := newMediaFieldEnv(t)
env.createType(t, "event", []map[string]any{{"key": "title", "label": "Title", "type": "text", "required": true}, mediaField("thumbnail", false)})
rec := env.createEntry(t, "event", ctAdminId, `{"thumbnail":999}`)
expectStatusAndBody(t, rec, http.StatusUnprocessableEntity, "invalid_entry: title: required")
})
t.Run("Entry list responses carry the media object per item", func(t *testing.T) {
env := newMediaFieldEnv(t)
env.createEventType(t, false)
env.seedEntry(t, "event", map[string]any{"title": "A", "thumbnail": float64(mfLimeID)})
env.seedEntry(t, "event", map[string]any{"title": "B", "thumbnail": float64(999)})
env.seedEntry(t, "event", map[string]any{"title": "C", "thumbnail": nil})
rec := env.member(t, http.MethodGet, "/v1/content-type/event/entry?sort=id:asc", "")
page := decodeContentObject(t, rec)
items := page["items"].([]any)
want := []any{map[string]any{"thumbnail": limeMedia()}, map[string]any{"thumbnail": missingMedia(999)}, map[string]any{}}
for position, item := range items {
if !reflect.DeepEqual(objectKeys(item.(map[string]any)), entryKeys) || !reflect.DeepEqual(item.(map[string]any)["media"], want[position]) {
t.Errorf("item %d: %v", position, item)
}
}
if len(items) != 3 || page["total"] != float64(3) || page["page"] != float64(1) || page["size"] != float64(25) {
t.Errorf("unexpected page %v", page)
}
})
t.Run("Types without a media field are not enriched", func(t *testing.T) {
env := newMediaFieldEnv(t)
env.createType(t, "recipe", recipeFields())
created := env.createEntry(t, "recipe", ctAdminId, `{"title":"Pad thai","difficulty":"easy"}`)
rec := env.member(t, http.MethodGet, "/v1/content-type/recipe/entry/"+strconv.Itoa(int(decodeContentObject(t, created)["id"].(float64))), "")
body := decodeContentObject(t, rec)
if rec.Code != http.StatusOK || !reflect.DeepEqual(objectKeys(body), entryKeys) || !reflect.DeepEqual(body["media"], map[string]any{}) || env.lookups.gets != 0 {
t.Errorf("status %d body %v lookups %d", rec.Code, body, env.lookups.gets)
}
})
t.Run("Each distinct image is looked up once per request", func(t *testing.T) {
env := newMediaFieldEnv(t)
env.createType(t, "gallery", []map[string]any{mediaField("cover", false), mediaField("banner", false)})
env.seedEntry(t, "gallery", map[string]any{"cover": float64(mfLimeID), "banner": float64(mfLimeID)})
env.seedEntry(t, "gallery", map[string]any{"cover": float64(mfLimeID), "banner": float64(mfBathroomID)})
rec := env.member(t, http.MethodGet, "/v1/content-type/gallery/entry", "")
if rec.Code != http.StatusOK || env.lookups.gets != 2 {
t.Errorf("status %d lookups %d", rec.Code, env.lookups.gets)
}
})
t.Run("A repository failure while resolving media is a 500", func(t *testing.T) {
env := newMediaFieldEnv(t)
env.createEventType(t, false)
stored := env.seedEntry(t, "event", map[string]any{"title": "A", "thumbnail": float64(mfLimeID)})
env.images.fail.failNext("Get")
rec := env.member(t, http.MethodGet, entryPath(stored.ID), "")
if rec.Code != http.StatusInternalServerError {
t.Errorf("status %d", rec.Code)
}
})
}
func TestMediaFieldTypeLibrary(t *testing.T) {
t.Run("Media list items count entries as uses", func(t *testing.T) {
env := newMediaFieldEnv(t)
env.createType(t, "event", []map[string]any{{"key": "title", "label": "Title", "type": "text"}, mediaField("thumbnail", false), mediaField("banner", false)})
env.seedArticleUsing(12, "Heat pumps", mfLimeID)
env.seedArticleUsing(13, "Insulation", mfLimeID)
for range 3 {
env.seedEntry(t, "event", map[string]any{"thumbnail": float64(mfBathroomID)})
}
env.entries.entries[1] = withData(env.entries.entries[1], map[string]any{"thumbnail": float64(mfBathroomID), "banner": float64(mfBathroomID)})
for range 5 {
env.seedEntry(t, "event", map[string]any{"thumbnail": float64(mfLimeID)})
}
list := decodeContentObject(t, env.member(t, http.MethodGet, "/v1/media/", ""))
one := decodeContentObject(t, env.member(t, http.MethodGet, "/v1/media/8", ""))
unused := decodeContentObject(t, env.member(t, http.MethodGet, "/v1/media/?filter=unused", ""))
usedIn := map[float64]float64{}
for _, item := range list["items"].([]any) {
usedIn[item.(map[string]any)["id"].(float64)] = item.(map[string]any)["used_in"].(float64)
}
if usedIn[mfBathroomID] != 3 || usedIn[mfLimeID] != 7 || one["used_in"] != float64(3) {
t.Errorf("used_in %v, one %v", usedIn, one["used_in"])
}
if len(unused["items"].([]any)) != 0 || unused["counts"].(map[string]any)["unused"] != float64(0) {
t.Errorf("unused %v", unused)
}
})
t.Run("Usage of an image lists articles and entries", func(t *testing.T) {
env := newMediaFieldEnv(t)
env.createType(t, "workshop", []map[string]any{{"key": "seats", "label": "Seats", "type": "number"}, mediaField("thumbnail", false)})
env.createEventType(t, false)
env.seedArticleUsing(12, "Heat pumps", mfLimeID)
workshop := env.seedEntry(t, "workshop", map[string]any{"seats": float64(18), "thumbnail": float64(mfLimeID)})
first := env.seedEntry(t, "event", map[string]any{"title": "Lime plaster workshop", "thumbnail": float64(mfLimeID)})
env.seedEntry(t, "event", map[string]any{"title": "Other", "thumbnail": float64(mfBathroomID)})
second := env.seedEntry(t, "event", map[string]any{"title": "Second", "thumbnail": float64(mfLimeID)})
third := env.seedEntry(t, "event", map[string]any{"title": "Third", "thumbnail": float64(mfLimeID)})
rec := env.member(t, http.MethodGet, "/v1/media/7/usage", "")
items := decodeContentArray(t, rec)
if rec.Code != http.StatusOK || len(items) != 5 {
t.Fatalf("status %d items %v", rec.Code, items)
}
wantArticle := map[string]any{"type": "article", "id": float64(12), "title": "Heat pumps", "published": true, "fields": []any{"cover"}}
if !reflect.DeepEqual(items[0], wantArticle) {
t.Errorf("article item %v", items[0])
}
wantWorkshop := map[string]any{"type": "entry", "id": float64(workshop.ID), "fields": []any{"thumbnail"}, "content_type_key": "workshop", "content_type_name": "Workshop", "first_field": map[string]any{"key": "seats", "type": "number", "value": float64(18)}}
if !reflect.DeepEqual(items[4], wantWorkshop) {
t.Errorf("workshop item %v", items[4])
}
for _, item := range items[1:4] {
if item["content_type_key"] != "event" || item["content_type_name"] != "Event" || item["title"] != nil || item["published"] != nil || item["type"] != "entry" {
t.Errorf("event item %v", item)
}
if len(item) != 6 {
t.Errorf("event item keys %v", item)
}
}
gotOrder := []float64{items[1]["id"].(float64), items[2]["id"].(float64), items[3]["id"].(float64), items[4]["id"].(float64)}
wantOrder := []float64{float64(first.ID), float64(second.ID), float64(third.ID), float64(workshop.ID)}
if !reflect.DeepEqual(gotOrder, wantOrder) {
t.Errorf("order after the article should be event %v then workshop: got %v", wantOrder[:3], gotOrder)
}
})
t.Run("The raw first field in usage", func(t *testing.T) {
examples := []struct {
name string
fieldType string
stored map[string]any
value any
}{
{"title", "text", map[string]any{"title": "Lime plaster workshop"}, "Lime plaster workshop"},
{"body", "richtext", map[string]any{"body": "\n\nFirst line\n\nSecond"}, "\n\nFirst line\n\nSecond"},
{"seats", "number", map[string]any{"seats": float64(18)}, float64(18)},
{"online", "boolean", map[string]any{"online": false}, false},
{"starts_on", "date", map[string]any{"starts_on": "2026-11-21"}, "2026-11-21"},
{"title", "text", map[string]any{"title": nil}, nil},
{"title", "text", map[string]any{}, nil},
}
for _, example := range examples {
t.Run(example.name+" "+example.fieldType, func(t *testing.T) {
env := newMediaFieldEnv(t)
env.createType(t, "event", []map[string]any{{"key": example.name, "label": "First", "type": example.fieldType}, mediaField("thumbnail", false)})
data := map[string]any{"thumbnail": float64(mfLimeID)}
for key, value := range example.stored {
data[key] = value
}
env.seedEntry(t, "event", data)
items := decodeContentArray(t, env.member(t, http.MethodGet, "/v1/media/7/usage", ""))
want := map[string]any{"key": example.name, "type": example.fieldType, "value": example.value}
if len(items) != 1 || !reflect.DeepEqual(items[0]["first_field"], want) || items[0]["title"] != nil {
t.Errorf("unexpected %v", items)
}
})
}
})
t.Run("The raw first field in usage for a media field", func(t *testing.T) {
env := newMediaFieldEnv(t)
env.createType(t, "event", []map[string]any{mediaField("cover", false)})
env.seedEntry(t, "event", map[string]any{"cover": float64(mfLimeID)})
items := decodeContentArray(t, env.member(t, http.MethodGet, "/v1/media/7/usage", ""))
want := map[string]any{"key": "cover", "type": "media", "value": float64(mfLimeID)}
if len(items) != 1 || !reflect.DeepEqual(items[0]["first_field"], want) || !reflect.DeepEqual(items[0]["fields"], []any{"cover"}) {
t.Errorf("unexpected %v", items)
}
})
t.Run("Usage of an unused or unknown image", func(t *testing.T) {
env := newMediaFieldEnv(t)
env.createEventType(t, false)
empty := env.member(t, http.MethodGet, "/v1/media/8/usage", "")
unknown := env.member(t, http.MethodGet, "/v1/media/999/usage", "")
malformed := env.member(t, http.MethodGet, "/v1/media/abc/usage", "")
expectStatusAndBody(t, empty, http.StatusOK, "[]")
expectStatusAndBody(t, unknown, http.StatusNotFound, apperr.ImageNotFoundErrorMessage)
expectStatusAndBody(t, malformed, http.StatusBadRequest, apperr.IdUint32ErrorMessage)
})
t.Run("Deleting an image used by entries is allowed", func(t *testing.T) {
env := newMediaFieldEnv(t)
env.createEventType(t, false)
env.seedArticleUsing(12, "Heat pumps", mfLimeID)
var before []entry.Entry
for range 5 {
before = append(before, env.seedEntry(t, "event", map[string]any{"title": "A", "thumbnail": float64(mfLimeID)}))
}
rec := env.member(t, http.MethodDelete, "/v1/media/7", "")
if rec.Code != http.StatusNoContent || env.entries.updateCalls != 0 {
t.Fatalf("status %d updates %d", rec.Code, env.entries.updateCalls)
}
for _, snapshot := range before {
if !reflect.DeepEqual(env.entries.entries[snapshot.ID], snapshot) {
t.Errorf("entry changed %v", env.entries.entries[snapshot.ID])
}
}
if _, gone := env.images.images[mfLimeID]; gone {
t.Errorf("image should be deleted")
}
})
t.Run("Merging duplicates repoints entry media", func(t *testing.T) {
env := newMergeEnv(t)
first := env.seedEntry(t, "event", map[string]any{"title": "A", "thumbnail": float64(mfCopyID)})
second := env.seedEntry(t, "event", map[string]any{"title": "B", "thumbnail": float64(mfCopyID)})
rec := env.member(t, http.MethodPost, "/v1/media/merge", `{"keep_id":7,"merge_ids":[9]}`)
if rec.Code != http.StatusOK {
t.Fatalf("status %d %s", rec.Code, rec.Body.String())
}
for _, original := range []entry.Entry{first, second} {
stored := env.entries.entries[original.ID]
if stored.Data["thumbnail"] != float64(mfLimeID) || stored.CreatedBy != original.CreatedBy || stored.UpdatedBy != original.UpdatedBy || !stored.UpdatedAt.Equal(original.UpdatedAt) {
t.Errorf("entry %d: %v", original.ID, stored)
}
}
if _, exists := env.images.images[mfCopyID]; exists {
t.Errorf("image 9 should be gone")
}
})
t.Run("A failure while repointing entries stops the merge", func(t *testing.T) {
env := newMergeEnv(t)
first := env.seedEntry(t, "event", map[string]any{"title": "A", "thumbnail": float64(mfCopyID)})
second := env.seedEntry(t, "event", map[string]any{"title": "B", "thumbnail": float64(mfCopyID)})
env.spy.failOnUpdate = 2
rec := env.member(t, http.MethodPost, "/v1/media/merge", `{"keep_id":7,"merge_ids":[9]}`)
if rec.Code != http.StatusInternalServerError {
t.Fatalf("status %d %s", rec.Code, rec.Body.String())
}
for _, original := range []entry.Entry{first, second} {
if !reflect.DeepEqual(env.entries.entries[original.ID], original) {
t.Errorf("entry %d not restored: %v", original.ID, env.entries.entries[original.ID])
}
}
if _, exists := env.images.images[mfCopyID]; !exists || len(env.images.deleteCalls) != 0 {
t.Errorf("no image should be removed")
}
})
t.Run("Entry uses decide which duplicate is kept", func(t *testing.T) {
env := newMergeEnv(t)
env.seedArticleUsing(12, "Heat pumps", mfLimeID)
baseline := decodeContentObject(t, env.admin(t, http.MethodGet, "/v1/media/purge-preview", ""))
baseList := baseline["list"].([]any)
if len(baseList) != 1 || baseList[0].(map[string]any)["keep_id"] != float64(mfLimeID) {
t.Fatalf("baseline %v", baseline)
}
env.seedEntry(t, "event", map[string]any{"title": "A", "thumbnail": float64(mfCopyID)})
tie := decodeContentObject(t, env.admin(t, http.MethodGet, "/v1/media/purge-preview", ""))
tieList := tie["list"].([]any)
if tieList[0].(map[string]any)["keep_id"] != float64(mfLimeID) || tieList[0].(map[string]any)["used_in"] != float64(1) || tie["fingerprint"] != baseline["fingerprint"] {
t.Errorf("one article against one entry is a tie, the older copy stays: %v", tie)
}
env.seedEntry(t, "event", map[string]any{"title": "B", "thumbnail": float64(mfCopyID)})
decided := decodeContentObject(t, env.admin(t, http.MethodGet, "/v1/media/purge-preview", ""))
decidedList := decided["list"].([]any)
if decidedList[0].(map[string]any)["keep_id"] != float64(mfCopyID) || decidedList[0].(map[string]any)["used_in"] != float64(2) || decided["fingerprint"] == baseline["fingerprint"] {
t.Errorf("two entries outweigh one article: %v", decided)
}
})
t.Run("The purge plan counts entries as uses", func(t *testing.T) {
env := newMergeEnv(t)
used := env.seedEntry(t, "event", map[string]any{"title": "A", "thumbnail": float64(mfCopyID)})
preview := decodeContentObject(t, env.admin(t, http.MethodGet, "/v1/media/purge-preview", ""))
run := env.admin(t, http.MethodPost, "/v1/media/purge", "")
list := preview["list"].([]any)
if len(list) != 1 || list[0].(map[string]any)["keep_id"] != float64(mfCopyID) || list[0].(map[string]any)["used_in"] != float64(1) {
t.Errorf("preview %v", preview)
}
if run.Code != http.StatusOK || env.entries.entries[used.ID].Data["thumbnail"] != float64(mfCopyID) {
t.Errorf("run %d %s, entry %v", run.Code, run.Body.String(), env.entries.entries[used.ID])
}
if _, exists := env.images.images[mfLimeID]; exists {
t.Errorf("image 7 should be merged away")
}
})
}
func newMergeEnv(t *testing.T) *mediaFieldEnv {
t.Helper()
env := newMediaFieldEnv(t)
env.createEventType(t, false)
env.seedImage(mfCopyID, "lime-plaster-copy.jpg", 1600, 900, 240000, "hash-lime")
return env
}
func withData(record entry.Entry, data map[string]any) entry.Entry {
record.Data = data
return record
}
+133
View File
@@ -0,0 +1,133 @@
package test
import (
"RenewCMS/internal/domain/article"
"RenewCMS/internal/domain/entry"
imageDomain "RenewCMS/internal/domain/image"
"RenewCMS/internal/infrastructure/useCases"
"bytes"
"encoding/json"
"errors"
"log"
"net/http/httptest"
"testing"
"time"
)
const (
mfLimeID = 7
mfBathroomID = 8
mfCopyID = 9
mfImagePath = "/v1/static/uploadedImages/lime-plaster.jpg"
)
var errMediaFieldEntryUpdate = errors.New("entry update failure")
type mfEntrySpyRepo struct {
*mockEntryRepo
failOnUpdate int
updates int
}
var _ entry.Repository = &mfEntrySpyRepo{}
func (s *mfEntrySpyRepo) Update(record entry.Entry) (entry.Entry, error) {
s.updates++
if s.failOnUpdate > 0 && s.updates == s.failOnUpdate {
return entry.Entry{}, errMediaFieldEntryUpdate
}
return s.mockEntryRepo.Update(record)
}
type mfImageSpyRepo struct {
*mockImageRepo
gets int
}
var _ imageDomain.Repository = &mfImageSpyRepo{}
func (s *mfImageSpyRepo) Get(id uint32) (imageDomain.Image, error) {
s.gets++
return s.mockImageRepo.Get(id)
}
type mediaFieldEnv struct {
*contentTypeEnv
articles *mockArticleRepo
spy *mfEntrySpyRepo
lookups *mfImageSpyRepo
logs *bytes.Buffer
}
func newMediaFieldEnv(t *testing.T) *mediaFieldEnv {
t.Helper()
base := newContentTypeEnv(t)
env := &mediaFieldEnv{contentTypeEnv: base, articles: newMockArticleRepo(), spy: &mfEntrySpyRepo{mockEntryRepo: base.entries}, lookups: &mfImageSpyRepo{mockImageRepo: base.images}, logs: &bytes.Buffer{}}
settings := newMockPurgeSettingsRepo()
now := func() time.Time { return base.clock }
merge := useCases.NewMergeMediaUseCase(base.images, env.articles, newMockImageStorage(), newMockVariantFileRepo(), discardRecorder, plainSites(), plainAuthors(), base.types, env.spy)
container := base.container
container.CreateEntryUseCase = useCases.NewCreateEntryUseCase(base.types, base.entries, env.lookups, now)
container.GetEntryUseCase = useCases.NewGetEntryUseCase(base.types, base.entries, env.lookups)
container.ListEntriesUseCase = useCases.NewListEntriesUseCase(base.types, base.entries, env.lookups)
container.UpdateEntryUseCase = useCases.NewUpdateEntryUseCase(base.types, base.entries, env.lookups, now)
container.ListMediaUseCase = useCases.NewListMediaUseCase(base.images, env.articles, base.users, newMockVariantFileRepo(), plainSites(), plainAuthors(), base.types, base.entries)
container.DeleteMediaUseCase = useCases.NewDeleteMediaUseCase(base.images, newMockImageStorage(), newMockVariantFileRepo(), discardRecorder, plainSites(), plainAuthors(), env.articles)
container.MergeMediaUseCase = merge
container.GetMediaUsageUseCase = useCases.NewGetMediaUsageUseCase(base.images, env.articles, plainSites(), plainAuthors(), base.types, base.entries)
container.PreviewPurgeUseCase = useCases.NewPreviewPurgeUseCase(base.images, env.articles, plainSites(), plainAuthors(), base.types, base.entries)
container.RunPurgeUseCase = useCases.NewRunPurgeUseCase(base.images, env.articles, merge, settings, now, log.New(env.logs, "", 0), discardRecorder, plainSites(), plainAuthors())
base.mountRouter()
env.seedImage(mfLimeID, "lime-plaster.jpg", 1600, 900, 240000, "hash-lime")
env.seedImage(mfBathroomID, "bathroom-tiles.png", 800, 600, 51200, "hash-bathroom")
return env
}
func (e *mediaFieldEnv) seedImage(id uint32, filename string, width int, height int, size int64, sha string) {
e.images.images[id] = imageDomain.Image{ID: id, Path: "/v1/static/uploadedImages/" + filename, Filename: filename, Size: size, ContentType: "image/jpeg", Width: width, Height: height, SHA256: sha, UploadedByID: ctAdminId, CreatedAt: e.clock.Add(time.Duration(id) * time.Minute)}
}
func mediaField(key string, required bool) map[string]any {
return map[string]any{"key": key, "label": "Thumbnail", "type": "media", "required": required, "unique": false, "default": nil, "min": nil, "max": nil, "options": []string{}}
}
func eventFields(required bool) []map[string]any {
return []map[string]any{{"key": "title", "label": "Title", "type": "text", "required": true}, mediaField("thumbnail", required)}
}
func (e *mediaFieldEnv) createEventType(t *testing.T, required bool) {
t.Helper()
e.createType(t, "event", eventFields(required))
}
func (e *mediaFieldEnv) seedEntry(t *testing.T, typeKey string, data map[string]any) entry.Entry {
t.Helper()
owner, err := e.types.GetByKey(typeKey)
if err != nil {
t.Fatalf("seed type %s: %v", typeKey, err)
}
stored, err := e.entries.Create(entry.Entry{ContentTypeID: owner.ID, Data: data, CreatedBy: ctMemberId, UpdatedBy: ctMemberId, CreatedAt: e.clock, UpdatedAt: e.clock})
if err != nil {
t.Fatalf("seed entry: %v", err)
}
return stored
}
func (e *mediaFieldEnv) member(t *testing.T, method string, path string, body string) *httptest.ResponseRecorder {
t.Helper()
return e.as(t, ctMemberId, method, path, body)
}
func (e *mediaFieldEnv) seedArticleUsing(id uint32, title string, imageID uint32) {
cover := imageID
e.articles.articles[id] = article.Article{ID: id, Title: title, IsOnline: true, CoverImageID: &cover}
}
func jsonOf(t *testing.T, value any) string {
t.Helper()
encoded, err := json.Marshal(value)
if err != nil {
t.Fatalf("encode: %v", err)
}
return string(encoded)
}
+229
View File
@@ -0,0 +1,229 @@
package test
import (
"RenewCMS/internal/domain/contenttype"
"RenewCMS/internal/domain/entry"
imageDomain "RenewCMS/internal/domain/image"
"RenewCMS/internal/infrastructure/useCases"
"errors"
"math"
"testing"
"time"
)
func mediaThumbnailSchema(t *testing.T, required bool) []contenttype.Field {
t.Helper()
fields, err := contenttype.ValidateFields([]contenttype.Field{
{Key: "title", Label: "Title", Type: contenttype.TypeText, Required: true},
{Key: "thumbnail", Label: "Thumbnail", Type: contenttype.TypeMedia, Required: required},
})
if err != nil {
t.Fatalf("schema: %v", err)
}
return fields
}
func expectFieldError(t *testing.T, err error, key string, rule string) {
t.Helper()
var fieldError entry.FieldError
if !errors.Is(err, entry.ErrInvalidEntry) || !errors.As(err, &fieldError) || fieldError.Key != key || fieldError.Rule != rule {
t.Errorf("want %s %s, got %v", key, rule, err)
}
}
func TestMediaFieldDomain(t *testing.T) {
t.Run("contenttype.ValidateFields refuses what a media field can't have", func(t *testing.T) {
refused := map[string]contenttype.Field{
"unique": {Unique: true},
"default int": {Default: float64(7)},
"default str": {Default: "lime"},
"min": {Min: float64(1)},
"max": {Max: float64(5)},
"options": {Options: []string{"a"}},
}
for name, base := range refused {
base.Key, base.Label, base.Type = "thumbnail", "Thumbnail", contenttype.TypeMedia
if _, err := contenttype.ValidateFields([]contenttype.Field{base}); !errors.Is(err, contenttype.ErrInvalidField) {
t.Errorf("%s: %v", name, err)
}
}
plain := contenttype.Field{Key: "thumbnail", Label: "Thumbnail", Type: contenttype.TypeMedia, Required: true}
if _, err := contenttype.ValidateFields([]contenttype.Field{plain}); err != nil {
t.Errorf("a plain media field should pass: %v", err)
}
})
t.Run("contenttype.MediaID accepts integers from 1 to the uint32 maximum only", func(t *testing.T) {
accepted := map[any]uint32{float64(1): 1, float64(7): 7, float64(math.MaxUint32): math.MaxUint32, 9: 9, int64(8): 8, uint32(3): 3}
for value, want := range accepted {
if got, ok := contenttype.MediaID(value); !ok || got != want {
t.Errorf("%v: %d %v", value, got, ok)
}
}
for _, value := range []any{float64(0), float64(-1), 7.5, float64(math.MaxUint32) + 1, "7", true, []any{7.0}, nil, 0, -3, uint32(0), math.NaN()} {
if _, ok := contenttype.MediaID(value); ok {
t.Errorf("%v should be refused", value)
}
}
})
t.Run("entry.Validate applies required and type to a media field", func(t *testing.T) {
schema := mediaThumbnailSchema(t, true)
expectFieldError(t, entry.Validate(schema, map[string]any{"title": "A"}), "thumbnail", entry.RuleRequired)
expectFieldError(t, entry.Validate(schema, map[string]any{"title": "A", "thumbnail": nil}), "thumbnail", entry.RuleRequired)
expectFieldError(t, entry.Validate(schema, map[string]any{"title": "A", "thumbnail": "7"}), "thumbnail", contenttype.RuleType)
expectFieldError(t, entry.Validate(schema, map[string]any{"title": "A", "thumbnail": 7.5}), "thumbnail", contenttype.RuleType)
if err := entry.Validate(schema, map[string]any{"title": "A", "thumbnail": float64(7)}); err != nil {
t.Errorf("valid media: %v", err)
}
if err := entry.Validate(mediaThumbnailSchema(t, false), map[string]any{"title": "A"}); err != nil {
t.Errorf("optional media: %v", err)
}
})
}
type mediaFieldFixture struct {
types *mockContentTypeRepo
entries *mockEntryRepo
images *mockImageRepo
now func() time.Time
}
func newMediaFieldFixture(t *testing.T, required bool) *mediaFieldFixture {
t.Helper()
fixture := &mediaFieldFixture{types: newMockContentTypeRepo(), entries: newMockEntryRepo(), images: newMockImageRepo(), now: func() time.Time { return time.Date(2026, time.October, 5, 9, 0, 0, 0, time.UTC) }}
if _, err := fixture.types.Create(contenttype.ContentType{Key: "event", Name: "Events", Fields: mediaThumbnailSchema(t, required)}); err != nil {
t.Fatalf("type: %v", err)
}
fixture.images.images[7] = imageDomain.Image{ID: 7, Filename: "lime-plaster.jpg", Path: mfImagePath, Width: 1600, Height: 900, Size: 240000}
fixture.images.images[8] = imageDomain.Image{ID: 8, Filename: "bathroom-tiles.png", Path: "/v1/static/uploadedImages/bathroom-tiles.png"}
fixture.types.createCalls = 0
return fixture
}
func TestMediaFieldUseCases(t *testing.T) {
t.Run("CreateEntry returns the same errors for a missing library image and creates nothing", func(t *testing.T) {
fixture := newMediaFieldFixture(t, false)
create := useCases.NewCreateEntryUseCase(fixture.types, fixture.entries, fixture.images, fixture.now)
_, err := create.Create(useCases.CreateEntryCommand{ContentTypeKey: "event", Data: map[string]any{"title": "A", "thumbnail": float64(999)}, UserID: 2})
expectFieldError(t, err, "thumbnail", contenttype.RuleType)
if fixture.entries.createCalls != 0 {
t.Errorf("creates %d", fixture.entries.createCalls)
}
})
t.Run("CreateEntry checks Validate before library existence", func(t *testing.T) {
fixture := newMediaFieldFixture(t, false)
create := useCases.NewCreateEntryUseCase(fixture.types, fixture.entries, fixture.images, fixture.now)
_, err := create.Create(useCases.CreateEntryCommand{ContentTypeKey: "event", Data: map[string]any{"thumbnail": float64(999)}, UserID: 2})
expectFieldError(t, err, "title", entry.RuleRequired)
})
t.Run("CreateEntry surfaces a library failure", func(t *testing.T) {
fixture := newMediaFieldFixture(t, false)
fixture.images.fail.failNext("Get")
create := useCases.NewCreateEntryUseCase(fixture.types, fixture.entries, fixture.images, fixture.now)
_, err := create.Create(useCases.CreateEntryCommand{ContentTypeKey: "event", Data: map[string]any{"title": "A", "thumbnail": float64(7)}, UserID: 2})
if !errors.Is(err, errRepositoryFailure) || fixture.entries.createCalls != 0 {
t.Errorf("err %v", err)
}
})
t.Run("UpdateEntry treats only the stored id as unchanged", func(t *testing.T) {
examples := []struct {
name string
required bool
value any
rule string
}{
{"unchanged and gone, optional", false, float64(7), ""},
{"unchanged and gone, required", true, float64(7), entry.RuleRequired},
{"changed to a missing image", false, float64(999), contenttype.RuleType},
{"changed to an existing image", true, float64(8), ""},
{"cleared, optional", false, nil, ""},
}
for _, example := range examples {
t.Run(example.name, func(t *testing.T) {
fixture := newMediaFieldFixture(t, example.required)
delete(fixture.images.images, 7)
stored, _ := fixture.entries.Create(entry.Entry{ContentTypeID: 1, Data: map[string]any{"title": "A", "thumbnail": float64(7)}})
fixture.entries.createCalls = 0
update := useCases.NewUpdateEntryUseCase(fixture.types, fixture.entries, fixture.images, fixture.now)
_, err := update.Update(useCases.UpdateEntryCommand{ContentTypeKey: "event", ID: stored.ID, Data: map[string]any{"title": "A", "thumbnail": example.value}, UserID: 3})
if example.rule == "" {
if err != nil || fixture.entries.updateCalls != 1 {
t.Errorf("err %v updates %d", err, fixture.entries.updateCalls)
}
return
}
expectFieldError(t, err, "thumbnail", example.rule)
if fixture.entries.updateCalls != 0 {
t.Errorf("updates %d", fixture.entries.updateCalls)
}
})
}
})
t.Run("UpdateContentType returns ErrSchemaIncompatible for a new required media field and does not update", func(t *testing.T) {
fixture := newMediaFieldFixture(t, false)
fixture.types.types[1] = contenttype.ContentType{ID: 1, Key: "event", Name: "Events", Fields: mediaThumbnailSchema(t, false)[:1]}
fixture.entries.Create(entry.Entry{ContentTypeID: 1, Data: map[string]any{"title": "A"}})
update := useCases.NewUpdateContentTypeUseCase(fixture.types, fixture.entries, fixture.now)
_, err := update.Update(useCases.UpdateContentTypeCommand{Key: "event", Name: "Events", Fields: mediaThumbnailSchema(t, true)})
if !errors.Is(err, contenttype.ErrSchemaIncompatible) || fixture.types.updateCalls != 0 {
t.Errorf("err %v updates %d", err, fixture.types.updateCalls)
}
})
t.Run("GetEntry and ListEntries resolve media once per distinct image and mark missing ones", func(t *testing.T) {
fixture := newMediaFieldFixture(t, false)
for _, id := range []float64{7, 7, 999} {
fixture.entries.Create(entry.Entry{ContentTypeID: 1, Data: map[string]any{"title": "A", "thumbnail": id}})
}
spy := &mfImageSpyRepo{mockImageRepo: fixture.images}
list := useCases.NewListEntriesUseCase(fixture.types, fixture.entries, spy)
page, err := list.ListPage(useCases.ListEntriesCommand{ContentTypeKey: "event", Page: 1, Size: 25, Sort: entry.Sort{Field: entry.SortByID, Direction: entry.SortAsc}})
if err != nil || spy.gets != 2 || len(page.Items) != 3 {
t.Fatalf("err %v lookups %d", err, spy.gets)
}
if page.Items[0].Media["thumbnail"].Filename != "lime-plaster.jpg" || !page.Items[2].Media["thumbnail"].Missing || page.Items[2].Media["thumbnail"].ID != 999 {
t.Errorf("media %+v %+v", page.Items[0].Media, page.Items[2].Media)
}
})
}
func TestMediaFieldUnknownDimensions(t *testing.T) {
fixture := newMediaFieldFixture(t, false)
owner, err := fixture.types.GetByKey("event")
if err != nil {
t.Fatalf("type: %v", err)
}
created, err := fixture.entries.Create(entry.Entry{ContentTypeID: owner.ID, Data: map[string]any{"title": "A", "thumbnail": float64(8)}})
if err != nil {
t.Fatalf("entry: %v", err)
}
get := useCases.NewGetEntryUseCase(fixture.types, fixture.entries, fixture.images)
found, err := get.Get("event", created.ID)
if err != nil {
t.Fatalf("get: %v", err)
}
media := found.Media["thumbnail"]
if media.Width != nil || media.Height != nil {
t.Errorf("dimensions %v %v, want nil", media.Width, media.Height)
}
}
+2 -2
View File
@@ -943,7 +943,7 @@ func TestMediaMerging(t *testing.T) {
t.Run("A duplicated id reaching the use case is refused before anything is read", func(t *testing.T) {
env := newEnv(t)
uc := useCases.NewMergeMediaUseCase(env.images, env.articles, env.storage, newMockVariantFileRepo(), discardRecorder, plainSites(), plainAuthors())
uc := useCases.NewMergeMediaUseCase(env.images, env.articles, env.storage, newMockVariantFileRepo(), discardRecorder, plainSites(), plainAuthors(), newMockContentTypeRepo(), newMockEntryRepo())
_, err := uc.Merge(testCtx, 2, []uint32{3, 3})
@@ -1038,7 +1038,7 @@ func TestMediaSentinels(t *testing.T) {
env.seedImage(2, "b.png", 1, "image/png", 1, 1, hashB, 1)
env.seedImage(3, "c.png", 1, "image/png", 1, 1, "", 1)
env.seedImage(4, "d.png", 1, "image/png", 1, 1, "", 1)
uc := useCases.NewMergeMediaUseCase(env.images, env.articles, env.storage, newMockVariantFileRepo(), discardRecorder, plainSites(), plainAuthors())
uc := useCases.NewMergeMediaUseCase(env.images, env.articles, env.storage, newMockVariantFileRepo(), discardRecorder, plainSites(), plainAuthors(), newMockContentTypeRepo(), newMockEntryRepo())
if _, err := uc.Merge(testCtx, 1, []uint32{9999}); !errors.Is(err, domainImage.ErrMergeCopyMissing) {
t.Errorf("expected ErrMergeCopyMissing, got %v", err)
+1 -1
View File
@@ -270,7 +270,7 @@ func TestListMediaUseCasePaging(t *testing.T) {
build := func() (*mockImageRepo, *mockVariantFileRepo, *useCases.ListMediaUseCase) {
images := newMockImageRepo()
variants := newMockVariantFileRepo()
return images, variants, useCases.NewListMediaUseCase(images, newMockArticleRepo(), newMockUserRepo(), variants, plainSites(), plainAuthors())
return images, variants, useCases.NewListMediaUseCase(images, newMockArticleRepo(), newMockUserRepo(), variants, plainSites(), plainAuthors(), newMockContentTypeRepo(), newMockEntryRepo())
}
seed := func(images *mockImageRepo, count int) {
for id := uint32(1); id <= uint32(count); id++ {
+1 -1
View File
@@ -31,7 +31,7 @@ type schedulerEnv struct {
func newSchedulerEnv(t *testing.T) *schedulerEnv {
t.Helper()
env := newPurgeEnv(t)
merge := useCases.NewMergeMediaUseCase(env.images, env.articles, env.storage, newMockVariantFileRepo(), discardRecorder, plainSites(), plainAuthors())
merge := useCases.NewMergeMediaUseCase(env.images, env.articles, env.storage, newMockVariantFileRepo(), discardRecorder, plainSites(), plainAuthors(), newMockContentTypeRepo(), newMockEntryRepo())
now := func() time.Time { return env.clock }
runPurge := useCases.NewRunPurgeUseCase(env.images, env.articles, merge, env.purgeSettings, now, log.New(env.logs, "", 0), discardRecorder, plainSites(), plainAuthors())
return &schedulerEnv{
+5 -5
View File
@@ -32,7 +32,7 @@ func TestUpdatePurgeSettingsRejectsOutOfRangeIntervals(t *testing.T) {
func TestRunPurgeDistinguishesBusyFromConflict(t *testing.T) {
newRun := func(env *mediaEnv) *useCases.RunPurgeUseCase {
merge := useCases.NewMergeMediaUseCase(env.images, env.articles, env.storage, newMockVariantFileRepo(), discardRecorder, plainSites(), plainAuthors())
merge := useCases.NewMergeMediaUseCase(env.images, env.articles, env.storage, newMockVariantFileRepo(), discardRecorder, plainSites(), plainAuthors(), newMockContentTypeRepo(), newMockEntryRepo())
return useCases.NewRunPurgeUseCase(env.images, env.articles, merge, env.purgeSettings, func() time.Time { return env.clock }, log.New(&bytes.Buffer{}, "", 0), discardRecorder, plainSites(), plainAuthors())
}
@@ -114,7 +114,7 @@ func TestPurgePlanOrderingAndFingerprint(t *testing.T) {
env.useImages(11, 5)
env.useImages(12, 3)
preview, err := useCases.NewPreviewPurgeUseCase(env.images, env.articles, plainSites(), plainAuthors()).Preview()
preview, err := useCases.NewPreviewPurgeUseCase(env.images, env.articles, plainSites(), plainAuthors(), newMockContentTypeRepo(), newMockEntryRepo()).Preview()
var kept []uint32
for _, group := range preview.List {
@@ -132,7 +132,7 @@ func TestPurgePlanOrderingAndFingerprint(t *testing.T) {
env.useImages(10, 1, 2, 3)
env.useImages(11, 5)
preview, err := useCases.NewPreviewPurgeUseCase(env.images, env.articles, plainSites(), plainAuthors()).Preview()
preview, err := useCases.NewPreviewPurgeUseCase(env.images, env.articles, plainSites(), plainAuthors(), newMockContentTypeRepo(), newMockEntryRepo()).Preview()
sum := sha256.Sum256([]byte("1:2,3;5:4;"))
if err != nil || preview.Fingerprint != hex.EncodeToString(sum[:]) {
@@ -148,7 +148,7 @@ func TestMergeMediaExposesTheRewrittenArticleIds(t *testing.T) {
env.useImages(1, 2)
env.useImages(2, 1, 2)
env.useImages(3, 1)
merge := useCases.NewMergeMediaUseCase(env.images, env.articles, env.storage, newMockVariantFileRepo(), discardRecorder, plainSites(), plainAuthors())
merge := useCases.NewMergeMediaUseCase(env.images, env.articles, env.storage, newMockVariantFileRepo(), discardRecorder, plainSites(), plainAuthors(), newMockContentTypeRepo(), newMockEntryRepo())
result, err := merge.Merge(testCtx, 1, []uint32{2})
@@ -163,7 +163,7 @@ func TestMergeMediaExposesTheRewrittenArticleIds(t *testing.T) {
env.useImages(1, 2)
env.useImages(2, 2)
env.articles.failUpdateBodyFor = map[uint32]error{2: errRepositoryFailure}
merge := useCases.NewMergeMediaUseCase(env.images, env.articles, env.storage, newMockVariantFileRepo(), discardRecorder, plainSites(), plainAuthors())
merge := useCases.NewMergeMediaUseCase(env.images, env.articles, env.storage, newMockVariantFileRepo(), discardRecorder, plainSites(), plainAuthors(), newMockContentTypeRepo(), newMockEntryRepo())
result, err := merge.Merge(testCtx, 1, []uint32{2})
+1 -1
View File
@@ -112,7 +112,7 @@ func TestMergeMediaRemovesTheMergedBlobs(t *testing.T) {
create := useCases.NewCreateImageUseCase(repo, store, discardRecorder)
kept, copyOne, copyTwo := uploadPng(t, create), uploadPng(t, create), uploadPng(t, create)
result, err := useCases.NewMergeMediaUseCase(repo, articles, store, newMockVariantFileRepo(), discardRecorder, plainSites(), plainAuthors()).Merge(testCtx, kept.ID, []uint32{copyOne.ID, copyTwo.ID})
result, err := useCases.NewMergeMediaUseCase(repo, articles, store, newMockVariantFileRepo(), discardRecorder, plainSites(), plainAuthors(), newMockContentTypeRepo(), newMockEntryRepo()).Merge(testCtx, kept.ID, []uint32{copyOne.ID, copyTwo.ID})
if err != nil || result.Merged != 2 {
t.Fatalf("merge returned %+v, %v", result, err)
+3 -3
View File
@@ -143,11 +143,11 @@ func newRuntimeSettingsContainer(t *testing.T) *api.UseCases {
SendMailUseCase: useCases.NewSendMailUseCase(mailRepo),
CreateImageUseCase: useCases.NewCreateImageUseCase(imageRepo, newMockImageStorage(), discardRecorder),
GenerateVariantsOnUploadUseCase: newInertGenerateOnUploadUseCase(),
ListMediaUseCase: useCases.NewListMediaUseCase(imageRepo, articleRepo, userRepo, newMockVariantFileRepo(), plainSites(), plainAuthors()),
ListMediaUseCase: useCases.NewListMediaUseCase(imageRepo, articleRepo, userRepo, newMockVariantFileRepo(), plainSites(), plainAuthors(), newMockContentTypeRepo(), newMockEntryRepo()),
RenameMediaUseCase: useCases.NewRenameMediaUseCase(imageRepo, discardRecorder),
DeleteMediaUseCase: useCases.NewDeleteMediaUseCase(imageRepo, newMockImageStorage(), newMockVariantFileRepo(), discardRecorder, plainSites(), plainAuthors(), newMockArticleRepo()),
MergeMediaUseCase: useCases.NewMergeMediaUseCase(imageRepo, articleRepo, newMockImageStorage(), newMockVariantFileRepo(), discardRecorder, plainSites(), plainAuthors()),
GetMediaUsageUseCase: useCases.NewGetMediaUsageUseCase(imageRepo, articleRepo, plainSites(), plainAuthors()),
MergeMediaUseCase: useCases.NewMergeMediaUseCase(imageRepo, articleRepo, newMockImageStorage(), newMockVariantFileRepo(), discardRecorder, plainSites(), plainAuthors(), newMockContentTypeRepo(), newMockEntryRepo()),
GetMediaUsageUseCase: useCases.NewGetMediaUsageUseCase(imageRepo, articleRepo, plainSites(), plainAuthors(), newMockContentTypeRepo(), newMockEntryRepo()),
}
}
+3 -3
View File
@@ -293,7 +293,7 @@ func TestSeoDataCleanerCompensationFailuresAreLogged(t *testing.T) {
e.updateArticle(9, func(a *article.Article) { a.Body = e.bodyUsing(6) })
buffer := captureLog(t)
flaky := &seoFlakyBodyArticles{mockArticleRepo: e.articles}
merge := useCases.NewMergeMediaUseCase(e.images, flaky, newMockImageStorage(), newMockVariantFileRepo(), discardRecorder, e.sites, e.authors)
merge := useCases.NewMergeMediaUseCase(e.images, flaky, newMockImageStorage(), newMockVariantFileRepo(), discardRecorder, e.sites, e.authors, newMockContentTypeRepo(), newMockEntryRepo())
_, err := merge.Merge(t.Context(), 5, []uint32{6})
@@ -330,7 +330,7 @@ func TestSeoDataCleanerCaseInsensitiveBodyMatches(t *testing.T) {
e := newSeoEnv(t)
seed(e)
before := e.stored(9)
merge := useCases.NewMergeMediaUseCase(e.images, seoCaseInsensitiveBodyArticles{e.articles}, newMockImageStorage(), newMockVariantFileRepo(), discardRecorder, e.sites, e.authors)
merge := useCases.NewMergeMediaUseCase(e.images, seoCaseInsensitiveBodyArticles{e.articles}, newMockImageStorage(), newMockVariantFileRepo(), discardRecorder, e.sites, e.authors, newMockContentTypeRepo(), newMockEntryRepo())
result, err := merge.Merge(t.Context(), 5, []uint32{6})
@@ -342,7 +342,7 @@ func TestSeoDataCleanerCaseInsensitiveBodyMatches(t *testing.T) {
t.Run("Usage only lists real body references", func(t *testing.T) {
e := newSeoEnv(t)
seed(e)
usage := useCases.NewGetMediaUsageUseCase(e.images, seoCaseInsensitiveBodyArticles{e.articles}, e.sites, e.authors)
usage := useCases.NewGetMediaUsageUseCase(e.images, seoCaseInsensitiveBodyArticles{e.articles}, e.sites, e.authors, newMockContentTypeRepo(), newMockEntryRepo())
items, err := usage.Usage(6)
+1 -1
View File
@@ -355,7 +355,7 @@ func TestSeoDataMediaMerge(t *testing.T) {
seedDuplicates(e)
e.updateArticle(8, func(a *article.Article) { a.CoverImageID = idPointer(6) })
e.updateArticle(9, func(a *article.Article) { a.SocialImageID = idPointer(6) })
merge := useCases.NewMergeMediaUseCase(e.images, e.articles, newMockImageStorage(), newMockVariantFileRepo(), discardRecorder, e.sites, e.authors)
merge := useCases.NewMergeMediaUseCase(e.images, e.articles, newMockImageStorage(), newMockVariantFileRepo(), discardRecorder, e.sites, e.authors, newMockContentTypeRepo(), newMockEntryRepo())
result, err := merge.Merge(testCtx, 5, []uint32{6})
+4 -4
View File
@@ -53,17 +53,17 @@ func newSeoEnv(t *testing.T) *seoEnv {
}
recorder := p.audit.recorder
renderer := &fakeBodyRenderer{}
mergeMedia := useCases.NewMergeMediaUseCase(p.images, p.articles, newMockImageStorage(), newMockVariantFileRepo(), recorder, sites, authors)
mergeMedia := useCases.NewMergeMediaUseCase(p.images, p.articles, newMockImageStorage(), newMockVariantFileRepo(), recorder, sites, authors, newMockContentTypeRepo(), newMockEntryRepo())
c := p.container
c.CreateArticleUseCase = useCases.NewCreateArticleUseCase(p.articles, renderer, recorder, sites, authors)
c.UpdateArticleUseCase = useCases.NewUpdateArticleUseCase(p.articles, renderer, recorder, sites, authors, p.images)
c.ListArticlesUseCase = useCases.NewListArticlesUseCase(p.articles, renderer, sites)
c.ListMediaUseCase = useCases.NewListMediaUseCase(p.images, p.articles, p.users, newMockVariantFileRepo(), sites, authors)
c.ListMediaUseCase = useCases.NewListMediaUseCase(p.images, p.articles, p.users, newMockVariantFileRepo(), sites, authors, newMockContentTypeRepo(), newMockEntryRepo())
c.DeleteMediaUseCase = useCases.NewDeleteMediaUseCase(p.images, newMockImageStorage(), newMockVariantFileRepo(), recorder, sites, authors, p.articles)
c.GetMediaUsageUseCase = useCases.NewGetMediaUsageUseCase(p.images, p.articles, sites, authors)
c.GetMediaUsageUseCase = useCases.NewGetMediaUsageUseCase(p.images, p.articles, sites, authors, newMockContentTypeRepo(), newMockEntryRepo())
c.MergeMediaUseCase = mergeMedia
c.RunPurgeUseCase = useCases.NewRunPurgeUseCase(p.images, p.articles, mergeMedia, newMockPurgeSettingsRepo(), func() time.Time { return p.now }, log.New(io.Discard, "", 0), recorder, sites, authors)
c.PreviewPurgeUseCase = useCases.NewPreviewPurgeUseCase(p.images, p.articles, sites, authors)
c.PreviewPurgeUseCase = useCases.NewPreviewPurgeUseCase(p.images, p.articles, sites, authors, newMockContentTypeRepo(), newMockEntryRepo())
c.ListSitesUseCase = useCases.NewListSitesUseCase(sites)
c.CreateSiteUseCase = useCases.NewCreateSiteUseCase(sites, p.images, recorder)
c.UpdateSiteUseCase = useCases.NewUpdateSiteUseCase(sites, p.images, recorder)
+3 -3
View File
@@ -298,15 +298,15 @@ func newSiteEnv(t *testing.T) *siteEnv {
sites := newMockSiteRepo(p.articles)
recorder := p.audit.recorder
renderer := &fakeBodyRenderer{}
mergeMedia := useCases.NewMergeMediaUseCase(p.images, p.articles, newMockImageStorage(), newMockVariantFileRepo(), recorder, sites, plainAuthors())
mergeMedia := useCases.NewMergeMediaUseCase(p.images, p.articles, newMockImageStorage(), newMockVariantFileRepo(), recorder, sites, plainAuthors(), newMockContentTypeRepo(), newMockEntryRepo())
c := p.container
c.CreateArticleUseCase = useCases.NewCreateArticleUseCase(p.articles, renderer, recorder, sites, plainAuthors())
c.UpdateArticleUseCase = useCases.NewUpdateArticleUseCase(p.articles, renderer, recorder, sites, plainAuthors(), p.images)
c.ListArticlesUseCase = useCases.NewListArticlesUseCase(p.articles, renderer, sites)
c.ListMediaUseCase = useCases.NewListMediaUseCase(p.images, p.articles, p.users, newMockVariantFileRepo(), sites, plainAuthors())
c.ListMediaUseCase = useCases.NewListMediaUseCase(p.images, p.articles, p.users, newMockVariantFileRepo(), sites, plainAuthors(), newMockContentTypeRepo(), newMockEntryRepo())
c.DeleteMediaUseCase = useCases.NewDeleteMediaUseCase(p.images, newMockImageStorage(), newMockVariantFileRepo(), recorder, sites, plainAuthors(), p.articles)
c.MergeMediaUseCase = mergeMedia
c.GetMediaUsageUseCase = useCases.NewGetMediaUsageUseCase(p.images, p.articles, sites, plainAuthors())
c.GetMediaUsageUseCase = useCases.NewGetMediaUsageUseCase(p.images, p.articles, sites, plainAuthors(), newMockContentTypeRepo(), newMockEntryRepo())
c.RunPurgeUseCase = useCases.NewRunPurgeUseCase(p.images, p.articles, mergeMedia, newMockPurgeSettingsRepo(), func() time.Time { return p.now }, log.New(io.Discard, "", 0), recorder, sites, plainAuthors())
c.ListSitesUseCase = useCases.NewListSitesUseCase(sites)
c.CreateSiteUseCase = useCases.NewCreateSiteUseCase(sites, p.images, recorder)