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

Parsing patterns when idling (performance follow-up for inserting patterns into containers) #29444

Merged
merged 19 commits into from
Mar 24, 2021
Merged
Show file tree
Hide file tree
Changes from 13 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
20 changes: 20 additions & 0 deletions lib/block-patterns.php
Original file line number Diff line number Diff line change
Expand Up @@ -62,3 +62,23 @@
<!-- /wp:columns -->',
)
);

for ( $i = 0; $i < 1000; $i++ ) {
Copy link
Member Author

Choose a reason for hiding this comment

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

For demonstration purposes only. I'll remove this once the PR is approved.

Copy link
Contributor

Choose a reason for hiding this comment

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

Can we remove that code, in order to get accurate numbers in the job and judge whether the PR allows us to get the previous loading numbers?

register_block_pattern(
'query/small-posts' . $i,
array(
'title' => __( 'Small' . $i, 'gutenberg' ),
'scope' => array(
'inserter' => true
),
'content' => '<!-- wp:columns {"verticalAlignment":"center"} -->
<div class="wp-block-columns are-vertically-aligned-center"><!-- wp:column {"verticalAlignment":"center","width":"25%"} -->
<div class="wp-block-column is-vertically-aligned-center" style="flex-basis:25%"><!-- wp:post-featured-image {"isLink":true} /--></div>
<!-- /wp:column -->
<!-- wp:column {"verticalAlignment":"center","width":"75%"} -->
<div class="wp-block-column is-vertically-aligned-center" style="flex-basis:75%"><!-- wp:post-title {"isLink":true} /--></div>
<!-- /wp:column --></div>
<!-- /wp:columns -->',
)
);
}
2 changes: 2 additions & 0 deletions packages/block-editor/src/components/block-list/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import useInsertionPoint from './insertion-point';
import BlockPopover from './block-popover';
import { store as blockEditorStore } from '../../store';
import { useScrollSelectionIntoView } from '../selection-scroll-into-view';
import { usePreParsePatterns } from '../../utils/pre-parse-patterns';

export const BlockNodes = createContext();
export const SetBlockNodes = createContext();
Expand All @@ -28,6 +29,7 @@ export default function BlockList( { className } ) {
const [ blockNodes, setBlockNodes ] = useState( {} );
const insertionPoint = useInsertionPoint( ref );
useScrollSelectionIntoView( ref );
usePreParsePatterns();

return (
<BlockNodes.Provider value={ blockNodes }>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
/**
* WordPress dependencies
*/
import { useMemo } from '@wordpress/element';
import { parse } from '@wordpress/blocks';
import {
VisuallyHidden,
__unstableComposite as Composite,
Expand All @@ -11,16 +9,22 @@ import {
} from '@wordpress/components';
import { useInstanceId } from '@wordpress/compose';
import { __ } from '@wordpress/i18n';
import { useSelect } from '@wordpress/data';

/**
* Internal dependencies
*/
import BlockPreview from '../block-preview';
import InserterDraggableBlocks from '../inserter-draggable-blocks';
import { store as blockEditorStore } from '../../store';

function BlockPattern( { isDraggable, pattern, onClick, composite } ) {
const { content, viewportWidth } = pattern;
const blocks = useMemo( () => parse( content ), [ content ] );
const { name, viewportWidth } = pattern;
const { blocks } = useSelect(
( select ) =>
select( blockEditorStore ).__experimentalGetParsedPattern( name ),
[ name ]
);
const instanceId = useInstanceId( BlockPattern );
const descriptionId = `block-editor-block-patterns-list__item-description-${ instanceId }`;

Expand Down
30 changes: 18 additions & 12 deletions packages/block-editor/src/store/selectors.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@ import {
filter,
mapKeys,
orderBy,
every,
} from 'lodash';
import createSelector from 'rememo';

Expand Down Expand Up @@ -1757,13 +1756,18 @@ export const __experimentalGetAllowedBlocks = createSelector(
]
);

const __experimentalGetParsedPatterns = createSelector(
( state ) => {
export const __experimentalGetParsedPattern = createSelector(
( state, patternName ) => {
const patterns = state.settings.__experimentalBlockPatterns;
return map( patterns, ( pattern ) => ( {
const pattern = patterns.find( ( { name } ) => name === patternName );
Copy link
Contributor

Choose a reason for hiding this comment

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

You already have the pattern from __experimentalGetAllowedPatterns. No need to get state.settings.__experimentalBlockPatterns again and filter. Am I missing something?

Copy link
Member Author

Choose a reason for hiding this comment

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

The goal is to have a selector function that can be memoized easily. The pattern name as parameter is immutable. If we used the pattern object then it might happen that we provide a modified/reconstructed pattern object that has a different reference.

if ( ! pattern ) {
return null;
}

return {
...pattern,
contentBlocks: parse( pattern.content ),
} ) );
blocks: parse( pattern.content ),
};
},
( state ) => [ state.settings.__experimentalBlockPatterns ]
);
Expand All @@ -1778,17 +1782,19 @@ const __experimentalGetParsedPatterns = createSelector(
*/
export const __experimentalGetAllowedPatterns = createSelector(
( state, rootClientId = null ) => {
const patterns = __experimentalGetParsedPatterns( state );

const patterns = state.settings.__experimentalBlockPatterns;
if ( ! rootClientId ) {
return patterns;
}

const patternsAllowed = filter( patterns, ( { contentBlocks } ) => {
return every( contentBlocks, ( { name } ) =>
const parsedPatterns = patterns.map( ( { name } ) =>
__experimentalGetParsedPattern( state, name )
);
const patternsAllowed = filter( parsedPatterns, ( { blocks } ) =>
blocks.every( ( { name } ) =>
canInsertBlockType( state, name, rootClientId )
);
} );
)
);

return patternsAllowed;
},
Expand Down
4 changes: 4 additions & 0 deletions packages/block-editor/src/store/test/selectors.js
Original file line number Diff line number Diff line change
Expand Up @@ -3375,10 +3375,12 @@ describe( 'selectors', () => {
settings: {
__experimentalBlockPatterns: [
{
name: 'pattern-a',
title: 'pattern with a',
content: `<!-- wp:test-block-a --><!-- /wp:test-block-a -->`,
},
{
name: 'pattern-b',
title: 'pattern with b',
content:
'<!-- wp:test-block-b --><!-- /wp:test-block-b -->',
Expand Down Expand Up @@ -3409,10 +3411,12 @@ describe( 'selectors', () => {
settings: {
__experimentalBlockPatterns: [
{
name: 'pattern-a',
title: 'pattern a',
scope: { block: [ 'test/block-a' ] },
},
{
name: 'pattern-b',
title: 'pattern b',
scope: { block: [ 'test/block-b' ] },
},
Expand Down
72 changes: 72 additions & 0 deletions packages/block-editor/src/utils/pre-parse-patterns.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
/**
* WordPress dependencies
*/
import { useSelect, select } from '@wordpress/data';
import { useEffect } from '@wordpress/element';

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

const requestIdleCallback = ( () => {
if ( typeof window === 'undefined' ) {
return ( callback ) => {
setTimeout( () => callback( Date.now() ), 0 );
};
}

return window.requestIdleCallback || window.requestAnimationFrame;
} )();

const cancelIdleCallback = ( () => {
if ( typeof window === 'undefined' ) {
return clearTimeout;
}

return window.cancelIdleCallback || window.cancelAnimationFrame;
} )();

export function usePreParsePatterns() {
const patterns =
useSelect(
( _select ) =>
_select( blockEditorStore ).getSettings()
.__experimentalBlockPatterns,
[]
) || [];

useEffect( () => {
if ( ! patterns?.length ) {
return;
}

let handle;
let index = -1;

const callback = () => {
index++;
if ( index >= patterns.length ) {
return;
}

const marker = `[usePreParsePatterns] process ${ index } ${ patterns[ index ]?.name }`;
window.console.time( marker );
select( blockEditorStore ).__experimentalGetParsedPattern(
patterns[ index ].name,
index
Copy link
Contributor

Choose a reason for hiding this comment

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

Is this second argument correct?

Copy link
Member Author

Choose a reason for hiding this comment

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

No, that's not needed anymore. Thanks!

);
window.console.timeEnd( marker );

handle = requestIdleCallback( callback );
};

window.console.time( '[usePreParsePatterns] initiate' );
window.console.timeEnd( '[usePreParsePatterns] initiate' );

handle = requestIdleCallback( callback );
return () => cancelIdleCallback( handle );
}, patterns );
youknowriad marked this conversation as resolved.
Show resolved Hide resolved

return null;
}
4 changes: 0 additions & 4 deletions packages/edit-post/src/editor.js
Original file line number Diff line number Diff line change
Expand Up @@ -82,10 +82,6 @@ function Editor( {
const isFSETheme = getEditorSettings().isFSETheme;
const isViewable = getPostType( postType )?.viewable ?? false;

// Prefetch and parse patterns. This ensures patterns are loaded and parsed when
// the editor is loaded rather than degrading the performance of the inserter.
select( 'core/block-editor' ).__experimentalGetAllowedPatterns();

return {
hasFixedToolbar:
isFeatureActive( 'fixedToolbar' ) ||
Expand Down
4 changes: 0 additions & 4 deletions packages/edit-site/src/components/editor/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -67,10 +67,6 @@ function Editor( { initialSettings } ) {
const postType = getEditedPostType();
const postId = getEditedPostId();

// Prefetch and parse patterns. This ensures patterns are loaded and parsed when
// the editor is loaded rather than degrading the performance of the inserter.
select( 'core/block-editor' ).__experimentalGetAllowedPatterns();

// The currently selected entity to display. Typically template or template part.
return {
isInserterOpen: isInserterOpened(),
Expand Down