Files
chrnx-dev-wp/docs/superpowers/plans/2026-08-12-related-stories-layouts.md

26 KiB
Raw Permalink Blame History

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 the ignored .wp-env.override.json with ports 8908/8909 before the first test. Parameterize the tracked Playwright config with CHRNX_E2E_BASE_URL, defaulting to 8888, and pass CHRNX_E2E_BASE_URL=http://localhost:8908 in every isolated browser/full-suite command.
  • 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.
  • playwright.config.mjs — environment-selectable base URL while preserving the default 8888 contract.
  • scripts/seed-test-content.sh and scripts/seed-test-content.php — local-only visual scenarios that mutate fixture-owned content only.

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 0: Start and prove the isolated environment

Files:

  • Create temporarily, never commit: .wp-env.override.json

  • Modify: playwright.config.mjs

  • Modify: tests/smoke/e2e-harness.test.mjs

  • Step 1: Write the failing environment-selection smoke test

Require playwright.config.mjs to read process.env.CHRNX_E2E_BASE_URL || 'http://localhost:8888', while retaining the existing serial scenario dependency project.

  • Step 2: Run RED
node --test tests/smoke/e2e-harness.test.mjs

Expected: FAIL because the base URL is hardcoded.

  • Step 3: Parameterize the base URL and create the ignored override

Apply the one-line config change, then create .wp-env.override.json with:

{
  "port": 8908,
  "testsPort": 8909
}
  • Step 4: Start, activate, install, and prove isolation
PATH=/opt/homebrew/opt/docker/bin:$PATH npx wp-env start --update
PATH=/opt/homebrew/opt/docker/bin:$PATH npx wp-env run cli wp theme activate chrnx
PATH=/opt/homebrew/opt/docker/bin:$PATH npm run composer -- install --no-interaction --prefer-dist
PATH=/opt/homebrew/opt/docker/bin:$PATH npx wp-env run cli wp option get home
curl -fsS -o /dev/null -w 'ROOT=%{http_code}\n' http://localhost:8888/
curl -fsS -o /dev/null -w 'ISOLATED=%{http_code}\n' http://localhost:8908/

Expected: home is http://localhost:8908; both HTTP probes are 200, proving the root environment remains available.

  • Step 5: Run GREEN and commit only tracked config/tests
node --test tests/smoke/e2e-harness.test.mjs
git add playwright.config.mjs tests/smoke/e2e-harness.test.mjs
git commit -m "test: parameterize CHRNX browser environment"

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:

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'],
});

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:

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 and the limit 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] and add layout. Do not reference scripts that do not exist yet; Tasks 2 and 3 add their own metadata atomically with their tested implementation.

In render.php, allowlist with strict type checks:

$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:

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
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: blocks/related-posts/block.json

  • 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 handle resolves to the local theme file, its dependencies exactly match the asset manifest, translations use chrnx, and the block remains registered when current screen is post, site-editor, or absent. Task 3 owns and tests viewScript atomically with the file it references.

  • Step 3: Write failing real-editor tests before implementation

Create tests/e2e/related-stories.spec.mjs. Log in locally, open /wp-admin/post-new.php, and assert that Related Posts is recognized/insertable and exposes both inspector controls. Open /wp-admin/site-editor.php, edit the Single template, select its Related Posts block, choose five/carousel, and inspect editor state to require numeric 5, allowlisted carousel, and null saved HTML. Never save or publish.

  • Step 4: Run focused RED tests
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'
CHRNX_E2E_BASE_URL=http://localhost:8908 npx playwright test tests/e2e/related-stories.spec.mjs --project=chromium --grep 'post editor|Site Editor'

Expected: Jest fails because the editor module does not exist; PHPUnit fails because no editor asset metadata exists; both browser cases fail because WordPress 6.9.6 has no registered client block.

  • Step 5: 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 and atomically add "editorScript":"file:../../assets/js/editor-related-posts.js" to block.json; do not enqueue it through inc/editor.php.

  • Step 6: Run focused GREEN tests, editors, and lint
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'
CHRNX_E2E_BASE_URL=http://localhost:8908 npx playwright test tests/e2e/related-stories.spec.mjs --project=chromium --grep 'post editor|Site Editor'
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, two real editor cases green, and no save/publish action or global errors.

  • Step 7: Commit Task 2
git add assets/js/editor-related-posts.js assets/js/editor-related-posts.asset.php blocks/related-posts/block.json 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"

Files:

  • Create: assets/js/related-posts.js

  • Create: tests/js/related-posts.test.js

  • Modify: blocks/related-posts/block.json

  • Modify: tests/php/EditorAssetsTest.php

  • Modify: tests/smoke/related-stories-contract.test.mjs

  • 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 first related-story link 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.

Add RED smoke/PHP assertions that viewScript equals the exact local controller path and its registered handle resolves to that existing file only when the block metadata is registered.

  • Step 2: Run controller RED
npm run test:js -- --runTestsByPath tests/js/related-posts.test.js
node --test tests/smoke/related-stories-contract.test.mjs
PATH=/opt/homebrew/opt/docker/bin:$PATH npm run test:php -- --filter 'EditorAssetsTest.*related.*view'

Expected: FAIL because assets/js/related-posts.js and the atomic viewScript metadata are 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. Add viewScript in the same change so metadata never references a missing file.

  • Step 4: Run controller GREEN and full JavaScript suite
npm run test:js -- --runTestsByPath tests/js/related-posts.test.js
node --test tests/smoke/related-stories-contract.test.mjs
PATH=/opt/homebrew/opt/docker/bin:$PATH npm run test:php -- --filter 'EditorAssetsTest.*related.*view'
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
git add assets/js/related-posts.js tests/js/related-posts.test.js blocks/related-posts/block.json blocks/related-posts/render.php tests/php/EditorAssetsTest.php tests/smoke/related-stories-contract.test.mjs
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

  • Modify: tests/fixtures/posts.json

  • 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
node --test tests/smoke/related-stories-contract.test.mjs

Expected: FAIL because style.css contains only card-media fallback rules.

  • Step 3: Write the failing runtime layout matrix before CSS implementation

Before writing the browser test, add six identified Related Stories block instances to the stored content of the existing synthetic long-title fixture—one for each 3/5 × adaptive/grid/carousel combination—wrapped in uniquely anchored groups. Keep the fixture count, key, slug, and published status unchanged. Global setup seeds this stable read-only route before all browser projects. Extend Playwright against that exact route at 375, 768, 900, 901, 1440, and 2560 in Light and Dark. Partial-result mutation scenarios belong to the separate serial Task 5 project, not this parallel read-only matrix.

Assert exact card counts and grid columns, active-rail control visibility, desktop/mobile card-width formulas, continuation preview bounds, track-only overflow, root containment, 200% text integrity, no intersections, and Light/Dark contrast.

CHRNX_E2E_BASE_URL=http://localhost:8908 npx playwright test tests/e2e/related-stories.spec.mjs --project=chromium --grep 'layout matrix'

Expected: FAIL because production CSS does not implement the selected layouts.

  • Step 4: 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 5: Run static and runtime GREEN
node --test tests/smoke/related-stories-contract.test.mjs
npm run lint:css -- --max-warnings=0
CHRNX_E2E_BASE_URL=http://localhost:8908 npx playwright test tests/e2e/related-stories.spec.mjs --project=chromium --grep 'layout matrix'
git diff --check

Expected: all PASS.

  • Step 6: Commit Task 4
git add blocks/related-posts/style.css tests/smoke/related-stories-contract.test.mjs tests/e2e/related-stories.spec.mjs tests/fixtures/posts.json
git commit -m "style: add Related Stories layouts"

Files:

  • Modify: tests/e2e/related-stories.spec.mjs

  • Modify: playwright.config.mjs

  • Modify: tests/smoke/e2e-harness.test.mjs

  • Modify as required by a valid RED: assets/js/related-posts.js, blocks/related-posts/render.php, blocks/related-posts/style.css

  • 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 first related-story link, which remains naturally focusable and visible in every engine's grid;
  • 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.

Partial availability counts of one, two, and four are server integration cases. Keep them in BlockRenderingTest.php, using isolated PHPUnit factories and parsed article counts. Browser coverage uses the stable seeded 3/5 × adaptive/grid/carousel matrix and must not mutate unrelated or unowned posts to manufacture smaller result sets.

Before implementation, extend tests/smoke/e2e-harness.test.mjs with a RED contract that recognizes only visual-scenarios.spec.mjs as a mutation spec, continues rejecting seed-test-content, wp-env, and execFileSync from every reader spec, and requires the dependency chain chromium/firefox/webkit → scenarios with the mutation project single-worker and non-parallel. The contract also rejects Related Stories scenarios or snapshots that could change unowned content.

  • Step 2: Run acceptance RED
CHRNX_E2E_BASE_URL=http://localhost:8908 npx playwright test tests/e2e/related-stories.spec.mjs --project=chromium --grep 'interaction|no JavaScript|permalink|accessibility'
node --test tests/smoke/e2e-harness.test.mjs

Expected: tests that require the new block behavior fail before final integration; harness smoke fails until browser specs stay read-only and no unsafe Related Stories mutation scenario exists.

  • Step 3: Make the minimum integration/fixture correction

Keep browser acceptance on the existing published fixtures. The local seed may update only _chrnx_fixture_key-owned records and must never snapshot, draft, delete, or otherwise mutate unowned posts. Preserve the approved 7-page/12-post count, stable keys/slugs, and production selector. Exact partial-count behavior remains covered by isolated PHPUnit factories; do not add URL rewriting or test-only production hooks.

  • Step 4: Run Chromium GREEN, then all engines
CHRNX_E2E_BASE_URL=http://localhost:8908 npx playwright test tests/e2e/related-stories.spec.mjs --project=chromium
CHRNX_E2E_BASE_URL=http://localhost:8908 npx playwright test tests/e2e/related-stories.spec.mjs --project=firefox
CHRNX_E2E_BASE_URL=http://localhost:8908 npx playwright test tests/e2e/related-stories.spec.mjs --project=webkit
node --test tests/smoke/e2e-harness.test.mjs

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
git add tests/e2e/related-stories.spec.mjs playwright.config.mjs tests/smoke/e2e-harness.test.mjs assets/js/related-posts.js blocks/related-posts/render.php blocks/related-posts/style.css
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
PATH=/opt/homebrew/opt/docker/bin:$PATH CHRNX_E2E_BASE_URL=http://localhost:8908 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
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 'Related stories|is-layout-adaptive' /tmp/chrnx-related-single.html
if rg -n 'PHP (?:Warning|Fatal|Notice)|Fatal error' /tmp/chrnx-related-single.html; then exit 1; fi

Expected: RELATED_BLOCK=1, HTTP 200, the positive markup search succeeds, and the negative error search finds nothing.

  • 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.

git diff main...HEAD --check
git status --short
git diff --stat main...HEAD

Expected: diff check clean; only intended files plus ignored temporary artifacts identified for deletion in Step 4.

  • Step 4: Stop only the isolated environment
PATH=/opt/homebrew/opt/docker/bin:$PATH npx wp-env stop
rm -f .wp-env.override.json
rm -rf test-results playwright-report
test ! -e .wp-env.override.json && test ! -e test-results && test ! -e playwright-report
git status --short --ignored

Expected: isolated 8908/8909 containers stop; root port 8888 remains untouched; ignored override/reports are gone. Re-run git status --short --ignored and confirm no temporary configuration/report artifact remains (an ignored node_modules/ entry is expected).

  • 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.