diff --git a/packages/core-data/src/private-selectors.ts b/packages/core-data/src/private-selectors.ts index 928e1eedeea60d..d50ea7ced0e912 100644 --- a/packages/core-data/src/private-selectors.ts +++ b/packages/core-data/src/private-selectors.ts @@ -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; @@ -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 ) { + if ( window.__experimentalEnableSync ) { + if ( globalThis.IS_GUTENBERG_PLUGIN ) { + return getSyncManager()?.undoManager ?? state.undoManager; + } + } + return state.undoManager; } diff --git a/packages/core-data/src/selectors.ts b/packages/core-data/src/selectors.ts index c05c4db6285695..80216e3e7c9505 100644 --- a/packages/core-data/src/selectors.ts +++ b/packages/core-data/src/selectors.ts @@ -15,6 +15,7 @@ import { getQueriedTotalPages, } from './queried-data'; import { DEFAULT_ENTITY_KEY } from './entities'; +import { getUndoManager } from './private-selectors'; import { getNormalizedCommaSeparable, isRawAttribute, @@ -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(); } /** @@ -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(); } /** diff --git a/packages/core-data/src/types.ts b/packages/core-data/src/types.ts index dac976505a8f2d..c60e49da1df634 100644 --- a/packages/core-data/src/types.ts +++ b/packages/core-data/src/types.ts @@ -1,3 +1,9 @@ +declare global { + interface Window { + __experimentalEnableSync?: boolean; + } +} + export interface AnyFunction { ( ...args: any[] ): any; } diff --git a/packages/sync/src/manager.ts b/packages/sync/src/manager.ts index 26691cbd25ba10..fdd9d289aaf911 100644 --- a/packages/sync/src/manager.ts +++ b/packages/sync/src/manager.ts @@ -23,6 +23,7 @@ import type { SyncConfig, SyncManager, } from './types'; +import { createUndoManager } from './undo-manager'; import { createYjsDoc } from './utils'; interface EntityState { @@ -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. @@ -97,6 +99,8 @@ export function createSyncManager(): SyncManager { void updateEntityRecord( objectType, objectId ); }; + undoManager.addToScope( recordMap ); + const entityState: EntityState = { handlers, objectId, @@ -297,6 +301,7 @@ export function createSyncManager(): SyncManager { return { createMeta: createEntityMeta, load: loadEntity, + undoManager, unload: unloadEntity, update: updateCRDTDoc, }; diff --git a/packages/sync/src/types.ts b/packages/sync/src/types.ts index 3100cb8adfb66b..3cb6a923cb1e01 100644 --- a/packages/sync/src/types.ts +++ b/packages/sync/src/types.ts @@ -1,3 +1,8 @@ +/** + * WordPress dependencies + */ +import type { UndoManager as WPUndoManager } from '@wordpress/undo-manager'; + /** * External dependencies */ @@ -83,6 +88,7 @@ export interface SyncManager { record: ObjectData, handlers: RecordHandlers ) => Promise< void >; + undoManager: SyncUndoManager; unload: ( objectType: ObjectType, objectId: ObjectID ) => void; update: ( objectType: ObjectType, @@ -91,3 +97,7 @@ export interface SyncManager { origin: string ) => void; } + +export interface SyncUndoManager extends WPUndoManager< ObjectData > { + addToScope: ( ymap: Y.Map< any > ) => void; +} diff --git a/packages/sync/src/undo-manager.ts b/packages/sync/src/undo-manager.ts new file mode 100644 index 00000000000000..3dca69935c1196 --- /dev/null +++ b/packages/sync/src/undo-manager.ts @@ -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 { + 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(); + }, + }; +} diff --git a/packages/sync/src/y-utilities/LICENSE b/packages/sync/src/y-utilities/LICENSE new file mode 100644 index 00000000000000..2988b7d57a2dc8 --- /dev/null +++ b/packages/sync/src/y-utilities/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2022 Kevin Jahns . + +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. diff --git a/packages/sync/src/y-utilities/y-multidoc-undomanager.js b/packages/sync/src/y-utilities/y-multidoc-undomanager.js new file mode 100644 index 00000000000000..59cb834a680403 --- /dev/null +++ b/packages/sync/src/y-utilities/y-multidoc-undomanager.js @@ -0,0 +1,229 @@ +// File copied as is from the y-utilities package. +/* eslint-disable eslint-comments/disable-enable-pair */ +/* eslint-disable eslint-comments/no-unlimited-disable */ +/* eslint-disable */ +// @ts-nocheck +/* eslint-env browser */ + +import * as array from 'lib0/array'; +import * as map from 'lib0/map'; +import { Observable } from 'lib0/observable'; +import * as Y from 'yjs'; + +/** + * @param {YMultiDocUndoManager} mum + * @param {'undo' | 'redo'} type + */ +const popStackItem = ( mum, type ) => { + const stack = type === 'undo' ? mum.undoStack : mum.redoStack; + while ( stack.length > 0 ) { + const um = /** @type {Y.UndoManager} */ ( stack.pop() ); + const prevUmStack = type === 'undo' ? um.undoStack : um.redoStack; + const stackItem = /** @type {any} */ ( prevUmStack.pop() ); + let actionPerformed = false; + if ( type === 'undo' ) { + um.undoStack = [ stackItem ]; + actionPerformed = um.undo() !== null; + um.undoStack = prevUmStack; + } else { + um.redoStack = [ stackItem ]; + actionPerformed = um.redo() !== null; + um.redoStack = prevUmStack; + } + if ( actionPerformed ) { + return stackItem; + } + } + return null; +}; + +/** + * @extends Observable + */ +export class YMultiDocUndoManager extends Observable { + /** + * @param {Y.AbstractType|Array>} typeScope Accepts either a single type, or an array of types + * @param {ConstructorParameters[1]} opts + */ + constructor( typeScope = [], opts = {} ) { + super(); + /** + * @type {Map} + */ + this.docs = new Map(); + this.trackedOrigins = opts.trackedOrigins || new Set( [ null ] ); + opts.trackedOrigins = this.trackedOrigins; + this._defaultOpts = opts; + /** + * @type {Array} + */ + this.undoStack = []; + /** + * @type {Array} + */ + this.redoStack = []; + this.addToScope( typeScope ); + } + + /** + * @param {Array> | Y.AbstractType} ytypes + */ + addToScope( ytypes ) { + ytypes = array.isArray( ytypes ) ? ytypes : [ ytypes ]; + ytypes.forEach( ( ytype ) => { + const ydoc = /** @type {Y.Doc} */ ( ytype.doc ); + const um = map.setIfUndefined( this.docs, ydoc, () => { + const um = new Y.UndoManager( [ ytype ], this._defaultOpts ); + um.on( + 'stack-cleared', + /** @param {any} opts */ ( { + undoStackCleared, + redoStackCleared, + } ) => { + this.clear( undoStackCleared, redoStackCleared ); + } + ); + ydoc.on( 'destroy', () => { + this.docs.delete( ydoc ); + this.undoStack = this.undoStack.filter( + ( um ) => um.doc !== ydoc + ); + this.redoStack = this.redoStack.filter( + ( um ) => um.doc !== ydoc + ); + } ); + um.on( + 'stack-item-added', + /** @param {any} change */ ( change ) => { + const stack = + change.type === 'undo' + ? this.undoStack + : this.redoStack; + stack.push( um ); + this.emit( 'stack-item-added', [ + { ...change, ydoc: ydoc }, + this, + ] ); + } + ); + um.on( + 'stack-item-updated', + /** @param {any} change */ ( change ) => { + this.emit( 'stack-item-updated', [ + { ...change, ydoc }, + this, + ] ); + } + ); + um.on( + 'stack-item-popped', + /** @param {any} change */ ( change ) => { + this.emit( 'stack-item-popped', [ + { ...change, ydoc }, + this, + ] ); + } + ); + // if doc is destroyed + // emit events from um to multium + return um; + } ); + /* c8 ignore next 4 */ + if ( um.scope.every( ( yt ) => yt !== ytype ) ) { + um.scope.push( ytype ); + } + } ); + } + + /** + * @param {any} origin + */ + /* c8 ignore next 3 */ + addTrackedOrigin( origin ) { + this.trackedOrigins.add( origin ); + } + + /** + * @param {any} origin + */ + /* c8 ignore next 3 */ + removeTrackedOrigin( origin ) { + this.trackedOrigins.delete( origin ); + } + + /** + * Undo last changes on type. + * + * @return {any?} Returns StackItem if a change was applied + */ + undo() { + return popStackItem( this, 'undo' ); + } + + /** + * Redo last undo operation. + * + * @return {any?} Returns StackItem if a change was applied + */ + redo() { + return popStackItem( this, 'redo' ); + } + + clear( clearUndoStack = true, clearRedoStack = true ) { + /* c8 ignore next */ + if ( + ( clearUndoStack && this.canUndo() ) || + ( clearRedoStack && this.canRedo() ) + ) { + this.docs.forEach( ( um ) => { + /* c8 ignore next */ + clearUndoStack && ( this.undoStack = [] ); + /* c8 ignore next */ + clearRedoStack && ( this.redoStack = [] ); + um.clear( clearUndoStack, clearRedoStack ); + } ); + this.emit( 'stack-cleared', [ + { + undoStackCleared: clearUndoStack, + redoStackCleared: clearRedoStack, + }, + ] ); + } + } + + /* c8 ignore next 5 */ + stopCapturing() { + this.docs.forEach( ( um ) => { + um.stopCapturing(); + } ); + } + + /** + * Are undo steps available? + * + * @return {boolean} `true` if undo is possible + */ + canUndo() { + return this.undoStack.length > 0; + } + + /** + * Are redo steps available? + * + * @return {boolean} `true` if redo is possible + */ + canRedo() { + return this.redoStack.length > 0; + } + + destroy() { + this.docs.forEach( ( um ) => um.destroy() ); + super.destroy(); + } +} + +/** + * @todo remove + * @deprecated Use YMultiDocUndoManager instead + */ +export const MultiDocUndoManager = YMultiDocUndoManager;