Skip to content
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
9 changes: 9 additions & 0 deletions packages/core-data/src/actions.js
Original file line number Diff line number Diff line change
Expand Up @@ -339,6 +339,15 @@ export const deleteEntityRecord =
} );

await dispatch( removeItems( kind, name, recordId, true ) );

if ( globalThis.IS_GUTENBERG_PLUGIN ) {
if ( entityConfig.syncConfig ) {
const objectType = `${ kind }/${ name }`;
const objectId = recordId;

getSyncManager()?.unload( objectType, objectId );
}
}
} catch ( _error ) {
hasError = true;
error = _error;
Expand Down
50 changes: 50 additions & 0 deletions packages/core-data/src/awareness/base-awareness.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
/**
* WordPress dependencies
*/
import { select } from '@wordpress/data';
import { AwarenessState } from '@wordpress/sync';

/**
* Internal dependencies
*/
import { STORE_NAME as coreStore } from '../name';
import { generateUserInfo, areUserInfosEqual } from './utils';

import type { BaseState } from './types';

export abstract class BaseAwarenessState<
State extends BaseState,
> extends AwarenessState< State > {
public setUp(): void {
super.setUp();

this.setCurrentUserInfo();
}

/**
* Set the current user info in the local state.
*/
private setCurrentUserInfo(): void {
const states = this.getStates();
const otherUserColors = Array.from( states.entries() )
.filter(
( [ clientId, state ] ) =>
state.userInfo && clientId !== this.clientID
)
.map( ( [ , state ] ) => state.userInfo.color )
.filter( Boolean );

// Get current user info and set it in local state.
const currentUser = select( coreStore ).getCurrentUser();
const userInfo = generateUserInfo( currentUser, otherUserColors );
this.setLocalStateField( 'userInfo', userInfo );
}
}

export const baseEqualityFieldChecks = {
userInfo: areUserInfosEqual,
};

export class BaseAwareness extends BaseAwarenessState< BaseState > {
protected equalityFieldChecks = baseEqualityFieldChecks;
}
28 changes: 4 additions & 24 deletions packages/core-data/src/awareness/post-editor-awareness.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,19 +2,19 @@
* WordPress dependencies
*/
import { dispatch, select, subscribe } from '@wordpress/data';
import { AwarenessState, type Y } from '@wordpress/sync';
import type { Y } from '@wordpress/sync';
// @ts-ignore No exported types for block editor store selectors.
import { store as blockEditorStore } from '@wordpress/block-editor';

/**
* Internal dependencies
*/
import { BaseAwarenessState, baseEqualityFieldChecks } from './base-awareness';
import {
AWARENESS_CURSOR_UPDATE_THROTTLE_IN_MS,
LOCAL_CURSOR_UPDATE_DEBOUNCE_IN_MS,
} from './config';
import { STORE_NAME as coreStore } from '../name';
import { generateUserInfo, areUserInfosEqual } from './utils';
import {
areSelectionsStatesEqual,
getSelectionState,
Expand All @@ -23,10 +23,10 @@ import {
import type { WPBlockSelection } from '../types';
import type { EditorState, PostEditorState } from './types';

export class PostEditorAwareness extends AwarenessState< PostEditorState > {
export class PostEditorAwareness extends BaseAwarenessState< PostEditorState > {
protected equalityFieldChecks = {
...baseEqualityFieldChecks,
editorState: this.areEditorStatesEqual,
userInfo: areUserInfosEqual,
};

public constructor(
Expand All @@ -41,29 +41,9 @@ export class PostEditorAwareness extends AwarenessState< PostEditorState > {
public setUp(): void {
super.setUp();

this.setCurrentUserInfo();
this.subscribeToUserSelectionChanges();
}

/**
* Set the current user info in the local state.
*/
private setCurrentUserInfo(): void {
const states = this.getStates();
const otherUserColors = Array.from( states.entries() )
.filter(
( [ clientId, state ] ) =>
state.userInfo && clientId !== this.clientID
)
.map( ( [ , state ] ) => state.userInfo.color )
.filter( Boolean );

// Get current user info and set it in local state.
const currentUser = select( coreStore ).getCurrentUser();
const userInfo = generateUserInfo( currentUser, otherUserColors );
this.setLocalStateField( 'userInfo', userInfo );
}

/**
* Subscribe to user selection changes and update the selection state.
*/
Expand Down
20 changes: 18 additions & 2 deletions packages/core-data/src/entities.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import { PostEditorAwareness } from './awareness/post-editor-awareness';
import { getSyncManager } from './sync';
import {
applyPostChangesToCRDTDoc,
defaultSyncConfig,
getPostChangesFromCRDTDoc,
} from './utils/crdt';

Expand Down Expand Up @@ -219,7 +220,16 @@ export const rootEntitiesConfig = [
plural: 'fontCollections',
key: 'slug',
},
];
].map( ( entity ) => {
const syncEnabledRootEntities = new Set( [ 'comment' ] );

if ( globalThis.IS_GUTENBERG_PLUGIN ) {
if ( syncEnabledRootEntities.has( entity.name ) ) {
entity.syncConfig = defaultSyncConfig;
}
}
return entity;
} );

export const deprecatedEntities = {
root: {
Expand Down Expand Up @@ -413,7 +423,7 @@ async function loadTaxonomyEntities() {
} );
return Object.entries( taxonomies ?? {} ).map( ( [ name, taxonomy ] ) => {
const namespace = taxonomy?.rest_namespace ?? 'wp/v2';
return {
const entity = {
kind: 'taxonomy',
baseURL: `/${ namespace }/${ taxonomy.rest_base }`,
baseURLParams: { context: 'edit' },
Expand All @@ -422,6 +432,12 @@ async function loadTaxonomyEntities() {
getTitle: ( record ) => record?.name,
supportsPagination: true,
};

if ( globalThis.IS_GUTENBERG_PLUGIN ) {
entity.syncConfig = defaultSyncConfig;
}

return entity;
} );
}

Expand Down
20 changes: 20 additions & 0 deletions packages/core-data/src/resolvers.js
Original file line number Diff line number Diff line change
Expand Up @@ -462,6 +462,26 @@ export const getEntityRecords =
};
}

if ( globalThis.IS_GUTENBERG_PLUGIN ) {
if ( entityConfig.syncConfig && -1 === query.per_page ) {
const objectType = `${ kind }/${ name }`;
getSyncManager()?.loadCollection(
entityConfig.syncConfig,
objectType,
{
refetchRecords: async () => {
dispatch.receiveEntityRecords(
kind,
name,
await apiFetch( { path, parse: true } ),
query
);
},
}
);
}
}

// If we request fields but the result doesn't contain the fields,
// explicitly set these fields as "undefined"
// that way we consider the query "fulfilled".
Expand Down
25 changes: 22 additions & 3 deletions packages/core-data/src/utils/crdt.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,18 @@ import fastDeepEqual from 'fast-deep-equal/es6/index.js';
*/
// @ts-expect-error No exported types.
import { __unstableSerializeAndClean } from '@wordpress/blocks';
import { type CRDTDoc, type ObjectData, Y } from '@wordpress/sync';
import {
type CRDTDoc,
type ObjectData,
type SyncConfig,
Y,
} from '@wordpress/sync';

/**
* Internal dependencies
*/
import { BaseAwareness } from '../awareness/base-awareness';
import { type BaseState } from '../awareness/types';
import {
mergeCrdtBlocks,
type Block,
Expand Down Expand Up @@ -48,6 +55,7 @@ export type PostChanges = Partial< Post > & {
export interface YPostRecord extends YMapRecord {
author: number;
blocks: YBlocks;
categories: number[];
comment_status: string;
date: string | null;
excerpt: string;
Expand All @@ -67,6 +75,7 @@ export interface YPostRecord extends YMapRecord {
const allowedPostProperties = new Set< string >( [
'author',
'blocks',
'categories',
'comment_status',
'date',
'excerpt',
Expand Down Expand Up @@ -95,7 +104,7 @@ const disallowedPostMetaKeys = new Set< string >( [
* @param {Partial< ObjectData >} changes
* @return {void}
*/
export function defaultApplyChangesToCRDTDoc(
function defaultApplyChangesToCRDTDoc(
ydoc: CRDTDoc,
changes: ObjectData
): void {
Expand Down Expand Up @@ -256,7 +265,7 @@ export function applyPostChangesToCRDTDoc(
}
}

export function defaultGetChangesFromCRDTDoc( crdtDoc: CRDTDoc ): ObjectData {
function defaultGetChangesFromCRDTDoc( crdtDoc: CRDTDoc ): ObjectData {
return getRootMap( crdtDoc, CRDT_RECORD_MAP_KEY ).toJSON();
}

Expand Down Expand Up @@ -396,6 +405,16 @@ export function getPostChangesFromCRDTDoc(
return changes;
}

/**
* This default sync config can be used for entities that are flat maps of
* primitive values and do not require custom logic to merge changes.
*/
export const defaultSyncConfig: SyncConfig< BaseState > = {
applyChangesToCRDTDoc: defaultApplyChangesToCRDTDoc,
createAwareness: ( ydoc: CRDTDoc ) => new BaseAwareness( ydoc ),
getChangesFromCRDTDoc: defaultGetChangesFromCRDTDoc,
};

/**
* Extract the raw string value from a property that may be a string or an object
* with a `raw` property (`RenderedText`).
Expand Down
Loading
Loading