From f55808e241ca159254545d7ae206f13459599b7a Mon Sep 17 00:00:00 2001 From: chriszarate Date: Thu, 16 Oct 2025 15:06:41 -0600 Subject: [PATCH 1/5] Real-time collaboration: Add YMultiDocUndoManager --- packages/core-data/src/entities.js | 4 +- packages/core-data/src/private-selectors.ts | 7 + packages/core-data/src/selectors.ts | 5 +- packages/core-data/src/types.ts | 6 + packages/sync/src/manager.ts | 7 + packages/sync/src/types.ts | 10 + packages/sync/src/undo-manager.ts | 110 +++++++++ packages/sync/src/y-utilities/LICENSE | 21 ++ .../src/y-utilities/y-multidoc-undomanager.js | 229 ++++++++++++++++++ 9 files changed, 396 insertions(+), 3 deletions(-) create mode 100644 packages/sync/src/undo-manager.ts create mode 100644 packages/sync/src/y-utilities/LICENSE create mode 100644 packages/sync/src/y-utilities/y-multidoc-undomanager.js diff --git a/packages/core-data/src/entities.js b/packages/core-data/src/entities.js index d7b7e421656481..964b102beae672 100644 --- a/packages/core-data/src/entities.js +++ b/packages/core-data/src/entities.js @@ -339,7 +339,9 @@ async function loadPostTypeEntities() { * * @type {Record< string, boolean >} */ - supports: {}, + supports: { + undo: true, + }, }; } } diff --git a/packages/core-data/src/private-selectors.ts b/packages/core-data/src/private-selectors.ts index eb121b170e03a1..dab3a3c69e2d3a 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; @@ -22,6 +23,12 @@ type EntityRecordKey = string | number; * @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 5844a2d21cb9fb..1568c2f9e0ca8d 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, @@ -1125,7 +1126,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(); } /** @@ -1137,7 +1138,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 b3643ed5733204..55cbea410a8c62 100644 --- a/packages/sync/src/manager.ts +++ b/packages/sync/src/manager.ts @@ -22,6 +22,7 @@ import type { SyncConfig, SyncManager, } from './types'; +import { createUndoManager } from './undo-manager'; import { createYjsDoc } from './utils'; interface EntityState { @@ -40,6 +41,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. @@ -96,6 +98,10 @@ export function createSyncManager(): SyncManager { void updateEntityRecord( objectType, objectId ); }; + if ( syncConfig.supports?.undo ) { + undoManager.addToScope( recordMap ); + } + const entityState: EntityState = { handlers, objectId, @@ -209,6 +215,7 @@ export function createSyncManager(): SyncManager { return { load: loadEntity, + undoManager, unload: unloadEntity, update: updateCRDTDoc, }; diff --git a/packages/sync/src/types.ts b/packages/sync/src/types.ts index fdad6498e45b57..3464be1ca51b62 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 */ @@ -67,6 +72,7 @@ export interface SyncManager { record: ObjectData, handlers: RecordHandlers ) => Promise< void >; + undoManager: SyncUndoManager; unload: ( objectType: ObjectType, objectId: ObjectID ) => void; update: ( objectType: ObjectType, @@ -75,3 +81,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; From 137489ae0a12ff3d2086cc3b7b0c9d24a922c75c Mon Sep 17 00:00:00 2001 From: chriszarate Date: Thu, 16 Oct 2025 15:06:41 -0600 Subject: [PATCH 2/5] Real-time collaboration: Add YMultiDocUndoManager --- packages/core-data/src/entities.js | 1 + packages/core-data/src/private-selectors.ts | 7 + packages/core-data/src/selectors.ts | 5 +- packages/core-data/src/types.ts | 6 + packages/sync/src/manager.ts | 7 + packages/sync/src/types.ts | 10 + packages/sync/src/undo-manager.ts | 110 +++++++++ packages/sync/src/y-utilities/LICENSE | 21 ++ .../src/y-utilities/y-multidoc-undomanager.js | 229 ++++++++++++++++++ 9 files changed, 394 insertions(+), 2 deletions(-) create mode 100644 packages/sync/src/undo-manager.ts create mode 100644 packages/sync/src/y-utilities/LICENSE create mode 100644 packages/sync/src/y-utilities/y-multidoc-undomanager.js diff --git a/packages/core-data/src/entities.js b/packages/core-data/src/entities.js index 86f659c62b642b..f91e70e86aa98e 100644 --- a/packages/core-data/src/entities.js +++ b/packages/core-data/src/entities.js @@ -374,6 +374,7 @@ async function loadPostTypeEntities() { */ supports: { crdtPersistence: true, + undo: true, }, }; } diff --git a/packages/core-data/src/private-selectors.ts b/packages/core-data/src/private-selectors.ts index 928e1eedeea60d..e16164c7be827c 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; @@ -22,6 +23,12 @@ type EntityRecordKey = string | number; * @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..89f79c947dffac 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,10 @@ export function createSyncManager(): SyncManager { void updateEntityRecord( objectType, objectId ); }; + if ( syncConfig.supports?.undo ) { + undoManager.addToScope( recordMap ); + } + const entityState: EntityState = { handlers, objectId, @@ -297,6 +303,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; From cad21339e7edaa68a378490c96ac11107f5b9aa2 Mon Sep 17 00:00:00 2001 From: ingeniumed Date: Tue, 2 Dec 2025 07:38:37 +1100 Subject: [PATCH 3/5] Drop undo from supports and have it be on by default --- packages/core-data/src/entities.js | 1 - packages/sync/src/manager.ts | 4 +--- 2 files changed, 1 insertion(+), 4 deletions(-) diff --git a/packages/core-data/src/entities.js b/packages/core-data/src/entities.js index d69fab166e4299..3a9070911bc746 100644 --- a/packages/core-data/src/entities.js +++ b/packages/core-data/src/entities.js @@ -375,7 +375,6 @@ async function loadPostTypeEntities() { supports: { undo: true, crdtPersistence: true, - undo: true, }, }; } diff --git a/packages/sync/src/manager.ts b/packages/sync/src/manager.ts index 89f79c947dffac..fdd9d289aaf911 100644 --- a/packages/sync/src/manager.ts +++ b/packages/sync/src/manager.ts @@ -99,9 +99,7 @@ export function createSyncManager(): SyncManager { void updateEntityRecord( objectType, objectId ); }; - if ( syncConfig.supports?.undo ) { - undoManager.addToScope( recordMap ); - } + undoManager.addToScope( recordMap ); const entityState: EntityState = { handlers, From 1f1020c83ecf547cb2f1fe5c6aba9b52690357b6 Mon Sep 17 00:00:00 2001 From: ingeniumed Date: Tue, 2 Dec 2025 07:40:24 +1100 Subject: [PATCH 4/5] Drop undo from supports and have it be on by default --- packages/core-data/src/entities.js | 1 - 1 file changed, 1 deletion(-) diff --git a/packages/core-data/src/entities.js b/packages/core-data/src/entities.js index 3a9070911bc746..86f659c62b642b 100644 --- a/packages/core-data/src/entities.js +++ b/packages/core-data/src/entities.js @@ -373,7 +373,6 @@ async function loadPostTypeEntities() { * @type {Record< string, boolean >} */ supports: { - undo: true, crdtPersistence: true, }, }; From 021c75d3dd42fb90b3fae844a4fc2cb9165b0c30 Mon Sep 17 00:00:00 2001 From: ingeniumed Date: Fri, 5 Dec 2025 09:19:02 +1100 Subject: [PATCH 5/5] Update the js selector doc --- packages/core-data/src/private-selectors.ts | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/packages/core-data/src/private-selectors.ts b/packages/core-data/src/private-selectors.ts index e16164c7be827c..d50ea7ced0e912 100644 --- a/packages/core-data/src/private-selectors.ts +++ b/packages/core-data/src/private-selectors.ts @@ -18,6 +18,18 @@ 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.