feat: add Related Stories editor controls
This commit is contained in:
6 files changed
+503
No files matched your search
@@ -0,0 +1,12 @@
|
||||
<?php
|
||||
// phpcs:ignoreFile WordPress.Files.FileName.InvalidClassFileName -- WordPress requires the adjacent .asset.php filename.
|
||||
/**
|
||||
* Related Stories editor asset metadata.
|
||||
*
|
||||
* @package CHRNX
|
||||
*/
|
||||
|
||||
return array(
|
||||
'dependencies' => array( 'wp-block-editor', 'wp-blocks', 'wp-components', 'wp-element', 'wp-i18n', 'wp-server-side-render' ),
|
||||
'version' => CHRNX_VERSION,
|
||||
);
|
||||
@@ -0,0 +1,128 @@
|
||||
( function ( factory ) {
|
||||
if ( typeof module === 'object' && module.exports ) {
|
||||
module.exports = factory();
|
||||
} else {
|
||||
factory().initialize( window.wp );
|
||||
}
|
||||
} )( function () {
|
||||
'use strict';
|
||||
|
||||
const attributes = {
|
||||
limit: { type: 'integer', default: 3, enum: [ 3, 5 ] },
|
||||
layout: {
|
||||
type: 'string',
|
||||
default: 'adaptive',
|
||||
enum: [ 'adaptive', 'grid', 'carousel' ],
|
||||
},
|
||||
headingLevel: { type: 'integer', default: 2, enum: [ 2, 3, 4, 5, 6 ] },
|
||||
};
|
||||
const layouts = [ 'adaptive', 'grid', 'carousel' ];
|
||||
|
||||
function hasRequiredGlobals( wp ) {
|
||||
return Boolean(
|
||||
wp &&
|
||||
wp.blocks &&
|
||||
typeof wp.blocks.registerBlockType === 'function' &&
|
||||
wp.blockEditor &&
|
||||
wp.blockEditor.InspectorControls &&
|
||||
wp.components &&
|
||||
wp.components.PanelBody &&
|
||||
wp.components.SelectControl &&
|
||||
wp.element &&
|
||||
typeof wp.element.createElement === 'function' &&
|
||||
wp.element.Fragment &&
|
||||
wp.i18n &&
|
||||
typeof wp.i18n.__ === 'function' &&
|
||||
wp.serverSideRender,
|
||||
);
|
||||
}
|
||||
|
||||
function initialize( wp ) {
|
||||
if ( ! hasRequiredGlobals( wp ) ) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const __ = wp.i18n.__;
|
||||
|
||||
function Edit( props ) {
|
||||
const currentAttributes = props.attributes || {};
|
||||
const setAttributes =
|
||||
typeof props.setAttributes === 'function' ? props.setAttributes : () => {};
|
||||
|
||||
return wp.element.createElement(
|
||||
wp.element.Fragment,
|
||||
null,
|
||||
wp.element.createElement(
|
||||
wp.blockEditor.InspectorControls,
|
||||
null,
|
||||
wp.element.createElement(
|
||||
wp.components.PanelBody,
|
||||
{
|
||||
title: __( 'Related stories settings', 'chrnx' ),
|
||||
initialOpen: true,
|
||||
},
|
||||
wp.element.createElement( wp.components.SelectControl, {
|
||||
label: __( 'Stories to show', 'chrnx' ),
|
||||
value: String( currentAttributes.limit === 5 ? 5 : 3 ),
|
||||
options: [
|
||||
{ label: '3', value: '3' },
|
||||
{ label: '5', value: '5' },
|
||||
],
|
||||
onChange( value ) {
|
||||
setAttributes( {
|
||||
limit: Number( value ) === 5 ? 5 : 3,
|
||||
} );
|
||||
},
|
||||
} ),
|
||||
wp.element.createElement( wp.components.SelectControl, {
|
||||
label: __( 'Layout', 'chrnx' ),
|
||||
value: layouts.includes( currentAttributes.layout )
|
||||
? currentAttributes.layout
|
||||
: 'adaptive',
|
||||
options: [
|
||||
{
|
||||
label: __( 'Adaptive', 'chrnx' ),
|
||||
value: 'adaptive',
|
||||
},
|
||||
{ label: __( 'Grid', 'chrnx' ), value: 'grid' },
|
||||
{
|
||||
label: __( 'Carousel', 'chrnx' ),
|
||||
value: 'carousel',
|
||||
},
|
||||
],
|
||||
help: __(
|
||||
'Adaptive uses a grid on larger screens and horizontal scrolling on smaller screens.',
|
||||
'chrnx',
|
||||
),
|
||||
onChange( value ) {
|
||||
setAttributes( {
|
||||
layout: layouts.includes( value ) ? value : 'adaptive',
|
||||
} );
|
||||
},
|
||||
} ),
|
||||
),
|
||||
),
|
||||
wp.element.createElement( wp.serverSideRender, {
|
||||
block: 'chrnx/related-posts',
|
||||
attributes: currentAttributes,
|
||||
} ),
|
||||
);
|
||||
}
|
||||
|
||||
wp.blocks.registerBlockType( 'chrnx/related-posts', {
|
||||
apiVersion: 3,
|
||||
title: __( 'Related Posts', 'chrnx' ),
|
||||
category: 'theme',
|
||||
description: __( 'Related stories selected by topic, tags, and recency.', 'chrnx' ),
|
||||
attributes,
|
||||
supports: { html: false, align: [ 'wide', 'full' ] },
|
||||
edit: Edit,
|
||||
save() {
|
||||
return null;
|
||||
},
|
||||
} );
|
||||
return true;
|
||||
}
|
||||
|
||||
return { initialize };
|
||||
} );
|
||||
@@ -14,6 +14,7 @@
|
||||
"headingLevel": { "type": "integer", "default": 2, "enum": [2, 3, 4, 5, 6] }
|
||||
},
|
||||
"supports": { "html": false, "align": ["wide", "full"] },
|
||||
"editorScript": "file:../../assets/js/editor-related-posts.js",
|
||||
"style": "file:./style.css",
|
||||
"render": "file:./render.php"
|
||||
}
|
||||
@@ -0,0 +1,141 @@
|
||||
import { expect, test } from '@playwright/test';
|
||||
|
||||
test.describe.configure( { mode: 'serial' } );
|
||||
|
||||
async function logIn( page ) {
|
||||
await page.goto( '/wp-login.php' );
|
||||
await page.locator( '#user_login' ).fill( 'admin' );
|
||||
await page.locator( '#user_pass' ).fill( 'password' );
|
||||
await Promise.all( [
|
||||
page.waitForURL( /\/wp-admin\// ),
|
||||
page.getByRole( 'button', { name: /log in/i } ).click(),
|
||||
] );
|
||||
}
|
||||
|
||||
async function closeWelcomeGuide( page ) {
|
||||
const welcomeDialog = page.getByRole( 'dialog', {
|
||||
name: /^Welcome to the (?:site )?editor$/,
|
||||
} );
|
||||
const isVisible = await welcomeDialog
|
||||
.waitFor( { state: 'visible', timeout: 5000 } )
|
||||
.then( () => true )
|
||||
.catch( () => false );
|
||||
if ( isVisible ) {
|
||||
const close = welcomeDialog.getByRole( 'button', { name: 'Close' } );
|
||||
if ( await close.isVisible() ) {
|
||||
await close.click();
|
||||
} else {
|
||||
await welcomeDialog.getByRole( 'button', { name: 'Get started' } ).click();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function openSettings( page ) {
|
||||
const settings = page.getByRole( 'button', { name: /^settings$/i } ).last();
|
||||
if ( ( await settings.getAttribute( 'aria-expanded' ) ) !== 'true' ) {
|
||||
await settings.click();
|
||||
}
|
||||
}
|
||||
|
||||
test( 'Related Stories is insertable and configurable in the real post editor', async ( {
|
||||
page,
|
||||
} ) => {
|
||||
await logIn( page );
|
||||
await page.goto( '/wp-admin/post-new.php' );
|
||||
await closeWelcomeGuide( page );
|
||||
await expect( page.getByRole( 'heading', { name: 'Add Post', exact: true } ) ).toBeVisible();
|
||||
|
||||
const inserted = await page.evaluate( () => {
|
||||
const type = window.wp.blocks.getBlockType( 'chrnx/related-posts' );
|
||||
if ( ! type ) {
|
||||
return false;
|
||||
}
|
||||
const block = window.wp.blocks.createBlock( 'chrnx/related-posts' );
|
||||
window.wp.data.dispatch( 'core/block-editor' ).insertBlock( block );
|
||||
window.wp.data.dispatch( 'core/block-editor' ).selectBlock( block.clientId );
|
||||
return (
|
||||
window.wp.data.select( 'core/block-editor' ).getSelectedBlockClientId() === block.clientId
|
||||
);
|
||||
} );
|
||||
expect( inserted ).toBe( true );
|
||||
|
||||
await openSettings( page );
|
||||
await expect( page.getByLabel( 'Stories to show', { exact: true } ) ).toBeVisible();
|
||||
await expect( page.getByLabel( 'Layout', { exact: true } ) ).toBeVisible();
|
||||
await expect( page.getByText( 'Related stories settings', { exact: true } ) ).toBeVisible();
|
||||
} );
|
||||
|
||||
test( 'Related Stories persists typed attributes with null saved HTML in the Site Editor', async ( {
|
||||
page,
|
||||
} ) => {
|
||||
await logIn( page );
|
||||
await page.goto(
|
||||
'/wp-admin/site-editor.php?postType=wp_template&postId=chrnx%2F%2Fsingle&canvas=edit',
|
||||
);
|
||||
await closeWelcomeGuide( page );
|
||||
|
||||
await expect
|
||||
.poll( () =>
|
||||
page.evaluate( () => {
|
||||
const editor = window.wp?.data?.select( 'core/block-editor' );
|
||||
return typeof editor?.getBlocks === 'function' && editor.getBlocks().length > 0;
|
||||
} ),
|
||||
)
|
||||
.toBe( true );
|
||||
|
||||
const recovery = page
|
||||
.locator( 'iframe' )
|
||||
.contentFrame()
|
||||
.getByRole( 'button', { name: 'Attempt recovery' } )
|
||||
.first();
|
||||
if ( await recovery.isVisible() ) {
|
||||
await recovery.click();
|
||||
}
|
||||
|
||||
const selected = await page.evaluate( () => {
|
||||
const getNestedBlocks = ( blocks ) =>
|
||||
blocks.flatMap( ( block ) => [ block, ...getNestedBlocks( block.innerBlocks || [] ) ] );
|
||||
const store = window.wp.data.select( 'core/block-editor' );
|
||||
const block = getNestedBlocks( store.getBlocks() ).find(
|
||||
( candidate ) => candidate.name === 'chrnx/related-posts',
|
||||
);
|
||||
if ( ! block ) {
|
||||
return false;
|
||||
}
|
||||
window.wp.data.dispatch( 'core/block-editor' ).selectBlock( block.clientId );
|
||||
return true;
|
||||
} );
|
||||
expect( selected ).toBe( true );
|
||||
|
||||
await openSettings( page );
|
||||
await page.getByLabel( 'Stories to show', { exact: true } ).selectOption( '5' );
|
||||
await page.getByLabel( 'Layout', { exact: true } ).selectOption( 'carousel' );
|
||||
|
||||
const state = await page.evaluate( () => {
|
||||
const getNestedBlocks = ( blocks ) =>
|
||||
blocks.flatMap( ( block ) => [ block, ...getNestedBlocks( block.innerBlocks || [] ) ] );
|
||||
const block = getNestedBlocks( window.wp.data.select( 'core/block-editor' ).getBlocks() ).find(
|
||||
( candidate ) => candidate.name === 'chrnx/related-posts',
|
||||
);
|
||||
return {
|
||||
limit: block.attributes.limit,
|
||||
limitType: typeof block.attributes.limit,
|
||||
layout: block.attributes.layout,
|
||||
editType: typeof window.wp.blocks.getBlockType( block.name )?.edit,
|
||||
selectedClientId: window.wp.data.select( 'core/block-editor' ).getSelectedBlockClientId(),
|
||||
clientId: block.clientId,
|
||||
saveContent: window.wp.blocks.getSaveContent( block.name, block.attributes ),
|
||||
serialized: window.wp.blocks.serialize( block ),
|
||||
};
|
||||
} );
|
||||
|
||||
expect( state.limit ).toBe( 5 );
|
||||
expect( state.limitType ).toBe( 'number' );
|
||||
expect( state.layout ).toBe( 'carousel' );
|
||||
expect( state.editType ).toBe( 'function' );
|
||||
expect( state.selectedClientId ).toBe( state.clientId );
|
||||
expect( state.saveContent ).toBe( '' );
|
||||
expect( state.serialized ).toMatch(
|
||||
/^<!-- wp:chrnx\/related-posts \{"limit":5,"layout":"carousel"\} \/-->$/,
|
||||
);
|
||||
} );
|
||||
@@ -0,0 +1,177 @@
|
||||
const fs = require( 'node:fs' );
|
||||
const path = require( 'node:path' );
|
||||
|
||||
const modulePath = '../../assets/js/editor-related-posts.js';
|
||||
|
||||
function flatten( node ) {
|
||||
if ( ! node || typeof node !== 'object' ) {
|
||||
return [];
|
||||
}
|
||||
return [ node ].concat( ( node.children || [] ).flatMap( flatten ) );
|
||||
}
|
||||
|
||||
function createWp() {
|
||||
const registerBlockType = jest.fn();
|
||||
const wp = {
|
||||
blocks: { registerBlockType },
|
||||
blockEditor: { InspectorControls: 'InspectorControls' },
|
||||
components: { PanelBody: 'PanelBody', SelectControl: 'SelectControl' },
|
||||
element: {
|
||||
createElement: ( type, props, ...children ) => ( {
|
||||
type,
|
||||
props: props || {},
|
||||
children,
|
||||
} ),
|
||||
Fragment: 'Fragment',
|
||||
},
|
||||
i18n: { __: jest.fn( ( text ) => text ) },
|
||||
serverSideRender: 'ServerSideRender',
|
||||
};
|
||||
return { wp, registerBlockType };
|
||||
}
|
||||
|
||||
describe( 'Related Stories editor block', () => {
|
||||
test( 'registers the dynamic block once with exact metadata attributes and null save output', () => {
|
||||
const helpers = require( modulePath );
|
||||
const { wp, registerBlockType } = createWp();
|
||||
const metadata = JSON.parse(
|
||||
fs.readFileSync( path.join( process.cwd(), 'blocks/related-posts/block.json' ), 'utf8' ),
|
||||
);
|
||||
|
||||
expect( helpers.initialize( wp ) ).toBe( true );
|
||||
expect( registerBlockType ).toHaveBeenCalledTimes( 1 );
|
||||
expect( registerBlockType.mock.calls[ 0 ][ 0 ] ).toBe( 'chrnx/related-posts' );
|
||||
expect( registerBlockType.mock.calls[ 0 ][ 1 ].attributes ).toEqual( metadata.attributes );
|
||||
expect( registerBlockType.mock.calls[ 0 ][ 1 ].save() ).toBeNull();
|
||||
} );
|
||||
|
||||
test( 'renders inspector controls beside one server preview', () => {
|
||||
const helpers = require( modulePath );
|
||||
const { wp, registerBlockType } = createWp();
|
||||
helpers.initialize( wp );
|
||||
const settings = registerBlockType.mock.calls[ 0 ][ 1 ];
|
||||
const tree = settings.edit( {
|
||||
attributes: { limit: 3, layout: 'adaptive', headingLevel: 2 },
|
||||
setAttributes: jest.fn(),
|
||||
} );
|
||||
const nodes = flatten( tree );
|
||||
|
||||
expect( nodes.filter( ( node ) => node.type === 'ServerSideRender' ) ).toHaveLength( 1 );
|
||||
expect( nodes.filter( ( node ) => node.type === 'InspectorControls' ) ).toHaveLength( 1 );
|
||||
expect( nodes.filter( ( node ) => node.type === 'SelectControl' ) ).toHaveLength( 2 );
|
||||
expect( nodes.find( ( node ) => node.type === 'ServerSideRender' ).props ).toEqual( {
|
||||
block: 'chrnx/related-posts',
|
||||
attributes: { limit: 3, layout: 'adaptive', headingLevel: 2 },
|
||||
} );
|
||||
} );
|
||||
|
||||
test( 'coerces limit selections to the approved numeric values', () => {
|
||||
const helpers = require( modulePath );
|
||||
const { wp, registerBlockType } = createWp();
|
||||
helpers.initialize( wp );
|
||||
const setAttributes = jest.fn();
|
||||
const tree = registerBlockType.mock.calls[ 0 ][ 1 ].edit( {
|
||||
attributes: { limit: 3, layout: 'adaptive' },
|
||||
setAttributes,
|
||||
} );
|
||||
const limit = flatten( tree ).find(
|
||||
( node ) => node.type === 'SelectControl' && node.props.label === 'Stories to show',
|
||||
);
|
||||
|
||||
limit.props.onChange( '5' );
|
||||
expect( setAttributes ).toHaveBeenLastCalledWith( { limit: 5 } );
|
||||
limit.props.onChange( 5 );
|
||||
expect( setAttributes ).toHaveBeenLastCalledWith( { limit: 5 } );
|
||||
for ( const malformed of [ '3junk', '12', '', null, {}, 5.5 ] ) {
|
||||
limit.props.onChange( malformed );
|
||||
expect( setAttributes ).toHaveBeenLastCalledWith( { limit: 3 } );
|
||||
}
|
||||
} );
|
||||
|
||||
test( 'persists only allowlisted layouts and defaults malformed values to adaptive', () => {
|
||||
const helpers = require( modulePath );
|
||||
const { wp, registerBlockType } = createWp();
|
||||
helpers.initialize( wp );
|
||||
const setAttributes = jest.fn();
|
||||
const tree = registerBlockType.mock.calls[ 0 ][ 1 ].edit( {
|
||||
attributes: { limit: 3, layout: 'adaptive' },
|
||||
setAttributes,
|
||||
} );
|
||||
const layout = flatten( tree ).find(
|
||||
( node ) => node.type === 'SelectControl' && node.props.label === 'Layout',
|
||||
);
|
||||
|
||||
for ( const approved of [ 'adaptive', 'grid', 'carousel' ] ) {
|
||||
layout.props.onChange( approved );
|
||||
expect( setAttributes ).toHaveBeenLastCalledWith( {
|
||||
layout: approved,
|
||||
} );
|
||||
}
|
||||
for ( const malformed of [ 'masonry', 'carousel evil', '', null, 1, [] ] ) {
|
||||
layout.props.onChange( malformed );
|
||||
expect( setAttributes ).toHaveBeenLastCalledWith( {
|
||||
layout: 'adaptive',
|
||||
} );
|
||||
}
|
||||
} );
|
||||
|
||||
test( 'fails closed when WordPress globals or any required dependency are missing', () => {
|
||||
const helpers = require( modulePath );
|
||||
expect( () => helpers.initialize() ).not.toThrow();
|
||||
expect( helpers.initialize() ).toBe( false );
|
||||
expect( helpers.initialize( {} ) ).toBe( false );
|
||||
|
||||
for ( const key of [
|
||||
'blocks',
|
||||
'blockEditor',
|
||||
'components',
|
||||
'element',
|
||||
'i18n',
|
||||
'serverSideRender',
|
||||
] ) {
|
||||
const { wp, registerBlockType } = createWp();
|
||||
delete wp[ key ];
|
||||
expect( () => helpers.initialize( wp ) ).not.toThrow();
|
||||
expect( helpers.initialize( wp ) ).toBe( false );
|
||||
expect( registerBlockType ).not.toHaveBeenCalled();
|
||||
}
|
||||
} );
|
||||
|
||||
test( 'passes every editor UI string through i18n with the chrnx domain', () => {
|
||||
const helpers = require( modulePath );
|
||||
const { wp, registerBlockType } = createWp();
|
||||
wp.i18n.__ = jest.fn( ( text, domain ) => `${ domain }:${ text }` );
|
||||
helpers.initialize( wp );
|
||||
const tree = registerBlockType.mock.calls[ 0 ][ 1 ].edit( {
|
||||
attributes: { limit: 3, layout: 'adaptive' },
|
||||
setAttributes: jest.fn(),
|
||||
} );
|
||||
const nodes = flatten( tree );
|
||||
const controls = nodes.filter( ( node ) => node.type === 'SelectControl' );
|
||||
|
||||
expect( nodes.find( ( node ) => node.type === 'PanelBody' ).props.title ).toBe(
|
||||
'chrnx:Related stories settings',
|
||||
);
|
||||
expect( controls.map( ( control ) => control.props.label ) ).toEqual( [
|
||||
'chrnx:Stories to show',
|
||||
'chrnx:Layout',
|
||||
] );
|
||||
expect( controls[ 1 ].props.help ).toBe(
|
||||
'chrnx:Adaptive uses a grid on larger screens and horizontal scrolling on smaller screens.',
|
||||
);
|
||||
|
||||
const translated = wp.i18n.__.mock.calls.map( ( call ) => call[ 0 ] );
|
||||
expect( translated ).toEqual(
|
||||
expect.arrayContaining( [
|
||||
'Related stories settings',
|
||||
'Stories to show',
|
||||
'Layout',
|
||||
'Adaptive',
|
||||
'Grid',
|
||||
'Carousel',
|
||||
'Adaptive uses a grid on larger screens and horizontal scrolling on smaller screens.',
|
||||
] ),
|
||||
);
|
||||
expect( wp.i18n.__.mock.calls.every( ( call ) => call[ 1 ] === 'chrnx' ) ).toBe( true );
|
||||
} );
|
||||
} );
|
||||
@@ -124,4 +124,48 @@ class EditorAssetsTest extends WP_UnitTestCase {
|
||||
$this->assertFalse( wp_script_is( 'chrnx-editor-podcast', 'enqueued' ) );
|
||||
}
|
||||
}
|
||||
|
||||
/** Related Stories editor metadata registers one local translated script with exact dependencies. */
|
||||
public function test_related_posts_registers_exact_editor_asset_metadata() {
|
||||
do_action( 'init' );
|
||||
$type = WP_Block_Type_Registry::get_instance()->get_registered( 'chrnx/related-posts' );
|
||||
|
||||
$this->assertInstanceOf( WP_Block_Type::class, $type );
|
||||
$this->assertCount( 1, $type->editor_script_handles );
|
||||
$handle = $type->editor_script_handles[0];
|
||||
$this->assertNotEmpty( $handle );
|
||||
|
||||
$manifest_path = get_theme_file_path( 'assets/js/editor-related-posts.asset.php' );
|
||||
$this->assertFileExists( $manifest_path );
|
||||
$manifest = require $manifest_path;
|
||||
$this->assertSame(
|
||||
array( 'wp-block-editor', 'wp-blocks', 'wp-components', 'wp-element', 'wp-i18n', 'wp-server-side-render' ),
|
||||
$manifest['dependencies']
|
||||
);
|
||||
|
||||
$scripts = wp_scripts();
|
||||
$this->assertArrayHasKey( $handle, $scripts->registered );
|
||||
$registered = $scripts->registered[ $handle ];
|
||||
$this->assertSame( get_theme_file_uri( 'assets/js/editor-related-posts.js' ), $registered->src );
|
||||
$this->assertSame( $manifest['dependencies'], $registered->deps );
|
||||
$this->assertSame( CHRNX_VERSION, $registered->ver );
|
||||
$this->assertSame( 'chrnx', $registered->textdomain );
|
||||
}
|
||||
|
||||
/** Related Stories remains metadata-registered on post, Site Editor, and screenless init. */
|
||||
public function test_related_posts_registration_is_not_post_screen_guarded() {
|
||||
foreach ( array( null, 'post', 'site-editor' ) as $screen_id ) {
|
||||
if ( null === $screen_id ) {
|
||||
$GLOBALS['current_screen'] = null;
|
||||
} else {
|
||||
$this->set_screen( $screen_id, true );
|
||||
}
|
||||
do_action( 'init' );
|
||||
$this->assertInstanceOf(
|
||||
WP_Block_Type::class,
|
||||
WP_Block_Type_Registry::get_instance()->get_registered( 'chrnx/related-posts' ),
|
||||
(string) $screen_id
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user