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
19 changes: 19 additions & 0 deletions packages/core-data/src/private-selectors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import { createSelector, createRegistrySelector } from '@wordpress/data';
import { getDefaultTemplateId, getEntityRecord, type State } from './selectors';
import { STORE_NAME } from './name';
import { unlock } from './lock-unlock';
import { getSyncManager } from './sync';
import logEntityDeprecation from './utils/log-entity-deprecation';

type EntityRecordKey = string | number;
Expand All @@ -17,11 +18,29 @@ type EntityRecordKey = string | number;
* Returns the previous edit from the current undo offset
* for the entity records edits history, if any.
*
* Known Issue: Every-time state.undoManager changes, the getUndoManager
* private selector is called (if used within useSelect and things like that)
* which ensures the UI is always properly reactive. But, it's not the case with
* the custom "sync" undo manager.
*
* Assumption: When an undo/redo is created, other parts of the core-data state
* are likely changing simultaneously, which will trigger the selectors again.
*
* This issue is acceptable based on the assumption above.
*
* @see https://github.com/WordPress/gutenberg/pull/72407/files#r2580214235 for more details.
*
* @param state State tree.
*
* @return The undo manager.
*/
export function getUndoManager( state: State ) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

One subtle issue here is that every-time state.undoManager changes, the getUndoManager private selector is called (if used within useSelect and things like that) which ensures the UI is always properly reactive.

But, it's not the case with the custom "sync" undo manager.


Solving that is a bit challenging. one possibility is building a custom @wordpress/data store in the sync package (a store is a function that returns subscribe, getActions, getSelectors) and ensure the listeners (folks that called subscribe) are actually called one new undo/redo actions are triggered. Once you have the store, you could transform getUndoManager to a "registry selector" (createRegistrySelector).

As evidenced by the above, it's a bit involved, so I wonder what you think. Should we try to address it or should we assume that if there's an undo or redo that is created something else in the "state" of core-data is probably changing at the same time (which triggers the selectors again). (Basically accept that the bug exists but is hidden, or hard to reproduce)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Thanks for pointing that out, and for explaining it so well.

Would you know off the top of your head, what could be a rough way to reproduce this bug? I'd be interested to see what the circumstances could be to trigger such a situation. We haven't been able to reproduce any issues in our testing, so maybe there is a workflow that we are missing. It'd be good to consider any such edge cases.

I'd lean towards accepting that the bug exists but is hidden or hard to reproduce. Given we have this as behind an experiment, it won't show up in the vanilla version of Gutenberg which is great. We can see if it comes up in during testing, and address it based on that.

we assume that if there's an undo or redo that is created something else in the "state" of core-data is probably changing at the same time

I think this is the assumption that I'd want to go with as well.

The multidocundomanager would keep track of all the changes in the editor, and so we'd be able to ensure that nothing is amiss.

Hopefully I clarified everything.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

I'd be interested to see what the circumstances could be to trigger such a situation. We haven't been able to reproduce any issues in our testing, so maybe there is a workflow that we are missing. It'd be good to consider any such edge cases.

Right now, it's not really possible to reproduce because any thing that creates an "undo" level also updates something else in the store (like entities data or something) which means the "subscribe" of the core-data store is triggered. But I'm not sure if this is a guarantee or just the current state of things.

Let's say tomorrow, we move "edits" out of the core-data store into the doc exclusively and the bug appears basically.

I'd lean towards accepting that the bug exists but is hidden or hard to reproduce. Given we have this as behind an experiment, it won't show up in the vanilla version of Gutenberg which is great. We can see if it comes up in during testing, and address it based on that.

I'm ok with this, I think we should mention the assumption above in the selector JSDoc to clarify that we're aware of it but we assume that an undo or redo level will always be accompanied by a change to the state.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Definitely understand that. I've updated the private selector with a summary of the issue, the assumption that's being made, and a link to this comment chain.

That should be sufficient for any changes that are needed down the line then.

if ( window.__experimentalEnableSync ) {
if ( globalThis.IS_GUTENBERG_PLUGIN ) {
return getSyncManager()?.undoManager ?? state.undoManager;
}
}

return state.undoManager;
}

Expand Down
5 changes: 3 additions & 2 deletions packages/core-data/src/selectors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import {
getQueriedTotalPages,
} from './queried-data';
import { DEFAULT_ENTITY_KEY } from './entities';
import { getUndoManager } from './private-selectors';
import {
getNormalizedCommaSeparable,
isRawAttribute,
Expand Down Expand Up @@ -1127,7 +1128,7 @@ export function getRedoEdit( state: State ): Optional< any > {
* @return Whether there is a previous edit or not.
*/
export function hasUndo( state: State ): boolean {
return state.undoManager.hasUndo();
return getUndoManager( state ).hasUndo();
}

/**
Expand All @@ -1139,7 +1140,7 @@ export function hasUndo( state: State ): boolean {
* @return Whether there is a next edit or not.
*/
export function hasRedo( state: State ): boolean {
return state.undoManager.hasRedo();
return getUndoManager( state ).hasRedo();
}

/**
Expand Down
6 changes: 6 additions & 0 deletions packages/core-data/src/types.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,9 @@
declare global {
interface Window {
__experimentalEnableSync?: boolean;
}
}

export interface AnyFunction {
( ...args: any[] ): any;
}
Expand Down
5 changes: 5 additions & 0 deletions packages/sync/src/manager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import type {
SyncConfig,
SyncManager,
} from './types';
import { createUndoManager } from './undo-manager';
import { createYjsDoc } from './utils';

interface EntityState {
Expand All @@ -41,6 +42,7 @@ interface EntityState {
*/
export function createSyncManager(): SyncManager {
const entityStates: Map< EntityID, EntityState > = new Map();
const undoManager = createUndoManager();

/**
* Load an entity for syncing and manage its lifecycle.
Expand Down Expand Up @@ -97,6 +99,8 @@ export function createSyncManager(): SyncManager {
void updateEntityRecord( objectType, objectId );
};

undoManager.addToScope( recordMap );

const entityState: EntityState = {
handlers,
objectId,
Expand Down Expand Up @@ -297,6 +301,7 @@ export function createSyncManager(): SyncManager {
return {
createMeta: createEntityMeta,
load: loadEntity,
undoManager,
unload: unloadEntity,
update: updateCRDTDoc,
};
Expand Down
10 changes: 10 additions & 0 deletions packages/sync/src/types.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,8 @@
/**
* WordPress dependencies
*/
import type { UndoManager as WPUndoManager } from '@wordpress/undo-manager';

/**
* External dependencies
*/
Expand Down Expand Up @@ -83,6 +88,7 @@ export interface SyncManager {
record: ObjectData,
handlers: RecordHandlers
) => Promise< void >;
undoManager: SyncUndoManager;
unload: ( objectType: ObjectType, objectId: ObjectID ) => void;
update: (
objectType: ObjectType,
Expand All @@ -91,3 +97,7 @@ export interface SyncManager {
origin: string
) => void;
}

export interface SyncUndoManager extends WPUndoManager< ObjectData > {
addToScope: ( ymap: Y.Map< any > ) => void;
}
110 changes: 110 additions & 0 deletions packages/sync/src/undo-manager.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
/**
* External dependencies
*/
import type * as Y from 'yjs';

/**
* WordPress dependencies
*/
import type { HistoryRecord } from '@wordpress/undo-manager';

/**
* Internal dependencies
*/
import { LOCAL_EDITOR_ORIGIN } from './config';
import { YMultiDocUndoManager } from './y-utilities/y-multidoc-undomanager';
import type { ObjectData, SyncUndoManager } from './types';

/**
* Implementation of the WordPress UndoManager interface using YMultiDocUndoManager
* internally. This allows undo/redo operations to be transacted against multiple
* CRDT documents (one per entity) and giving each peer their own undo/redo stack
* without conflicts.
*/
export function createUndoManager(): SyncUndoManager {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

I wonder if this deserves some unit tests, to check the behavior of undoing/redoing stuff. Seems important.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Agreed, it def is.

I'll be making a follow up PR with that. I wanted to limit the scope of this PR on just the UndoManager changes.

Happy to make it in this PR, if you'd prefer that.

const yUndoManager = new YMultiDocUndoManager( [], {
// Throttle undo/redo captures. (default: 500ms)
captureTimeout: 200,
// Ensure that we only scope the undo/redo to the current editor.
// The yjs document's clientID is added once it's available.
trackedOrigins: new Set( [ LOCAL_EDITOR_ORIGIN ] ),
} );

return {
/**
* Record changes into the history.
* Since Yjs automatically tracks changes, this method translates the WordPress
* HistoryRecord format into Yjs operations.
*
* @param _record A record of changes to record.
* @param _isStaged Whether to immediately create an undo point or not.
*/
addRecord(
_record?: HistoryRecord< ObjectData >,
_isStaged = false // eslint-disable-line @typescript-eslint/no-unused-vars
): void {
// This is a no-op for Yjs since it automatically tracks changes.
// If needed, we could implement custom logic to handle specific records.
},

/**
* Add a Yjs map to the scope of the undo manager.
*
* @param {Y.Map< any >} ymap The Yjs map to add to the scope.
*/
addToScope( ymap: Y.Map< any > ): void {
yUndoManager.addToScope( ymap );
},

/**
* Undo the last recorded changes.
*
*/
undo(): HistoryRecord< ObjectData > | undefined {
if ( ! yUndoManager.canUndo() ) {
return;
}

// Perform the undo operation
yUndoManager.undo();

// Intentionally return an empty array, because the SyncProvider will update
// the entity record based on the Yjs document changes.
return [];
},

/**
* Redo the last undone changes.
*/
redo(): HistoryRecord< ObjectData > | undefined {
if ( ! yUndoManager.canRedo() ) {
return;
}

// Perform the redo operation
yUndoManager.redo();

// Intentionally return an empty array, because the SyncProvider will update
// the entity record based on the Yjs document changes.
return [];
},

/**
* Check if there are changes that can be undone.
*
* @return {boolean} Whether there are changes to undo.
*/
hasUndo(): boolean {
return yUndoManager.canUndo();
},

/**
* Check if there are changes that can be redone.
*
* @return {boolean} Whether there are changes to redo.
*/
hasRedo(): boolean {
return yUndoManager.canRedo();
},
};
}
21 changes: 21 additions & 0 deletions packages/sync/src/y-utilities/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
The MIT License (MIT)

Copyright (c) 2022 Kevin Jahns <kevin.jahns@protonmail.com>.

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
Loading