docs: plan Related Stories layouts

This commit is contained in:
chrnx committed 2026-08-12 18:32:38 -05:00
1 parent e9a551064b
commit e0e9ba51c5
1 file changed
+423
@@ -0,0 +1,423 @@
# Related Stories Layouts Implementation Plan
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
**Goal:** Make `chrnx/related-posts` configurable as three or five stories in adaptive, grid, or manual carousel layouts, with usable no-JavaScript behavior and valid seeded destinations.
**Architecture:** Keep the existing tiered PHP selector and editorial-card helper as the data authority. Extend the dynamic block with strict server attributes, a registered client edit component, and a block-scoped frontend controller that reveals enhancement controls only after successful initialization. CSS owns layout and native horizontal scrolling; JavaScript only measures one-card movement, edge state, responsive semantics, and focus repair.
**Tech Stack:** WordPress 6.9.6 block metadata and dynamic rendering, vanilla JavaScript, WordPress editor packages, PHP 8.3, PHPUnit, Jest/jsdom, Node smoke tests, Playwright, Stylelint, PHPCS.
---
## Working rules
- Work only in `/Users/chrnx/workspace/chrnx-dev/wp-theme/.worktrees/related-stories-layouts` on `feature/related-stories-layouts`.
- Do not merge, push, deploy, publish, or mutate production content.
- Use an isolated `wp-env`; do not stop or reuse the root environment on port 8888. Create an ignored temporary `.wp-env.override.json` with ports 8908/8909 and a temporary Playwright config outside the repository when browser verification begins.
- Follow strict RED → GREEN. Every production behavior below must first fail for the intended reason.
- Preserve `chrnx_get_related_post_ids()` topic → shared tags → recency semantics.
- Never commit `node_modules`, Playwright reports, screenshots, temporary environment files, credentials, or seeded database state.
## File map
### Modify
- `blocks/related-posts/block.json` — exact public attributes plus editor/frontend asset ownership.
- `blocks/related-posts/render.php` — strict defaults, layout class, accessible track, and enhancement controls.
- `blocks/related-posts/style.css` — adaptive/grid/carousel geometry and control styling.
- `tests/php/BlockRenderingTest.php` — server validation, counts, markup, localization, and empty/partial states.
- `tests/php/EditorAssetsTest.php` — registered editor/view asset metadata and dependencies.
- `tests/smoke/theme-preference-contract.test.mjs` — static block asset/schema ownership contract.
- `tests/e2e/global-setup.mjs` only if the existing idempotent fixture seed needs no-op-safe related-story guarantees.
- `tests/fixtures/posts.json` only if deterministic five-related-story coverage cannot be formed from the existing twelve posts; keep the approved fixture count invariant unless a failing test proves expansion necessary.
### Create
- `assets/js/editor-related-posts.js` — WordPress 6.9.6 client block registration, inspector controls, and server preview.
- `assets/js/editor-related-posts.asset.php` — exact local WordPress dependencies and `CHRNX_VERSION`-compatible asset version.
- `assets/js/related-posts.js` — independent progressive controllers for rendered rails.
- `tests/js/editor-related-posts.test.js` — registration, numeric coercion, allowlisting, and edit behavior.
- `tests/js/related-posts.test.js` — initialization, navigation, focus, resize, failure, and cleanup behavior.
- `tests/e2e/related-stories.spec.mjs` — real editor, frontend, responsive, accessibility, no-JS, and permalink coverage.
- `tests/smoke/related-stories-contract.test.mjs` — metadata, CSS, localization, and forbidden-behavior checks.
## Task 1: Lock the dynamic block's server contract
**Files:**
- Modify: `blocks/related-posts/block.json`
- Modify: `blocks/related-posts/render.php`
- Modify: `tests/php/BlockRenderingTest.php`
- Create: `tests/smoke/related-stories-contract.test.mjs`
- [ ] **Step 1: Write failing metadata and render tests**
Add Node smoke assertions that require:
```js
assert.deepEqual(metadata.attributes.limit, {
type: 'integer', default: 3, enum: [3, 5],
});
assert.deepEqual(metadata.attributes.layout, {
type: 'string', default: 'adaptive', enum: ['adaptive', 'grid', 'carousel'],
});
assert.equal(metadata.editorScript, 'file:../../assets/js/editor-related-posts.js');
assert.equal(metadata.viewScript, 'file:../../assets/js/related-posts.js');
```
Add PHPUnit data providers that render the block with malformed, missing, and valid attributes. Assert:
- missing, `1`, `12`, string `"5"`, negative, array, and float limits render exactly three cards;
- integer `5` renders exactly five when five eligible posts exist;
- invalid layout values render `is-layout-adaptive` only;
- valid values render exactly one matching `is-layout-*` class;
- grid emits no controls and no track region/tab stop;
- adaptive/carousel emit a labelled, focusable region and a `role="group"` controls wrapper with `hidden`;
- one, two, and four available posts render only that many cards;
- zero results return no section;
- button and group labels are localized through text domain `chrnx`.
Use HTML parsing or `WP_HTML_Tag_Processor`, not card-count substring guesses.
- [ ] **Step 2: Run focused RED tests**
Run:
```bash
node --test tests/smoke/related-stories-contract.test.mjs
PATH=/opt/homebrew/opt/docker/bin:$PATH npm run test:php -- --filter 'BlockRenderingTest::test_related'
```
Expected: smoke fails because `layout`, scripts, and enum are absent; PHPUnit fails because the renderer accepts 1–12 and always emits the old grid wrapper.
- [ ] **Step 3: Implement strict metadata and server rendering**
In `block.json`, replace the limit range with enum `[3,5]`, add `layout`, `editorScript`, and `viewScript`.
In `render.php`, allowlist with strict type checks:
```php
$chrnx_limit = isset( $attributes['limit'] ) && is_int( $attributes['limit'] ) && 5 === $attributes['limit'] ? 5 : 3;
$chrnx_layout = isset( $attributes['layout'] ) && is_string( $attributes['layout'] ) && in_array( $attributes['layout'], array( 'adaptive', 'grid', 'carousel' ), true )
? $attributes['layout']
: 'adaptive';
```
Render the spec's class and semantic variants. Escape every generated ID/class/label. Keep cards and their query order unchanged.
- [ ] **Step 4: Run focused GREEN tests**
Run the commands from Step 2.
Expected: smoke PASS; focused PHPUnit PASS with exact card counts, allowlisting, and markup.
- [ ] **Step 5: Run server regression gates**
Run:
```bash
PATH=/opt/homebrew/opt/docker/bin:$PATH npm run test:php -- --filter 'BlockRenderingTest|EditorialQueriesTest'
PATH=/opt/homebrew/opt/docker/bin:$PATH npm run phpcs
git diff --check
```
Expected: all selected tests PASS; PHPCS and diff check exit 0.
- [ ] **Step 6: Commit Task 1**
```bash
git add blocks/related-posts/block.json blocks/related-posts/render.php tests/php/BlockRenderingTest.php tests/smoke/related-stories-contract.test.mjs
git commit -m "feat: configure Related Stories rendering"
```
## Task 2: Register and configure the block in both editors
**Files:**
- Create: `assets/js/editor-related-posts.js`
- Create: `assets/js/editor-related-posts.asset.php`
- Create: `tests/js/editor-related-posts.test.js`
- Modify: `tests/php/EditorAssetsTest.php`
- Modify: `tests/e2e/related-stories.spec.mjs`
- [ ] **Step 1: Write failing client registration tests**
Build a Jest fixture with minimal `wp.blocks`, `wp.blockEditor`, `wp.components`, `wp.element`, `wp.i18n`, and `wp.serverSideRender` APIs. Require:
- one `registerBlockType('chrnx/related-posts', …)` call;
- exact attributes matching `block.json`;
- `save()` returns `null`;
- the edit tree contains ServerSideRender and an InspectorControls panel;
- selecting `5` calls `setAttributes({limit: 5})`, not `"5"`;
- malformed limit values become `3`;
- layout persists only `adaptive`, `grid`, or `carousel`, otherwise `adaptive`;
- missing WordPress globals/dependencies fail closed without registration or thrown errors;
- all UI strings pass through `wp.i18n.__` with `chrnx`.
- [ ] **Step 2: Write failing PHP asset tests**
In `EditorAssetsTest`, retrieve the registered `chrnx/related-posts` type after `init`. Assert that its editor and view handles resolve to local theme files, the editor dependencies exactly match the asset manifest, translations use `chrnx`, and the block remains registered when current screen is `post`, `site-editor`, or absent.
- [ ] **Step 3: Run focused RED tests**
```bash
npm run test:js -- --runTestsByPath tests/js/editor-related-posts.test.js
PATH=/opt/homebrew/opt/docker/bin:$PATH npm run test:php -- --filter 'EditorAssetsTest.*related'
```
Expected: Jest fails because the editor module does not exist; PHPUnit fails because no editor asset metadata exists.
- [ ] **Step 4: Implement the client block**
Create a no-JSX IIFE that validates required WordPress APIs, registers the dynamic block, creates two `SelectControl` components, and renders ServerSideRender. Use the exact numeric coercion and layout allowlist from the spec. Create the adjacent PHP asset manifest with local dependencies; do not enqueue it through `inc/editor.php`.
- [ ] **Step 5: Run focused GREEN tests and lint**
```bash
npm run test:js -- --runTestsByPath tests/js/editor-related-posts.test.js
PATH=/opt/homebrew/opt/docker/bin:$PATH npm run test:php -- --filter 'EditorAssetsTest.*related'
npm run lint:js -- --max-warnings=0
PATH=/opt/homebrew/opt/docker/bin:$PATH npm run phpcs
```
Expected: all commands PASS with numeric `5` persisted and no global errors.
- [ ] **Step 6: Prove real post and Site Editor availability**
Start the isolated environment, seed it, and add Playwright tests that log in locally, open `/wp-admin/post-new.php`, insert/select Related Posts, and verify both controls. Then open `/wp-admin/site-editor.php`, edit the Single template, select its existing Related Posts block, choose five/carousel, and verify the serialized block attributes through editor state without saving or publishing.
Run with a temporary Playwright config whose `baseURL` is `http://localhost:8908`:
```bash
npx playwright test tests/e2e/related-stories.spec.mjs --project=chromium --grep 'post editor|Site Editor'
```
Expected: 2 tests PASS; no save/publish action occurs.
- [ ] **Step 7: Commit Task 2**
```bash
git add assets/js/editor-related-posts.js assets/js/editor-related-posts.asset.php tests/js/editor-related-posts.test.js tests/php/EditorAssetsTest.php tests/e2e/related-stories.spec.mjs
git commit -m "feat: add Related Stories editor controls"
```
## Task 3: Add the progressive carousel controller
**Files:**
- Create: `assets/js/related-posts.js`
- Create: `tests/js/related-posts.test.js`
- Modify: `blocks/related-posts/render.php` only if the RED test proves a missing data hook
- [ ] **Step 1: Write failing controller tests**
Create real DOM fixtures for two block instances. Inject matchMedia and element geometry rather than implementation mocks. Test:
- each instance initializes independently and reveals only its own controls;
- grid never initializes controls;
- adaptive initializes as rail at `max-width: 900px` and as grid above it;
- carousel stays a rail at every width;
- Next/Previous call `scrollBy` with one measured card width plus computed gap;
- start/end buttons receive correct native disabled states after scroll and resize;
- reduced motion selects instant/auto behavior and default permits smooth behavior;
- missing buttons, track, cards, matchMedia, or scroll APIs leave controls hidden and do not throw;
- 900→901 while either button owns focus moves focus to the visible heading before hiding;
- unrelated focus stays unchanged;
- rail semantics and controls restore at 901→900;
- reinitialization does not duplicate listeners; cleanup removes every listener;
- no timers, autoplay, clones, globals, link rewriting, or network APIs are used.
- [ ] **Step 2: Run controller RED**
```bash
npm run test:js -- --runTestsByPath tests/js/related-posts.test.js
```
Expected: FAIL because `assets/js/related-posts.js` is missing.
- [ ] **Step 3: Implement the smallest controller**
Use an IIFE with an exported CommonJS test surface only when `module.exports` exists, matching the repository's navigation/theme pattern. Initialize on DOM ready, scope queries to each section, use a `MediaQueryList`, calculate `card.getBoundingClientRect().width + parseFloat(getComputedStyle(track).columnGap || getComputedStyle(track).gap)`, update edge state from `scrollLeft`, `clientWidth`, and `scrollWidth`, and return cleanup callbacks. Reveal controls only after all requirements pass.
- [ ] **Step 4: Run controller GREEN and full JavaScript suite**
```bash
npm run test:js -- --runTestsByPath tests/js/related-posts.test.js
npm run test:js
npm run lint:js -- --max-warnings=0
```
Expected: focused and full Jest suites PASS; lint exits 0.
- [ ] **Step 5: Commit Task 3**
```bash
git add assets/js/related-posts.js tests/js/related-posts.test.js blocks/related-posts/render.php
git commit -m "feat: enhance Related Stories carousels"
```
## Task 4: Implement measurable grid and rail presentation
**Files:**
- Modify: `blocks/related-posts/style.css`
- Modify: `tests/smoke/related-stories-contract.test.mjs`
- Modify: `tests/e2e/related-stories.spec.mjs`
- [ ] **Step 1: Write failing static CSS contract tests**
Require selectors for all three layout classes, the 900px boundary, `overflow-x:auto`, `scroll-snap-type:x mandatory`, `scroll-snap-align:start`, the mobile flex-basis formula, three-column desktop grids, native `[hidden]`, 45px controls, light/dark focus tokens, and reduced-motion behavior. Reject animation, autoplay hooks, forced hidden scrollbars, `overflow-x:hidden` on page roots, and fixed pixel card widths.
- [ ] **Step 2: Run smoke RED**
```bash
node --test tests/smoke/related-stories-contract.test.mjs
```
Expected: FAIL because `style.css` contains only card-media fallback rules.
- [ ] **Step 3: Implement CSS layout and controls**
Use block-local custom properties for gap and card basis. Grid modes use `repeat(min(3, item-count), minmax(0,1fr))` behavior through safe selectors/classes or auto-fit with a tested minimum; do not rely on unsupported generated CSS. Rails use flex, native overflow, snap, overscroll containment, and stable scrollbar space when supported. Preserve card heights through stretch alignment and set `min-width:0` on content. Style buttons from theme tokens with 45px targets and existing focus contrast.
- [ ] **Step 4: Run smoke/CSS GREEN**
```bash
node --test tests/smoke/related-stories-contract.test.mjs
npm run lint:css -- --max-warnings=0
git diff --check
```
Expected: all PASS.
- [ ] **Step 5: Add runtime layout matrix before adjusting production CSS**
Extend Playwright to create deterministic Related Stories variants locally through block attributes and seeded posts. Cover `3/5 × adaptive/grid/carousel` at 375, 768, 900, 901, 1440, and 2560 in Light and Dark. Also exercise adaptive one/two/four availability fixtures without changing production query semantics.
Assert:
- exact card counts and grid column counts;
- controls visible only for active rails;
- desktop carousel card width equals `(track - 2 gaps)/3 ±2px`;
- mobile card width equals the specified formula ±2px;
- next-card preview is at least 24px and no more than 25% when another card exists;
- only the track overflows; root `scrollWidth <= clientWidth`;
- card text is not clipped at 200% zoom;
- section/cards/controls do not overlap;
- Light/Dark text and focus contrast remain compliant.
Run:
```bash
npx playwright test tests/e2e/related-stories.spec.mjs --project=chromium --grep 'layout matrix'
```
Expected before final CSS tuning: at least one geometry assertion FAIL for the old layout. Adjust only block-local CSS, rerun until PASS.
- [ ] **Step 6: Commit Task 4**
```bash
git add blocks/related-posts/style.css tests/smoke/related-stories-contract.test.mjs tests/e2e/related-stories.spec.mjs
git commit -m "style: add Related Stories layouts"
```
## Task 5: Verify real interaction, no-JS access, and valid links
**Files:**
- Modify: `tests/e2e/related-stories.spec.mjs`
- Modify: `tests/fixtures/posts.json` and `tests/e2e/global-setup.mjs` only if a RED test proves existing fixtures cannot provide five deterministic related stories
- [ ] **Step 1: Write failing browser acceptance tests**
On a seeded single-post route containing the default block, add tests for:
- button navigation moves exactly one card and updates disabled edges;
- native horizontal wheel/touch-compatible scrolling remains possible;
- Tab reaches the rail and buttons in DOM order and exits without wrapping/trapping;
- resizing at the 900/901 boundary repairs button focus to the heading;
- reduced motion produces no smooth programmatic scroll but preserves geometry;
- JavaScript-disabled adaptive/carousel variants keep controls hidden and every card/link reachable through the focus order;
- controller failure simulated before initialization leaves native rail and links usable;
- clicking each rendered related card reaches a same-origin published single-post response with HTTP 200 and no PHP warning;
- axe finds no automatically detectable WCAG 2.2 AA violations in grid and active carousel states.
- [ ] **Step 2: Run acceptance RED**
```bash
npx playwright test tests/e2e/related-stories.spec.mjs --project=chromium --grep 'interaction|no JavaScript|permalink|accessibility'
```
Expected: tests that require the new block behavior fail before final integration; fixture changes are authorized only if the permalink/count precondition itself fails.
- [ ] **Step 3: Make the minimum integration/fixture correction**
Prefer existing published fixtures. If five deterministic related posts are impossible, update existing fixture taxonomy/tag assignments without increasing the approved 7-page/12-post count, keep keys/slugs stable, and prove double-seed idempotency. Do not add test-only production URL rewriting.
- [ ] **Step 4: Run Chromium GREEN, then all engines**
```bash
npx playwright test tests/e2e/related-stories.spec.mjs --project=chromium
npx playwright test tests/e2e/related-stories.spec.mjs --project=firefox
npx playwright test tests/e2e/related-stories.spec.mjs --project=webkit
```
Expected: all behavior passes in Chromium, Firefox, and WebKit. Axe may remain intentionally Chromium-only and must be explicitly skipped elsewhere.
- [ ] **Step 5: Commit Task 5**
```bash
git add tests/e2e/related-stories.spec.mjs tests/fixtures/posts.json tests/e2e/global-setup.mjs
git commit -m "test: verify Related Stories workflows"
```
## Task 6: Final verification and handoff
**Files:** No new production scope.
- [ ] **Step 1: Run complete repository verification sequentially**
```bash
PATH=/opt/homebrew/opt/docker/bin:$PATH npm test
```
Expected: smoke, JS/CSS lint, PHPCS, Jest, PHPUnit on `tests-cli`, and Playwright all PASS. Do not run PHPUnit and Playwright concurrently against shared state.
- [ ] **Step 2: Verify the isolated live site**
```bash
PATH=/opt/homebrew/opt/docker/bin:$PATH npx wp-env run cli wp eval 'echo WP_Block_Type_Registry::get_instance()->is_registered("chrnx/related-posts") ? "RELATED_BLOCK=1\n" : "RELATED_BLOCK=0\n";'
curl -fsS -o /tmp/chrnx-related-single.html -w 'HTTP=%{http_code}\n' http://localhost:8908/una-cuerda-rota-tambien-puede-decidir-el-arreglo/
rg -n 'PHP Warning|PHP Fatal|Related stories|is-layout-adaptive' /tmp/chrnx-related-single.html
```
Expected: `RELATED_BLOCK=1`, HTTP 200, Related Stories markup present, and no PHP warning/fatal output.
- [ ] **Step 3: Security and scope review**
Inspect the complete branch diff. Confirm strict attribute allowlists, escaped output, local-only scripts, no raw SQL/request interpolation, no remote calls, no timers/autoplay, no cloned links, no secrets/absolute developer paths/debug calls, no production fixture hooks, and no changes outside the listed scope.
```bash
git diff main...HEAD --check
git status --short
git diff --stat main...HEAD
```
Expected: diff check clean; only intended files plus the ignored `node_modules` symlink if present; no temporary environment/config/report artifacts.
- [ ] **Step 4: Stop only the isolated environment**
```bash
PATH=/opt/homebrew/opt/docker/bin:$PATH npx wp-env stop
```
Expected: isolated 8908/8909 containers stop; root port 8888 remains untouched.
- [ ] **Step 5: Request spec and quality review**
Provide reviewers the design, this plan, commit list, exact test evidence, and branch diff. Fix valid findings through separate RED → GREEN commits; never amend reviewed commits.
- [ ] **Step 6: Report completion without integration**
Report commit IDs, test totals, isolated URL evidence, security review, and any remaining concerns. Do not merge to `main`, push, deploy, or publish until the user explicitly selects local integration.