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

Add hook to validate useOnce blocks #5031

Merged
merged 1 commit into from
Feb 24, 2018
Merged
Show file tree
Hide file tree
Changes from all 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
1 change: 1 addition & 0 deletions edit-post/hooks/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,4 @@
* Internal dependencies
*/
import './more-menu';
import './validate-use-once';
123 changes: 123 additions & 0 deletions edit-post/hooks/validate-use-once/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
/**
* External dependencies
*/
import { find } from 'lodash';

/**
* WordPress dependencies
*/
import { createBlock, getBlockType } from '@wordpress/blocks';
import { Button } from '@wordpress/components';
import { withSelect, withDispatch } from '@wordpress/data';
import { Warning } from '@wordpress/editor';
import { compose, getWrapperDisplayName } from '@wordpress/element';
import { addFilter } from '@wordpress/hooks';
import { __ } from '@wordpress/i18n';

const enhance = compose(
/*
* For blocks whose block type defines `useOnce`, provides the wrapped
* component with `originalBlockUid` -- a reference to the first block of
* the same type in the content -- if and only if that "original" block is
* not the current one. Thus, an inexisting `originalBlockUid` prop signals
* that the block is valid.
*
* @param {Component} WrappedBlockEdit A filtered BlockEdit instance.
* @return {Component} Enhanced component with merged state
* data props.
*/
withSelect( ( select, block ) => {
const blocks = select( 'core/editor' ).getBlocks();
const { useOnce } = getBlockType( block.name );

// For block types with no `useOnce` restriction, there is no "original
// block" to be found in the content, as the block itself is valid.
if ( ! useOnce ) {
return {};
}

// Otherwise, only pass `originalBlockUid` if it refers to a different
// block from the current one.
const firstOfSameType = find( blocks, ( { name } ) => block.name === name );
const isInvalid = firstOfSameType && firstOfSameType.uid !== block.id;
Copy link
Member

Choose a reason for hiding this comment

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

Is this actually doing anything? Where is block.id assigned for this? Is this a typo for block.uid?

(Asking as I seek to upgrade all references of uid to clientId)

Copy link
Contributor Author

Choose a reason for hiding this comment

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

It's passed from BlockListBlock to BlockEdit, but it's a synonym of clientId.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

<BlockEdit
name={ blockName }
isSelected={ isSelected }
attributes={ block.attributes }
setAttributes={ this.setAttributes }
insertBlocksAfter={ isLocked ? undefined : this.insertBlocksAfter }
onReplace={ isLocked ? undefined : onReplace }
mergeBlocks={ isLocked ? undefined : this.mergeBlocks }
id={ block.uid }
isSelectionEnabled={ this.props.isSelectionEnabled }
toggleSelection={ this.props.toggleSelection }
/>

Copy link
Member

Choose a reason for hiding this comment

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

Another reason #7990 was desperately needed 😅

return {
originalBlockUid: isInvalid && firstOfSameType.uid,
};
} ),
withDispatch( ( dispatch, { originalBlockUid } ) => ( {
selectFirst: () => dispatch( 'core/editor' ).selectBlock( originalBlockUid ),
} ) ),
);

function withUseOnceValidation( BlockEdit ) {
const WrappedBlockEdit = ( {
originalBlockUid,
selectFirst,
...props
} ) => {
if ( ! originalBlockUid ) {
return <BlockEdit { ...props } />;
}

const blockType = getBlockType( props.name );
const outboundType = getOutboundType( blockType );

return [
<div key="invalid-preview" style={ { minHeight: '100px' } }>
<BlockEdit key="block-edit" { ...props } />
</div>,
<Warning key="use-once-warning">
<p>
<strong>{ blockType.title }: </strong>
{ __( 'This block may not be used more than once.' ) }</p>
<p>
<Button isLarge onClick={
selectFirst
}>{ __( 'Find original' ) }</Button>
<Button isLarge onClick={
() => props.onReplace( [] )
}>{ __( 'Remove' ) }</Button>
{ outboundType &&
<Button isLarge onClick={ () => props.onReplace(
createBlock( outboundType.name, props.attributes )
) }>
{ __( 'Transform into:' ) }{ ' ' }
{ outboundType.title }
</Button>
}
</p>
</Warning>,
];
};

WrappedBlockEdit.displayName = getWrapperDisplayName( BlockEdit, 'useOnceValidation' );

return enhance( WrappedBlockEdit );
}

/**
* Given a base block type, returns the default block type to which to offer
* transforms.
*
* @param {Object} blockType Base block type.
* @return {?Object} The chosen default block type.
*/
function getOutboundType( blockType ) {
// Grab the first outbound transform
const { to = [] } = blockType.transforms || {};
const transform = find( to, ( { type, blocks } ) =>
type === 'block' && blocks.length === 1 // What about when .length > 1?
);

if ( ! transform ) {
return null;
}

return getBlockType( transform.blocks[ 0 ] );
}

addFilter(
'blocks.BlockEdit',
'core/validation/useOnce',
withUseOnceValidation
);