Skip to content
33 changes: 30 additions & 3 deletions packages/core-data/src/utils/crdt.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,10 @@ import fastDeepEqual from 'fast-deep-equal/es6/index.js';
/**
* WordPress dependencies
*/
import { __unstableSerializeAndClean } from '@wordpress/blocks';
import {
__unstableSerializeAndClean,
type Block as WPBlock,
} from '@wordpress/blocks';
import {
type CRDTDoc,
type ObjectData,
Expand Down Expand Up @@ -46,10 +49,16 @@ import {
type YMapWrap,
} from './crdt-utils';

// A function that derives content from blocks. Two callers produce this:
// `useEntityBlockEditor` reads blocks from its argument (so the optional arg
// lets it accept whatever caller is invoked with), and the receiver-side
// injection in this file captures blocks in a closure and ignores the arg.
type ContentFromBlocksFn = ( args?: { blocks: Block[] } ) => string;

// Changes that can be applied to a post entity record.
export type PostChanges = Partial< Post > & {
blocks?: Block[];
content?: Post[ 'content' ] | string;
content?: Post[ 'content' ] | string | ContentFromBlocksFn;
excerpt?: Post[ 'excerpt' ] | string;
selection?: WPSelection;
title?: Post[ 'title' ] | string;
Expand Down Expand Up @@ -138,7 +147,10 @@ export function applyPostChangesToCRDTDoc(

const newValue = changes[ key ];

// Cannot serialize function values, so cannot sync them.
// Cannot serialize function values, so cannot sync them. `content` is
// often passed as a lazy serializer by `useEntityBlockEditor`; the
// receiver re-derives it from the synced blocks (see
// getPostChangesFromCRDTDoc), so dropping it here is intentional.
if ( 'function' === typeof newValue ) {
return;
}
Expand Down Expand Up @@ -431,6 +443,21 @@ export function getPostChangesFromCRDTDoc(
);
}

// When blocks changed but content didn't (the sender internally used a lazy
// serializer function), inject a closure that captures the synced blocks
// and serializes them on demand. Mirrors what useEntityBlockEditor does
// locally. A fresh function on every persistent edit marks the entity
// dirty (so the save button reactivates for peers), while serialization
// stays lazy (only runs when getEditedPostContent reads it). The closure
// captures `capturedBlocks` so the right content is returned even if the
// caller later clears `record.blocks` (e.g. the Code Editor re-parsing
// from content).
if ( changes.blocks && ! changes.content ) {
const capturedBlocks = changes.blocks;
changes.content = () =>
__unstableSerializeAndClean( capturedBlocks as WPBlock[] );
}

// Meta changes must be merged with the edited record since not all meta
// properties are synced.
if ( 'object' === typeof changes.meta ) {
Expand Down
124 changes: 123 additions & 1 deletion packages/core-data/src/utils/test/crdt.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,9 @@ import { describe, expect, it, jest, beforeEach } from '@jest/globals';

/**
* Mock getBlockTypes so CRDT merging can identify rich-text attributes.
* Also stub __unstableSerializeAndClean so we can assert how it's invoked
* (the real implementation returns "" without registered block types, which
* isn't useful for asserting closure-capture behavior).
*/
jest.mock( '@wordpress/blocks', () => {
const actual = jest.requireActual( '@wordpress/blocks' ) as Record<
Expand Down Expand Up @@ -43,6 +46,9 @@ jest.mock( '@wordpress/blocks', () => {
},
},
],
__unstableSerializeAndClean: jest.fn(
( blocks: unknown[] ) => `serialized:${ blocks?.length ?? 0 }`
),
};
} );

Expand All @@ -63,7 +69,7 @@ import {
type PostChanges,
type YPostRecord,
} from '../crdt';
import type { YBlock, YBlockRecord, YBlocks } from '../crdt-blocks';
import type { Block, YBlock, YBlockRecord, YBlocks } from '../crdt-blocks';
import { updateSelectionHistory } from '../crdt-selection';
import { createYMap, getRootMap, type YMapWrap } from '../crdt-utils';
import type { Post } from '../../entity-types';
Expand Down Expand Up @@ -126,9 +132,12 @@ describe( 'crdt', () => {
beforeEach( () => {
doc = new Y.Doc();
jest.clearAllMocks();
jest.useFakeTimers();
} );

afterEach( () => {
jest.runAllTimers();
jest.useRealTimers();
doc.destroy();
} );

Expand Down Expand Up @@ -439,6 +448,23 @@ describe( 'crdt', () => {
expect( metaMap?.get( 'custom_field' ) ).toBe( 'value' );
} );

it( 'skips function-valued content in changes', () => {
const changes = {
content: ( {
blocks: blocksForSerialization = [],
}: {
blocks: Block[];
} ) =>
blocksForSerialization
.map( ( b ) => b.attributes.content )
.join( '' ),
} as unknown as PostChanges;

applyPostChangesToCRDTDoc( doc, changes, defaultSyncedProperties );

expect( map.has( 'content' ) ).toBe( false );
} );

it( 'syncs taxonomy rest_base values included in syncedProperties', () => {
const changes = {
categories: [ 1, 2, 3 ],
Expand Down Expand Up @@ -958,6 +984,102 @@ describe( 'crdt', () => {
expect( changes.selection ).toBeUndefined();
} );
} );

it( 'injects a closure-based content function when blocks changed but content did not', () => {
addBlockToDoc( map, 'block-1', 'Hello world' );

const editedRecord = {
title: 'CRDT Title',
status: 'draft',
content: { raw: 'Same content', rendered: 'Same content' },
blocks: [],
} as unknown as Post;

const changes = getPostChangesFromCRDTDoc(
doc,
editedRecord,
defaultSyncedProperties
);

// Blocks changed, content didn't, so a lazy content function is injected.
expect( changes.blocks ).toBeDefined();
expect( typeof changes.content ).toBe( 'function' );
} );

it( 'injected content function captures the synced blocks and ignores its caller-supplied argument', () => {
addBlockToDoc( map, 'block-1', 'Hello world' );

const editedRecord = {
title: 'CRDT Title',
status: 'draft',
content: { raw: 'Same content', rendered: 'Same content' },
blocks: [],
} as unknown as Post;

const changes = getPostChangesFromCRDTDoc(
doc,
editedRecord,
defaultSyncedProperties
);

// The injected function takes no parameters and serializes the
// captured (synced) blocks. This is what makes getEditedPostContent
// keep working after the Code Editor clears `record.blocks` to force
// a re-parse: the closure already has the right blocks on hand.
//
// The mocked __unstableSerializeAndClean returns "serialized:<n>"
// where n is the length of the blocks it was called with. The
// captured blocks have one entry, so both calls below should yield
// "serialized:1" (proving the closure ignores its argument and
// uses the captured blocks instead).
const contentFn = changes.content as ( args?: {
blocks: Block[];
} ) => string;
expect( contentFn() ).toBe( 'serialized:1' );
expect( contentFn( { blocks: [] } ) ).toBe( 'serialized:1' );
} );

it( 'does not inject a content function when content also changed in the doc', () => {
addBlockToDoc( map, 'block-1', 'Hello world' );
map.set( 'content', new Y.Text( 'New content' ) );

const editedRecord = {
title: 'CRDT Title',
status: 'draft',
content: { raw: 'Old content', rendered: 'Old content' },
blocks: [],
} as unknown as Post;

const changes = getPostChangesFromCRDTDoc(
doc,
editedRecord,
defaultSyncedProperties
);

// Content changed directly, so it should be a string, not a function.
expect( changes.blocks ).toBeDefined();
expect( typeof changes.content ).toBe( 'string' );
expect( changes.content ).toBe( 'New content' );
} );

it( 'does not inject a content function when blocks did not change', () => {
map.set( 'content', new Y.Text( 'Same content' ) );

const editedRecord = {
title: 'CRDT Title',
status: 'draft',
content: { raw: 'Same content', rendered: 'Same content' },
} as unknown as Post;

const changes = getPostChangesFromCRDTDoc(
doc,
editedRecord,
defaultSyncedProperties
);

expect( changes.blocks ).toBeUndefined();
expect( changes.content ).toBeUndefined();
} );
} );
} );

Expand Down
110 changes: 110 additions & 0 deletions test/e2e/specs/editor/collaboration/collaboration-undo-redo.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -193,6 +193,116 @@ test.describe( 'Collaboration - Undo/Redo', () => {
] );
} );

test( 'Content in CRDT doc stays in sync when blocks are cleared', async ( {
collaborationUtils,
requestUtils,
editor,
} ) => {
const post = await requestUtils.createPost( {
title: 'Content CRDT Sync Test',
status: 'draft',
date_gmt: new Date().toISOString(),
} );
await collaborationUtils.openCollaborativeSession( post.id );

const { page2, editor2 } = collaborationUtils;

// User A inserts a block. Block insertion triggers onChange
// (a persistent edit) which passes content as a function.
await editor.insertBlock( {
name: 'core/paragraph',
attributes: { content: 'Important work' },
} );

// Wait for User B to see the block.
await expect
.poll( () => editor2.getBlocks(), { timeout: 5000 } )
.toMatchObject( [
{
name: 'core/paragraph',
attributes: { content: 'Important work' },
},
] );

// Clear blocks on User B via editEntityRecord, simulating what
// the Code Editor does (post-text-editor sets blocks: undefined
// when the user edits HTML directly). The receiver-injected
// content closure captured the synced blocks, so getEditedPostContent
// should still return the right HTML even with blocks cleared.
await page2.evaluate( () => {
const postId = ( window as any ).wp.data
.select( 'core/editor' )
.getCurrentPostId();
( window as any ).wp.data
.dispatch( 'core' )
.editEntityRecord( 'postType', 'post', postId, {
blocks: undefined,
} );
} );

await expect
.poll(
() =>
page2.evaluate( () =>
( window as any ).wp.data
.select( 'core/editor' )
.getEditedPostContent()
),
{ timeout: 5000 }
)
.toContain( 'Important work' );
} );

test( 'Post is marked dirty on both collaborators after User A inserts a block', async ( {
collaborationUtils,
requestUtils,
editor,
} ) => {
const post = await requestUtils.createPost( {
title: 'Dirty State Test',
content:
'<!-- wp:paragraph --><p>Initial</p><!-- /wp:paragraph -->',
status: 'draft',
date_gmt: new Date().toISOString(),
} );
await collaborationUtils.openCollaborativeSession( post.id );

const { page2 } = collaborationUtils;

// Both users should start with a clean (non-dirty) state.
await expect
.poll(
() =>
page2.evaluate( () =>
( window as any ).wp.data
.select( 'core/editor' )
.isEditedPostDirty()
),
{ timeout: 5000 }
)
.toBe( false );

// User A inserts a new block.
await editor.insertBlock( {
name: 'core/paragraph',
attributes: { content: 'New content from A' },
} );

// User B should see the post as dirty after sync, because
// the content field was updated in the CRDT doc.
await expect
.poll(
() =>
page2.evaluate( () =>
( window as any ).wp.data
.select( 'core/editor' )
.isEditedPostDirty()
),
{ timeout: 5000 }
)
.toBe( true );
} );

test( 'Undo restores the post selection when another synced entity is loaded', async ( {
collaborationUtils,
requestUtils,
Expand Down
Loading