Tags page (#298)

* Add spec for tag pages and tags index

* button no underscore

* Add implementation plan for tag pages and tags index

* Add TagListing type

* Extract createTag factory

* Add createTagPageCards factory

* Add getAllTagSlugs API

* Add getPagesByTag API

* Add getAllTagsWithCounts API

* Parallelize tag and page fetches in getAllTagsWithCounts

* Add Pagination component

* Use cx for Pagination class composition

* Add TagsIndex component

* Add /tags/[slug] route

* Parallelize params/searchParams awaits in /tags/[slug]

* Add /tags index route

* Activate tag buttons

* Add tag URLs to sitemap

* Mark PageGrid and Overlay as client components

* Filter zero-count tags from getAllTagSlugs

* Fix tag filter operator and draft filter for nullable field
This commit is contained in:
tmshv authored and GitHub committed 2026-04-25 17:16:46 +03:00
1 parent 467a218d00
commit 285527f43c
20 files changed
+1990 -15

No files matched your search

File diff suppressed because it is too large. Load diff
+247
View File
@@ -0,0 +1,247 @@
# Spec: Tag pages and tags index
## Goal
Make tag buttons on every page navigate to a paginated listing of pages sharing
that tag, and add an index page that lists all tags. Tag links currently target
`/tags/<slug>` (built in `factory.ts:179`) but no route handles them, so they
404 and the buttons are rendered with `disabled={true}`. Activate the links and
build the destination.
## Scope
In scope:
- New route `/tags/[slug]` — paginated listing of pages tagged `<slug>`.
- New route `/tags` — index of all tags ordered by page count.
- Activation of tag buttons in `TagList` (drop `disabled={true}`).
- Sitemap entries for both new route shapes.
- Unit tests for new factory and pagination logic.
Out of scope:
- Filtering or searching within a tag listing.
- Multi-tag intersection (`/tags/a+b` etc.).
- "Related tags" widget on a page.
- Editorial featuring of pages within a tag listing — when a `featured`/`starred`
field is added to PocketBase later, `createTagPageCards` is the one place to
flip `featured` from the source field.
- Russian collation niceties beyond `String#localeCompare("ru")` if a tiebreak
is ever needed.
## Routes
### `/tags/[slug]?page=N`
- Pages tagged with `<slug>`, sorted by PocketBase `updated` desc.
- 24 items per page.
- Page 1 statically generated via `generateStaticParams` (one entry per tag
slug); pages 2..N rendered on demand and cached by ISR (`revalidate = 30`).
Next.js `generateStaticParams` does not accept search params.
- Renders `<App>` with breadcrumb `Главная → Метки → <label>`, `<h1>{label}</h1>`,
`<PageGrid items={items} />`, and `<Pagination ... />`.
- Missing or invalid `?page` (non-integer, `<1`): treat as page 1, do not
redirect.
- `?page=N` exceeds the page count for a non-empty tag: `notFound()`.
- Empty tag (no non-draft pages): render heading, breadcrumb, and the copy
`Пока нет записей.` — no 404, regardless of `?page`.
- Unknown slug (no `tags` record): `notFound()`.
### `/tags`
- Single static route, ISR-revalidated.
- Renders `<App>` with breadcrumb `Главная → Метки`, `<h1>Метки</h1>`, and
a wrapped flex list of tag buttons rendering `<label> · <count>`.
- Tags sorted by `count desc`, ties broken by `label asc` (`localeCompare("ru")`).
- Tags with `count === 0` are omitted.
## Data layer
### New API functions in `src/remote/api.ts`
```ts
async function getPagesByTag(slug: string, page: number, perPage: number)
: Promise<TagListing | null>
async function getAllTagsWithCounts(): Promise<Tag[]>
async function getAllTagSlugs(): Promise<string[]>
```
`getPagesByTag` flow:
1. `pb.collection("tags").getFirstListItem<PbTag>(\`slug="${slug}"\`)` — return
`null` on not-found.
2. `pb.collection("pages").getList<PbPage>(page, perPage, { filter: \`tags ~
"${tag.id}" && draft=false\`, sort: "-updated", fields: "id,slug,title,cover,
updated,date" })`.
3. `fetchImagesByIds()` for the page's cover IDs only.
4. `createTagPageCards(pages, images)` to build `PageCardDto[]` (`featured`
always `false` for now).
5. Return `{ tag: createTag(record, total), items, total, page, perPage }`.
`getAllTagsWithCounts` flow (single-scan in-memory aggregation):
1. `pb.collection("pages").getFullList<{ tags: string[] }>({ filter:
"draft=false", fields: "tags" })` → `Map<tagId, count>`.
2. `pb.collection("tags").getFullList<PbTag>()`.
3. Join; drop `count === 0`; sort by `count desc` then `label asc`.
`getAllTagSlugs` is a lighter variant used by `generateStaticParams` and
`sitemap.ts` — `pb.collection("tags").getFullList<PbTag>({ fields: "slug" })`.
### New types in `src/types.ts`
```ts
export type TagListing = {
tag: Tag
items: PageCardDto[]
total: number
page: number
perPage: number
}
```
The existing `Tag.count` field becomes meaningful (it is currently hard-coded to
`0` in `createPage`).
### New factory functions in `src/remote/factory.ts`
```ts
export function createTag(record: PbTag, count: number): Tag
export function createTagPageCards(
pages: PbPage[],
images: Map<string, PbImage>,
): PageCardDto[]
```
The inline tag-mapping at `factory.ts:175-181` is replaced with `createTag(record, 0)`.
`createTagPageCards` always sets `featured: false`. When a `featured`/`starred`
field lands on PocketBase pages later, this function is the single place to
read it.
## UI components
### New `src/components/TagsIndex/`
- `index.tsx` — server component.
- Props: `{ items: Tag[] }`.
- Renders a wrapped flex list of `Button` links from `@hudozka/ui`. Each button
reads `<label> · <count>` and links to `tag.href`.
- `styles.module.css` for layout (gap, wrap).
### New `src/components/Pagination/`
- `index.tsx` — server component.
- Props: `{ basePath: string; page: number; total: number; perPage: number }`.
- Renders `← Назад`, page numbers with ellipsis (window: first, last, current
±1; ellipsis when >7 pages), `Вперёд →`.
- Page links are `<Link href="${basePath}?page=N">`. The current page renders
as a non-link `<span>` with `aria-current="page"`.
- Hidden entirely when `total <= perPage`.
- Wrapper is `<nav aria-label="Постраничная навигация">`.
- `styles.module.css` for layout.
### Tag listing page body — composed inline in `src/app/tags/[slug]/page.tsx`
- `<App breadcrumbs={[home, { name: 'Метки', href: '/tags' }, { name: tag.name,
href: tag.href }]}>`.
- `<Title level={1}>{tag.name}</Title>` from `@hudozka/ui`.
- Empty: `<p>Пока нет записей.</p>`.
- Otherwise: `<PageGrid items={items} />` then `<Pagination ... />`.
### Tags index page body — composed inline in `src/app/tags/page.tsx`
- `<App breadcrumbs={[home, { name: 'Метки', href: '/tags' }]}>`.
- `<Title level={1}>Метки</Title>`.
- `<TagsIndex items={tags} />`.
### Activate `TagList`
- Remove `disabled={true}` from `TagItem` in `src/components/TagList/index.tsx:22`.
- Tag buttons become live links to `/tags/<slug>`. The underline removal from
`Button` (added earlier in the session) already covers the visual side.
## Metadata
`generateMetadata` per route, built with the existing `MetaBuilder` +
`buildMetadata()` helper for consistency with `[...slug]/page.tsx`.
`tags/page.tsx`:
- `title: "Метки"`.
- `description: "Список всех меток сайта."`.
`tags/[slug]/page.tsx`:
- Unknown slug: return `{}` (matches `[...slug]/page.tsx`).
- Page 1: `title: "{tag.name} — метка"`,
`description: "Записи с меткой «{tag.name}»."`.
- Pages 2+: `title: "{tag.name} — метка, страница {page}"`,
`robots: { index: false, follow: true }` so search engines don't index every
paginated variant.
## Sitemap
`src/app/sitemap.ts`:
- Add `/tags`.
- Add `/tags/<slug>` for every tag (page 1 only — paginated variants excluded).
- `lastModified: new Date()`, `changeFrequency: "weekly"`, `priority: 0.5`.
- Reuses `getAllTagSlugs()`.
## File plan
Created:
- `apps/hudozka/src/app/tags/page.tsx`
- `apps/hudozka/src/app/tags/[slug]/page.tsx`
- `apps/hudozka/src/components/TagsIndex/index.tsx`
- `apps/hudozka/src/components/TagsIndex/styles.module.css`
- `apps/hudozka/src/components/Pagination/index.tsx`
- `apps/hudozka/src/components/Pagination/styles.module.css`
- `apps/hudozka/src/components/Pagination/Pagination.test.tsx`
- `apps/hudozka/src/components/TagsIndex/TagsIndex.test.tsx`
Modified:
- `apps/hudozka/src/types.ts` — add `TagListing`.
- `apps/hudozka/src/remote/api.ts` — add `getPagesByTag`, `getAllTagsWithCounts`,
`getAllTagSlugs`.
- `apps/hudozka/src/remote/factory.ts` — extract `createTag`, add
`createTagPageCards`.
- `apps/hudozka/src/remote/factory.test.ts` — cases for `createTag` and
`createTagPageCards`.
- `apps/hudozka/src/components/TagList/index.tsx` — drop `disabled={true}`.
- `apps/hudozka/src/app/sitemap.ts` — append tag URLs.
## Testing
Vitest, co-located.
- `factory.test.ts` — `createTag(record, count)` propagates count and href;
`createTagPageCards(pages, images)` falls back to default cover when missing
and always sets `featured: false`.
- `Pagination.test.tsx` — hidden when `total <= perPage`, renders correct page
links, current page is non-link with `aria-current="page"`, ellipsis logic
for >7 pages.
- `TagsIndex.test.tsx` — renders `<label> · <count>`; component does not sort
(sorting is the API's job).
No tests for the App Router page modules — the existing codebase tests data and
components in isolation, not routes.
## Open questions
None. All resolved during brainstorming:
- Pagination style: page-based with `?page=N`.
- Item appearance: `PageGrid` reused, `featured: false` for now, future-ready
when starred pages land.
- Sort order: PocketBase `updated` desc.
- Heading and breadcrumb: `<label>` heading, `Главная → Метки → <label>` path.
- Page size: 24.
- Empty tag: render empty-state copy. Unknown tag: 404.
- `/tags` index: built now, sorted by count desc.
- Tag count strategy: single scan + in-memory aggregation.