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

Off Canvas Navigation Editor: Add Convert To Links Modal #45984

Closed
wants to merge 27 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
27 commits
Select commit Hold shift + click to select a range
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

This file was deleted.

43 changes: 36 additions & 7 deletions packages/block-editor/src/components/off-canvas-editor/block.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,10 @@ import {
__experimentalTreeGridCell as TreeGridCell,
__experimentalTreeGridItem as TreeGridItem,
MenuItem,
Button,
} from '@wordpress/components';
import { useInstanceId } from '@wordpress/compose';
import { moreVertical } from '@wordpress/icons';
import { moreVertical, edit } from '@wordpress/icons';
import {
useState,
useRef,
Expand All @@ -34,12 +35,14 @@ import {
} from '../block-mover/button';
import ListViewBlockContents from './block-contents';
import BlockSettingsDropdown from '../block-settings-menu/block-settings-dropdown';
import BlockEditButton from './block-edit-button';
// import BlockEditButton from './block-edit-button';
import { useListViewContext } from './context';
import { getBlockPositionDescription } from './utils';
import { store as blockEditorStore } from '../../store';
import useBlockDisplayInformation from '../use-block-display-information';
import { useBlockLock } from '../block-lock';
import usePageData from './use-page-data';
import { ConvertToLinksModal } from './convert-to-links-modal';

function ListViewBlock( {
block,
Expand All @@ -60,7 +63,8 @@ function ListViewBlock( {
} ) {
const cellRef = useRef( null );
const [ isHovered, setIsHovered ] = useState( false );
const { clientId, attributes } = block;
const [ convertModalOpen, setConvertModalOpen ] = useState( false );
const { clientId, attributes, name } = block;

const { isLocked, isContentLocked } = useBlockLock( clientId );
const forceSelectionContentLock = useSelect(
Expand Down Expand Up @@ -210,6 +214,22 @@ function ListViewBlock( {
[ clientId, expand, collapse, isExpanded ]
);

// 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;
const { pages, totalPages } = usePageData();

const allowConvertToLinks =
'core/page-list' === name && totalPages <= MAX_PAGE_COUNT;

const blockEditOnClick = () => {
if ( allowConvertToLinks ) {
setConvertModalOpen( ! convertModalOpen );
} else {
selectBlock( clientId );
}
};

let colSpan;
if ( hasRenderedMovers ) {
colSpan = 2;
Expand Down Expand Up @@ -331,12 +351,14 @@ function ListViewBlock( {
!! isSelected || forceSelectionContentLock
}
>
{ ( props ) =>
{ ( { ref, tabIndex } ) =>
isEditable && (
<BlockEditButton
{ ...props }
<Button
icon={ edit }
label={ editAriaLabel }
clientId={ clientId }
ref={ ref }
tabIndex={ tabIndex }
onClick={ blockEditOnClick }
/>
)
}
Expand Down Expand Up @@ -393,6 +415,13 @@ function ListViewBlock( {
</TreeGridCell>
</>
) }
{ convertModalOpen && (
<ConvertToLinksModal
onClose={ () => setConvertModalOpen( false ) }
clientId={ clientId }
pages={ pages }
/>
) }
</ListViewLeaf>
);
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
/**
* WordPress dependencies
*/
import { __ } from '@wordpress/i18n';
import { Button, Modal } from '@wordpress/components';
import { useDispatch } from '@wordpress/data';
import { createBlock as create } from '@wordpress/blocks';

/**
* Internal dependencies
*/
import { store as blockEditorStore } from '../../store';

// copied from packages/block-library/src/page-list/convert-to-links-modal.js
const convertSelectedBlockToNavigationLinks =
( { pages, clientId, replaceBlock, createBlock } ) =>
() => {
if ( ! pages?.length ) {
return;
}

const linkMap = {};
const navigationLinks = [];
pages.forEach( ( { id, title, link: url, type, parent } ) => {
// See if a placeholder exists. This is created if children appear before parents in list.
const innerBlocks = linkMap[ id ]?.innerBlocks ?? [];
linkMap[ id ] = createBlock(
'core/navigation-link',
{
id,
label: title.rendered,
url,
type,
kind: 'post-type',
},
innerBlocks
);

if ( ! parent ) {
navigationLinks.push( linkMap[ id ] );
} else {
if ( ! linkMap[ parent ] ) {
// Use a placeholder if the child appears before parent in list.
linkMap[ parent ] = { innerBlocks: [] };
}
const parentLinkInnerBlocks = linkMap[ parent ].innerBlocks;
parentLinkInnerBlocks.push( linkMap[ id ] );
}
} );

// Transform all links with innerBlocks into Submenus. This can't be done
// sooner because page objects have no information on their children.
const transformSubmenus = ( listOfLinks ) => {
listOfLinks.forEach( ( block, index, listOfLinksArray ) => {
const { attributes, innerBlocks } = block;
if ( innerBlocks.length !== 0 ) {
transformSubmenus( innerBlocks );
const transformedBlock = createBlock(
'core/navigation-submenu',
attributes,
innerBlocks
);
listOfLinksArray[ index ] = transformedBlock;
}
} );
};

transformSubmenus( navigationLinks );

replaceBlock( clientId, navigationLinks );
};

export const ConvertToLinksModal = ( { onClose, clientId, pages } ) => {
const hasPages = !! pages?.length;

const { replaceBlock } = useDispatch( blockEditorStore );

return (
<Modal
closeLabel={ __( 'Close' ) }
onRequestClose={ onClose }
title={ __( 'Customize this menu' ) }
className={ 'wp-block-page-list-modal' }
aria={ { describedby: 'wp-block-page-list-modal__description' } }
>
<p id={ 'wp-block-page-list-modal__description' }>
{ __(
'This menu is automatically kept in sync with pages on your site. You can manage the menu yourself by clicking customize below.'
) }
</p>
<div className="wp-block-page-list-modal-buttons">
<Button variant="tertiary" onClick={ onClose }>
{ __( 'Cancel' ) }
</Button>
<Button
variant="primary"
disabled={ ! hasPages }
onClick={ convertSelectedBlockToNavigationLinks( {
pages,
replaceBlock,
clientId,
createBlock: create,
} ) }
>
{ __( 'Customize' ) }
</Button>
</div>
</Modal>
);
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
/**
* WordPress dependencies
*/
import { useSelect } from '@wordpress/data';
import { useMemo } from '@wordpress/element';

/**
* Internal dependencies
*/
import { store as blockEditorStore } from '../../store';

// copied from packages/block-library/src/page-list/edit.js

export default () => {
// 1. Grab editor settings
// 2. Call the selector when we need it
const { pages } = useSelect( ( select ) => {
const { getSettings } = select( blockEditorStore );

return {
pages: getSettings().__experimentalFetchPageEntities( {
orderby: 'menu_order',
order: 'asc',
_fields: [ 'id', 'link', 'parent', 'title', 'menu_order' ],
per_page: -1,
context: 'view',
} ),
};
}, [] );

return useMemo( () => {
// TODO: Once the REST API supports passing multiple values to
// 'orderby', this can be removed.
// https://core.trac.wordpress.org/ticket/39037
const sortedPages = [ ...( pages ?? [] ) ].sort( ( a, b ) => {
if ( a.menu_order === b.menu_order ) {
return a.title.rendered.localeCompare( b.title.rendered );
}
return a.menu_order - b.menu_order;
} );
const pagesByParentId = sortedPages.reduce( ( accumulator, page ) => {
const { parent } = page;
if ( accumulator.has( parent ) ) {
accumulator.get( parent ).push( page );
} else {
accumulator.set( parent, [ page ] );
}
return accumulator;
}, new Map() );

return {
pages, // necessary for access outside the hook
pagesByParentId,
totalPages: pages?.length ?? null,
};
}, [ pages ] );
};
18 changes: 17 additions & 1 deletion packages/edit-site/src/components/block-editor/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,16 @@ export default function BlockEditor( { setIsInserterOpen } ) {
[ settingsBlockPatternCategories, restBlockPatternCategories ]
);

const { fetchPagesEntities } = useSelect( ( select ) => {
const { getEntityRecords } = select( coreStore );

return {
fetchPagesEntities: ( options = {} ) => {
return getEntityRecords( 'postType', 'page', options );
},
};
}, [] );

const settings = useMemo( () => {
const {
__experimentalAdditionalBlockPatterns,
Expand All @@ -138,8 +148,14 @@ export default function BlockEditor( { setIsInserterOpen } ) {
__unstableFetchMedia: fetchMedia,
__experimentalBlockPatterns: blockPatterns,
__experimentalBlockPatternCategories: blockPatternCategories,
__experimentalFetchPageEntities: fetchPagesEntities,
georgeh marked this conversation as resolved.
Show resolved Hide resolved
};
}, [ storedSettings, blockPatterns, blockPatternCategories ] );
}, [
storedSettings,
blockPatterns,
blockPatternCategories,
fetchPagesEntities,
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do you think there's a chance this might cause a perf problem because fetchPagesEntities is always a new function reference?

I'm hoping the fact that useSelect has [] as deps means it will only run once and thus fetchPagesEntities will remain a consistent reference but if that's not true then it will cause problems as the useMemo will be invalidated for the entire editor settings.

] );

const [ blocks, onInput, onChange ] = useEntityBlockEditor(
'postType',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,16 @@ function useBlockEditorSettings( settings, hasTemplate ) {

const { saveEntityRecord } = useDispatch( coreStore );

const { fetchPagesEntities } = useSelect( ( select ) => {
const { getEntityRecords } = select( coreStore );

return {
fetchPagesEntities: ( options = {} ) => {
return getEntityRecords( 'postType', 'page', options );
},
};
}, [] );

/**
* Creates a Post entity.
* This is utilised by the Link UI to allow for on-the-fly creation of Posts/Pages.
Expand Down Expand Up @@ -176,6 +186,7 @@ function useBlockEditorSettings( settings, hasTemplate ) {
'supportsLayout',
'widgetTypesToHideFromLegacyWidgetBlock',
'__unstableResolvedAssets',
'__experimentalFetchPageEntities',
].includes( key )
)
),
Expand All @@ -196,6 +207,7 @@ function useBlockEditorSettings( settings, hasTemplate ) {
__experimentalUserCanCreatePages: userCanCreatePages,
pageOnFront,
__experimentalPreferPatternsOnRoot: hasTemplate,
__experimentalFetchPageEntities: fetchPagesEntities,
} ),
[
settings,
Expand All @@ -208,6 +220,7 @@ function useBlockEditorSettings( settings, hasTemplate ) {
hasTemplate,
userCanCreatePages,
pageOnFront,
fetchPagesEntities,
]
);
}
Expand Down