Skip to content

Commit

Permalink
Fix blocks detection
Browse files Browse the repository at this point in the history
  • Loading branch information
kevin940726 committed Nov 2, 2022
1 parent 1418655 commit 9b203f0
Showing 1 changed file with 22 additions and 3 deletions.
25 changes: 22 additions & 3 deletions packages/block-editor/src/components/use-paste-styles/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
* WordPress dependencies
*/
import { useCallback } from '@wordpress/element';
import { getBlockType, serialize, parse } from '@wordpress/blocks';
import { getBlockType, parse } from '@wordpress/blocks';
import { useDispatch, useRegistry } from '@wordpress/data';
import { store as noticesStore } from '@wordpress/notices';
import { __, sprintf } from '@wordpress/i18n';
Expand All @@ -12,6 +12,24 @@ import { __, sprintf } from '@wordpress/i18n';
*/
import { store as blockEditorStore } from '../../store';

function looksLikeBlocks( text ) {
try {
const blocks = parse( text, {
__unstableSkipMigrationLogs: true,
__unstableSkipAutop: true,
} );
if ( blocks.length === 1 && blocks[ 0 ].name === 'core/freeform' ) {
// It's likely that the text is just plain text and not serialized blocks.
return false;
}
return true;
} catch ( err ) {
// Parsing error, the text is not serialized blocks.
// (Even though that it technically won't happen)
return false;
}
}

function getStyleAttributes( block ) {
const blockType = getBlockType( block.name );
const attributes = {};
Expand Down Expand Up @@ -77,9 +95,8 @@ export default function usePasteStyles() {
return;
}

const copiedBlocks = parse( html );
// Abort if the copied text is empty or doesn't look like serialized blocks.
if ( ! html || serialize( copiedBlocks ) !== html ) {
if ( ! html || ! looksLikeBlocks( html ) ) {
createWarningNotice(
__( "The copied data doesn't appear to be blocks." ),
{
Expand All @@ -89,6 +106,8 @@ export default function usePasteStyles() {
return;
}

const copiedBlocks = parse( html );

if ( copiedBlocks.length === 1 ) {
// Apply styles of the block to all the target blocks.
registry.batch( () => {
Expand Down

0 comments on commit 9b203f0

Please sign in to comment.