Skip to content

Commit

Permalink
Collab editing: ensure block attributes are serialisable (#57025)
Browse files Browse the repository at this point in the history
  • Loading branch information
ellatrix authored Dec 13, 2023
1 parent 57052f3 commit 1f89b42
Showing 1 changed file with 40 additions and 5 deletions.
45 changes: 40 additions & 5 deletions packages/core-data/src/entities.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import { capitalCase, pascalCase } from 'change-case';
*/
import apiFetch from '@wordpress/api-fetch';
import { __ } from '@wordpress/i18n';
import { RichTextData } from '@wordpress/rich-text';

/**
* Internal dependencies
Expand Down Expand Up @@ -275,6 +276,29 @@ export const prePersistPostType = ( persistedRecord, edits ) => {
return newEdits;
};

const serialisableBlocksCache = new WeakMap();

function makeBlockAttributesSerializable( attributes ) {
const newAttributes = { ...attributes };
for ( const [ key, value ] of Object.entries( attributes ) ) {
if ( value instanceof RichTextData ) {
newAttributes[ key ] = value.valueOf();
}
}
return newAttributes;
}

function makeBlocksSerializable( blocks ) {
return blocks.map( ( block ) => {
const { innerBlocks, attributes, ...rest } = block;
return {
...rest,
attributes: makeBlockAttributesSerializable( attributes ),
innerBlocks: makeBlocksSerializable( innerBlocks ),
};
} );
}

/**
* Returns the list of post type entities.
*
Expand Down Expand Up @@ -317,12 +341,23 @@ async function loadPostTypeEntities() {
},
applyChangesToDoc: ( doc, changes ) => {
const document = doc.getMap( 'document' );

Object.entries( changes ).forEach( ( [ key, value ] ) => {
if (
document.get( key ) !== value &&
typeof value !== 'function'
) {
document.set( key, value );
if ( typeof value !== 'function' ) {
if ( key === 'blocks' ) {
if ( ! serialisableBlocksCache.has( value ) ) {
serialisableBlocksCache.set(
value,
makeBlocksSerializable( value )
);
}

value = serialisableBlocksCache.get( value );
}

if ( document.get( key ) !== value ) {
document.set( key, value );
}
}
} );
},
Expand Down

1 comment on commit 1f89b42

@github-actions
Copy link

Choose a reason for hiding this comment

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

Flaky tests detected in 1f89b42.
Some tests passed with failed attempts. The failures may not be related to this commit but are still reported for visibility. See the documentation for more information.

🔍 Workflow run URL: https://github.com/WordPress/gutenberg/actions/runs/7202051416
📝 Reported issues:

Please sign in to comment.