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

Collab editing: ensure block attributes are serializable #57025

Merged
merged 2 commits into from
Dec 13, 2023
Merged
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
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
Loading