Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Page List: Create a JS version for the editor #31670

Merged
merged 16 commits into from
Oct 25, 2021
Merged
Show file tree
Hide file tree
Changes from 11 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 0 additions & 33 deletions packages/block-library/src/page-list/block.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,39 +7,6 @@
"keywords": [ "menu", "navigation" ],
"textdomain": "default",
"attributes": {
"textColor": {
"type": "string"
},
"customTextColor": {
"type": "string"
},
"backgroundColor": {
"type": "string"
},
"customBackgroundColor": {
"type": "string"
},
"overlayBackgroundColor": {
"type": "string"
},
"customOverlayBackgroundColor": {
"type": "string"
},
"overlayTextColor": {
"type": "string"
},
"customOverlayTextColor": {
"type": "string"
},
"isNavigationChild": {
"type": "boolean"
},
"showSubmenuIcon": {
"type": "boolean"
},
"openSubmenusOnClick" : {
"type": "boolean"
}
},
"usesContext": [
"textColor",
Expand Down
266 changes: 155 additions & 111 deletions packages/block-library/src/page-list/edit.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,138 +2,58 @@
* External dependencies
*/
import classnames from 'classnames';
import { sortBy } from 'lodash';

/**
* WordPress dependencies
*/
import {
BlockControls,
useBlockProps,
store as blockEditorStore,
getColorClassName,
} from '@wordpress/block-editor';
import ServerSideRender from '@wordpress/server-side-render';
import { ToolbarButton } from '@wordpress/components';
import { __ } from '@wordpress/i18n';
import { useEffect, useState } from '@wordpress/element';
import { useSelect } from '@wordpress/data';
import apiFetch from '@wordpress/api-fetch';
import { addQueryArgs } from '@wordpress/url';

/**
* Internal dependencies
*/
import ConvertToLinksModal from './convert-to-links-modal';
import { ItemSubmenuIcon } from '../navigation-link/icons';

// We only show the edit option when page count is <= MAX_PAGE_COUNT
// Performance of Navigation Links is not good past this value.
const MAX_PAGE_COUNT = 100;

export default function PageListEdit( {
context,
clientId,
attributes,
setAttributes,
} ) {
// Copy context to attributes to make it accessible in the editor's
// ServerSideRender
useEffect( () => {
const {
textColor,
customTextColor,
backgroundColor,
customBackgroundColor,
overlayTextColor,
customOverlayTextColor,
overlayBackgroundColor,
customOverlayBackgroundColor,
} = context;
setAttributes( {
textColor,
customTextColor,
backgroundColor,
customBackgroundColor,
overlayTextColor,
customOverlayTextColor,
overlayBackgroundColor,
customOverlayBackgroundColor,
} );
}, [
context.textColor,
context.customTextColor,
context.backgroundColor,
context.customBackgroundColor,
context.overlayTextColor,
context.customOverlayTextColor,
context.overlayBackgroundColor,
context.customOverlayBackgroundColor,
] );

const { textColor, backgroundColor, style } = context || {};

const [ allowConvertToLinks, setAllowConvertToLinks ] = useState( false );

const blockProps = useBlockProps( {
className: classnames( {
'has-text-color': !! textColor,
[ getColorClassName( 'color', textColor ) ]: !! textColor,
'has-background': !! backgroundColor,
[ getColorClassName(
'background-color',
backgroundColor
) ]: !! backgroundColor,
} ),
style: { ...style?.color },
} );

const isParentNavigation = useSelect(
( select ) => {
const { getBlockParentsByBlockName } = select( blockEditorStore );
return (
getBlockParentsByBlockName( clientId, 'core/navigation' )
.length > 0
);
},
[ clientId ]
);

useEffect( () => {
setAttributes( {
isNavigationChild: isParentNavigation,
openSubmenusOnClick: !! context.openSubmenusOnClick,
showSubmenuIcon: !! context.showSubmenuIcon,
} );
}, [ context.openSubmenusOnClick, context.showSubmenuIcon ] );
export default function PageListEdit( { context, clientId } ) {
const { pagesByParentId, totalPages } = usePagesByParentId();

useEffect( () => {
if ( isParentNavigation ) {
apiFetch( {
path: addQueryArgs( '/wp/v2/pages', {
per_page: 1,
_fields: [ 'id' ],
} ),
parse: false,
} ).then( ( res ) => {
setAllowConvertToLinks(
res.headers.get( 'X-WP-Total' ) <= MAX_PAGE_COUNT
);
} );
} else {
setAllowConvertToLinks( false );
}
}, [ isParentNavigation ] );
const isNavigationChild = 'showSubmenuIcon' in context;
const allowConvertToLinks =
isNavigationChild && totalPages <= MAX_PAGE_COUNT;

const [ isOpen, setOpen ] = useState( false );
const openModal = () => setOpen( true );
const closeModal = () => setOpen( false );

// Update parent status before component first renders.
const attributesWithParentStatus = {
...attributes,
isNavigationChild: isParentNavigation,
openSubmenusOnClick: !! context.openSubmenusOnClick,
showSubmenuIcon: !! context.showSubmenuIcon,
};
const blockProps = useBlockProps( {
className: classnames( 'wp-block-page-list', {
'has-text-color': !! context.textColor,
[ getColorClassName(
'color',
context.textColor
) ]: !! context.textColor,
'has-background': !! context.backgroundColor,
[ getColorClassName(
'background-color',
context.backgroundColor
) ]: !! context.backgroundColor,
} ),
style: { ...context.style?.color },
} );

return (
<>
Expand All @@ -150,15 +70,139 @@ export default function PageListEdit( {
clientId={ clientId }
/>
) }
<div { ...blockProps }>
<ServerSideRender
block="core/page-list"
attributes={ attributesWithParentStatus }
EmptyResponsePlaceholder={ () => (
<span>{ __( 'Page List: No pages to show.' ) }</span>
) }
/>
</div>
{ totalPages > 0 ? (
<ul { ...blockProps }>
<PageItems
context={ context }
pagesByParentId={ pagesByParentId }
/>
</ul>
) : (
<div { ...blockProps }>
<span>{ __( 'Page List: No pages to show.' ) }</span>
</div>
) }
</>
);
}

function usePagesByParentId() {
const [ pagesByParentId, setPagesByParentId ] = useState( new Map() );
const [ totalPages, setTotalPages ] = useState( 0 );

useEffect( () => {
async function performFetch() {
let pages = await apiFetch( {
path: addQueryArgs( '/wp/v2/pages', {
orderby: 'menu_order',
order: 'asc',
_fields: [ 'id', 'link', 'parent', 'title', 'menu_order' ],
per_page: -1,
} ),
} );

// TODO: Once the REST API supports passing multiple values to
// 'orderby', this an be removed.
noisysocks marked this conversation as resolved.
Show resolved Hide resolved
// https://core.trac.wordpress.org/ticket/39037
pages = sortBy( pages, [ 'menu_order', 'title.rendered' ] );

setPagesByParentId(
pages.reduce( ( accumulator, page ) => {
const { parent } = page;
if ( accumulator.has( parent ) ) {
accumulator.get( parent ).push( page );
} else {
accumulator.set( parent, [ page ] );
}
return accumulator;
}, new Map() )
);
setTotalPages( pages.length );
}
performFetch();
}, [] );

return {
pagesByParentId,
totalPages,
};
}

function PageItems( { context, pagesByParentId, parentId = 0, depth = 0 } ) {
const pages = pagesByParentId.get( parentId );

if ( ! pages?.length ) {
return [];
}

return pages.map( ( page ) => {
const hasChildren = pagesByParentId.has( page.id );
const isNavigationChild = 'showSubmenuIcon' in context;
return (
<li
key={ page.id }
className={ classnames( 'wp-block-pages-list__item', {
'has-child': hasChildren,
'wp-block-navigation-item': isNavigationChild,
'open-on-click':
isNavigationChild && context.openSubmenusOnClick,
noisysocks marked this conversation as resolved.
Show resolved Hide resolved
'open-on-hover-click':
isNavigationChild &&
! context.openSubmenusOnClick &&
context.showSubmenuIcon,
} ) }
>
{ hasChildren &&
isNavigationChild &&
context.openSubmenusOnClick ? (
<ItemSubmenuToggle title={ page.title?.rendered } />
) : (
<a
className={ classnames(
'wp-block-pages-list__item__link',
{
'wp-block-navigation-item__content': isNavigationChild,
}
) }
href={ page.link }
>
{ page.title?.rendered }
</a>
) }
{ hasChildren && (
<>
{ isNavigationChild &&
! context.openSubmenusOnClick &&
context.showSubmenuIcon && <ItemSubmenuToggle /> }
<ul
className={ classnames( 'submenu-container', {
'wp-block-navigation__submenu-container': isNavigationChild,
} ) }
>
<PageItems
context={ context }
pagesByParentId={ pagesByParentId }
parentId={ page.id }
depth={ depth + 1 }
/>
</ul>
</>
) }
</li>
);
} );
}

function ItemSubmenuToggle( { title } ) {
return (
<button
className="wp-block-navigation-item__content wp-block-navigation-submenu__toggle"
aria-expanded="false"
>
{ title }
<span className="wp-block-page-list__submenu-icon wp-block-navigation__submenu-icon">
<ItemSubmenuIcon />
</span>
</button>
);
}
8 changes: 1 addition & 7 deletions packages/block-library/src/page-list/index.php
Original file line number Diff line number Diff line change
Expand Up @@ -238,20 +238,14 @@ function render_block_core_page_list( $attributes, $content, $block ) {
static $block_id = 0;
$block_id++;

// TODO: When https://core.trac.wordpress.org/ticket/39037 REST API support for multiple orderby values is resolved,
// update 'sort_column' to 'menu_order, post_title'. Sorting by both menu_order and post_title ensures a stable sort.
// Otherwise with pages that have the same menu_order value, we can see different ordering depending on how DB
// queries are constructed internally. For example we might see a different order when a limit is set to <499
// versus >= 500.
$all_pages = get_pages(
array(
'sort_column' => 'menu_order',
'sort_column' => 'menu_order,post_title',
noisysocks marked this conversation as resolved.
Show resolved Hide resolved
'order' => 'asc',
)
);

// If thare are no pages, there is nothing to show.
// Return early and empty to trigger EmptyResponsePlaceholder.
if ( empty( $all_pages ) ) {
return;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ exports[`Navigation Creating from existing Menus creates an empty navigation blo

exports[`Navigation Creating from existing Pages allows a navigation block to be created using existing pages 1`] = `
"<!-- wp:navigation -->
<!-- wp:page-list {\\"isNavigationChild\\":true,\\"showSubmenuIcon\\":true,\\"openSubmenusOnClick\\":false} /-->
noisysocks marked this conversation as resolved.
Show resolved Hide resolved
<!-- wp:page-list /-->
<!-- /wp:navigation -->"
`;

Expand Down