From df2d21ffdf1b357b113ccc827c297e5c2457f03e Mon Sep 17 00:00:00 2001 From: Ilya Maroz <37909603+ilyamore88@users.noreply.github.com> Date: Sat, 10 Oct 2026 13:23:01 +0100 Subject: [PATCH 1/2] feat(core): group undo steps by browser task UndoRedoManager buffers the local model events of the current browser task and records them when the task ends (setTimeout 0). A single event keeps the consecutive-text batching, so typing is unchanged; several events from one task (Enter split, paste) close the open batch and start a new step together. undo()/redo() record buffered events first, destroy() drops them. Also wrap block-level event data in a list when re-applying it: block events carry one serialized block while the model inserts/removes blocks as lists, so undoing or redoing any block add/remove used to throw. --- docs/collaboration.md | 4 + docs/diagrams/undo-redo-flow.mmd | 7 + openspec/changes/undo-group-by-task/tasks.md | 22 +- .../UndoRedoManager.integration.spec.ts | 132 ++++++++ .../src/components/UndoRedoManager.spec.ts | 305 +++++++++++++++++- .../core/src/components/UndoRedoManager.ts | 71 +++- 6 files changed, 521 insertions(+), 20 deletions(-) create mode 100644 packages/core/src/components/UndoRedoManager.integration.spec.ts diff --git a/docs/collaboration.md b/docs/collaboration.md index a6d77757..32f5afec 100644 --- a/docs/collaboration.md +++ b/docs/collaboration.md @@ -58,6 +58,8 @@ There are two undo/redo systems: `UndoRedoManager` in Core listens to document model events directly, groups consecutive changes by a 500ms debounce window, and stores logical steps on stacks. +Events are first buffered per browser task. When the task ends, a single event (e.g. a keystroke) is batched by the rule above: consecutive text inserts or removals in the same input within the debounce window. Several events from one task (e.g. a block split on Enter, or a paste) are one user action, so they close the open batch and start a new one together. Block-level events carry a single serialized block, which the manager wraps in a list when it re-applies them, because the model inserts and removes blocks as lists. + Undo/redo inverts and re-applies the stored events while suppressing re-record to avoid stack pollution. This manager respects `UndoCoreEvent` and `RedoCoreEvent` — if either event's `defaultPrevented` is true, the manager skips the operation, allowing other handlers (like `CollaborationManager`) to take precedence. @@ -66,6 +68,8 @@ This manager respects `UndoCoreEvent` and `RedoCoreEvent` — if either event's `UndoRedoManager` in Collaboration stores `Operation` instances and inverts them for the OT pipeline. +It batches operations with its own debounce rule and does not group by browser task yet, so an action that makes several changes at once (Enter split, paste) can undo in several steps when collaboration is enabled. + `BatchedOperation` groups rapid single-character inserts or deletes on the same data key into one logical edit for better history granularity. Insert operations are batched when each character is appended sequentially (`[0,0]`, `[1,1]`, `[2,2]`...). Delete operations are batched in two patterns: **backspace** where position decrements after each deletion (`[3,3]`, `[2,2]`, `[1,1]`...), or **forward delete** where position stays the same (`[0,0]`, `[0,0]`...). When a user presses Cmd/Ctrl+Z or calls `api.document.undo()`, `DocumentAPI` dispatches a `UndoCoreEvent`. `CollaborationManager` listens first and immediately calls `preventDefault()` to take over undo/redo handling, forwarding the operation through the OT server (if connected). Core's `UndoRedoManager` also listens but only processes undo if not prevented by an earlier handler. diff --git a/docs/diagrams/undo-redo-flow.mmd b/docs/diagrams/undo-redo-flow.mmd index a9c6f6d0..972aae8f 100644 --- a/docs/diagrams/undo-redo-flow.mmd +++ b/docs/diagrams/undo-redo-flow.mmd @@ -45,3 +45,10 @@ sequenceDiagram Note over CollaborationManager: Debounce timeout fires → batch moves to undo stack + %% ── Core: one user action = one step (grouping by task) ── + User->>EditorJSModel: presses Enter mid-paragraph (one browser task) + EditorJSModel-->>CoreUndoRedoManager: TextRemovedEvent (buffered for the task) + EditorJSModel-->>CoreUndoRedoManager: BlockAddedEvent (buffered for the task) + Note over CoreUndoRedoManager: Task ends (setTimeout 0) → several events → close the open batch, start a new one with both + Note over CoreUndoRedoManager: A task with a single event (a keystroke) follows the consecutive-text batching above + Note over CollaborationManager: Does not group by task yet — the same Enter is two undo steps here diff --git a/openspec/changes/undo-group-by-task/tasks.md b/openspec/changes/undo-group-by-task/tasks.md index 2671f1c6..536122ad 100644 --- a/openspec/changes/undo-group-by-task/tasks.md +++ b/openspec/changes/undo-group-by-task/tasks.md @@ -1,7 +1,7 @@ ## 1. Tests first (UndoRedoManager unit) -- [ ] 1.1 Switch `packages/core/src/components/UndoRedoManager.spec.ts` to Jest fake timers where it isn't already, and confirm the existing tests still pass unchanged -- [ ] 1.2 Write failing tests for the core spec scenarios: +- [x] 1.1 Use Jest fake timers in `packages/core/src/components/UndoRedoManager.spec.ts` and add an `endTask()` helper. Existing tests that fire several events to model *separate* user actions now end the task between them; previously they relied on every event being judged individually +- [x] 1.2 Write failing tests for the core spec scenarios: - should undo several changes made in one task in a single step - should redo a whole task in a single step - should keep single keystrokes batched as before @@ -15,20 +15,20 @@ ## 2. Implementation -- [ ] 2.1 Add `#taskEvents`, `#taskTimer` and `#closeTask()` to `UndoRedoManager`, and route local events through the buffer (design D1, D3). Keep clearing `#redoStack` when each event arrives -- [ ] 2.2 Apply the one-event and several-event rules in `#closeTask()` (design D2) -- [ ] 2.3 Call `#closeTask()` from `undo()` and `redo()` before `#putBatchToUndo()`, and clear `#taskTimer` in `destroy()` (design D4) -- [ ] 2.4 Write failing tests for re-applying block events (undo of Added and Removed, redo), then wrap a block event's data in a one-item list in `#apply` (design D5) -- [ ] 2.5 Run `yarn test`, `yarn lint` and `yarn test:mutations` (if configured) in `packages/core` +- [x] 2.1 Add `#taskEvents`, `#taskTimer` and `#closeTask()` to `UndoRedoManager`, and route local events through the buffer (design D1, D3). Keep clearing `#redoStack` when each event arrives +- [x] 2.2 Apply the one-event and several-event rules in `#closeTask()` (design D2) +- [x] 2.3 Call `#closeTask()` from `undo()` and `redo()` before `#putBatchToUndo()`, and clear `#taskTimer` in `destroy()` (design D4) +- [x] 2.4 Write failing tests for re-applying block events (undo of Added and Removed, redo), then wrap a block event's data in a one-item list in `#apply` (design D5) +- [x] 2.5 Run `yarn test`, `yarn lint` and `yarn test:mutations` (if configured) in `packages/core` ## 3. Integration tests (real model and BlocksManager) -- [ ] 3.1 should undo a mid-paragraph Enter split in one step -- [ ] 3.2 should undo and redo a multi-change task that adds a block with text without AlreadyExistingKeyError. Its comment should explain why block-construction `DataNodeAddedEvent`s must stay out of undo (design R2) +- [x] 3.1 should undo a mid-paragraph Enter split in one step +- [x] 3.2 should undo and redo a multi-change task that adds a block with text without AlreadyExistingKeyError. Its comment should explain why block-construction `DataNodeAddedEvent`s must stay out of undo (design R2) ## 4. Docs and wrap-up -- [ ] 4.1 Update `docs/diagrams/undo-redo-flow.mmd` with the task buffering step in core's undo manager -- [ ] 4.2 Note in `docs/collaboration.md` that `collaboration-manager` undo does not group by task yet +- [x] 4.1 Update `docs/diagrams/undo-redo-flow.mmd` with the task buffering step in core's undo manager +- [x] 4.2 Note in `docs/collaboration.md` that `collaboration-manager` undo does not group by task yet - [ ] 4.3 Run `yarn lint` and `yarn test` from the repo root - [ ] 4.4 Run `openspec validate undo-group-by-task --type change` and fix any issues diff --git a/packages/core/src/components/UndoRedoManager.integration.spec.ts b/packages/core/src/components/UndoRedoManager.integration.spec.ts new file mode 100644 index 00000000..bc1d810e --- /dev/null +++ b/packages/core/src/components/UndoRedoManager.integration.spec.ts @@ -0,0 +1,132 @@ +/* eslint-disable @typescript-eslint/no-magic-numbers */ +import { jest, beforeEach, afterEach, describe, it, expect } from '@jest/globals'; +import type { CoreConfigValidated, DataKey } from '@editorjs/sdk'; +// @ts-expect-error - TS don't import types via import() so have to import them here as well +import type { BlocksManager } from './BlockManager'; +// @ts-expect-error - TS don't import types via import() so have to import them here as well +import type ToolsManager from '../tools/ToolsManager'; +import { EventBus } from '@editorjs/sdk'; +import { EditorJSModel } from '@editorjs/model'; + +const USER_ID = 'integration-user'; +const DOCUMENT_ID = 'integration-doc'; + +/** + * Mock ToolsManager — tools rendering is not part of this integration scope. + * Paragraphs can be split, so a split moves the text after the caret into a new paragraph + */ +jest.unstable_mockModule('../tools/ToolsManager', () => ({ + default: jest.fn(() => ({ + blockTools: { + get: jest.fn((name: string) => ({ + name, + options: { canBeSplit: true }, + create: jest.fn(() => ({ + render: jest.fn(() => Promise.resolve(document.createElement('div'))), + })), + })), + }, + })), +})); + +const ToolsManager = (await import('../tools/ToolsManager')).default; +const { BlocksManager } = await import('./BlockManager.js'); +const { UndoRedoManager } = await import('./UndoRedoManager.js'); + +/** + * Ends the current browser task, so UndoRedoManager groups the events dispatched so far + */ +function endTask(): void { + jest.advanceTimersByTime(0); +} + +describe('UndoRedoManager integration (real model, mocked tools)', () => { + let model: InstanceType; + let blocksManager: BlocksManager; + let undoRedoManager: InstanceType; + + const config = { + defaultBlock: 'paragraph', + userId: USER_ID, + documentId: DOCUMENT_ID, + holder: {} as HTMLElement, + } as CoreConfigValidated; + + const paragraph = (value: string): Record => ({ + text: { + $t: 't', + value, + fragments: [], + }, + }); + + beforeEach(() => { + jest.useFakeTimers(); + + model = new EditorJSModel(USER_ID, { identifier: DOCUMENT_ID }); + + const eventBus = new EventBus(); + + // @ts-expect-error — mock constructor + const toolsManager = new ToolsManager(); + + blocksManager = new BlocksManager(model, eventBus, toolsManager, config); + undoRedoManager = new UndoRedoManager(model, eventBus, config); + + /** + * The initial paragraph is its own undo step + */ + model.addBlock(USER_ID, { + name: 'paragraph', + data: paragraph('Hello world'), + }); + endTask(); + jest.runAllTimers(); + }); + + afterEach(() => { + undoRedoManager.destroy(); + jest.useRealTimers(); + jest.restoreAllMocks(); + }); + + it('should undo a mid-paragraph Enter split in one step', () => { + const before = structuredClone(model.serialized.blocks); + + blocksManager.splitBlock(0, 'text' as DataKey, 5); + endTask(); + + expect(model.length).toBe(2); + + undoRedoManager.undo(); + + expect(model.serialized.blocks).toEqual(before); + }); + + /** + * Building a block dispatches a BlockAddedEvent and, in a microtask, one DataNodeAddedEvent + * per data key. Those deferred events reach the undo manager without a userId, so they are not + * recorded — which is required: the BlockAddedEvent already carries the block's data, and + * re-applying both on redo would create the same data node twice (AlreadyExistingKeyError). + * If this test starts failing after userId forwarding is fixed, skip data-node events that are + * covered by a BlockAddedEvent of the same step instead of recording them. + */ + it('should undo and redo a multi-change task that adds a block with text without AlreadyExistingKeyError', async () => { + blocksManager.splitBlock(0, 'text' as DataKey, 5); + + /** + * Let the deferred DataNodeAddedEvents run inside the same task + */ + await Promise.resolve(); + endTask(); + + const afterSplit = structuredClone(model.serialized.blocks); + + undoRedoManager.undo(); + + expect(model.length).toBe(1); + + expect(() => undoRedoManager.redo()).not.toThrow(); + expect(model.serialized.blocks).toEqual(afterSplit); + }); +}); diff --git a/packages/core/src/components/UndoRedoManager.spec.ts b/packages/core/src/components/UndoRedoManager.spec.ts index a1893e4a..d53e3d73 100644 --- a/packages/core/src/components/UndoRedoManager.spec.ts +++ b/packages/core/src/components/UndoRedoManager.spec.ts @@ -39,10 +39,11 @@ jest.unstable_mockModule('@editorjs/sdk', () => ({ Modified: 'modified', }, TextIndex: class TextIndex {}, + BlockIndex: class BlockIndex {}, })); const { EditorJSModel } = await import('@editorjs/model'); -const { EventType, EventAction, EventBus, TextIndex } = await import('@editorjs/sdk'); +const { EventType, EventAction, EventBus, TextIndex, BlockIndex } = await import('@editorjs/sdk'); const { UndoRedoManager } = await import('./UndoRedoManager.js'); // ─── helpers ──────────────────────────────────────────────────────────────── @@ -114,6 +115,14 @@ function fireModelEvent(listener: (e: unknown) => void, payload: ReturnType { let model: MockModel; let eventBus: MockEventBus; @@ -211,6 +220,16 @@ describe('UndoRedoManager', () => { expect(clearTimeoutSpy).toHaveBeenCalled(); }); + it('should not record events buffered for an unfinished task after destroy', () => { + fireModelEvent(modelChangedListener, createPayload(EventAction.Added)); + + manager.destroy(); + jest.runAllTimers(); + manager.undo(); + + expect(model.removeData).not.toHaveBeenCalled(); + }); + it('should remove the model updates listener', () => { manager.destroy(); @@ -416,6 +435,7 @@ describe('UndoRedoManager', () => { } ) ); + endTask(); fireModelEvent( modelChangedListener, createPayload( @@ -426,6 +446,7 @@ describe('UndoRedoManager', () => { } ) ); + endTask(); jest.runAllTimers(); manager.undo(); @@ -669,6 +690,7 @@ describe('UndoRedoManager', () => { } ) ); + endTask(); fireModelEvent( modelChangedListener, createPayload( @@ -679,6 +701,7 @@ describe('UndoRedoManager', () => { } ) ); + endTask(); jest.runAllTimers(); manager.undo(); // both events should be undone in a single step @@ -700,6 +723,7 @@ describe('UndoRedoManager', () => { } ) ); + endTask(); fireModelEvent( modelChangedListener, createPayload( @@ -710,6 +734,7 @@ describe('UndoRedoManager', () => { } ) ); + endTask(); jest.runAllTimers(); manager.undo(); // only the second event @@ -739,6 +764,7 @@ describe('UndoRedoManager', () => { } ) ); + endTask(); fireModelEvent( modelChangedListener, createPayload( @@ -752,6 +778,7 @@ describe('UndoRedoManager', () => { } ) ); + endTask(); jest.runAllTimers(); // First undo targets the Modified event (on top of the stack) @@ -775,6 +802,7 @@ describe('UndoRedoManager', () => { } ) ); + endTask(); fireModelEvent( modelChangedListener, createPayload( @@ -785,6 +813,7 @@ describe('UndoRedoManager', () => { } ) ); + endTask(); jest.runAllTimers(); // First undo should only undo the Removed event (top of stack) @@ -814,6 +843,7 @@ describe('UndoRedoManager', () => { } ) ); + endTask(); fireModelEvent( modelChangedListener, createPayload( @@ -824,6 +854,7 @@ describe('UndoRedoManager', () => { } ) ); + endTask(); jest.runAllTimers(); manager.undo(); @@ -851,6 +882,7 @@ describe('UndoRedoManager', () => { } ) ); + endTask(); fireModelEvent( modelChangedListener, createPayload( @@ -861,6 +893,7 @@ describe('UndoRedoManager', () => { } ) ); + endTask(); jest.runAllTimers(); manager.undo(); @@ -888,6 +921,7 @@ describe('UndoRedoManager', () => { } ) ); + endTask(); fireModelEvent( modelChangedListener, createPayload( @@ -898,6 +932,7 @@ describe('UndoRedoManager', () => { } ) ); + endTask(); jest.runAllTimers(); manager.undo(); @@ -920,6 +955,7 @@ describe('UndoRedoManager', () => { } ) ); + endTask(); fireModelEvent( modelChangedListener, createPayload( @@ -930,6 +966,7 @@ describe('UndoRedoManager', () => { } ) ); + endTask(); jest.runAllTimers(); manager.undo(); @@ -952,6 +989,7 @@ describe('UndoRedoManager', () => { } ) ); + endTask(); fireModelEvent( modelChangedListener, createPayload( @@ -962,6 +1000,7 @@ describe('UndoRedoManager', () => { } ) ); + endTask(); jest.runAllTimers(); manager.undo(); @@ -982,6 +1021,7 @@ describe('UndoRedoManager', () => { } ) ); + endTask(); jest.runAllTimers(); // debounce fires → batch pushed to undoStack @@ -1004,6 +1044,7 @@ describe('UndoRedoManager', () => { } ) ); + endTask(); // Advance to 400 ms – timer has not fired yet (fires at 500 ms) jest.advanceTimersByTime(400); @@ -1019,6 +1060,7 @@ describe('UndoRedoManager', () => { } ) ); + endTask(); // Advance another 400 ms – total 800 ms but timer was reset at 400 ms, fires at 900 ms jest.advanceTimersByTime(400); @@ -1030,4 +1072,265 @@ describe('UndoRedoManager', () => { expect(model.removeData).toHaveBeenCalledTimes(2); }); }); + + describe('block events', () => { + const blockIndex = (): object => Object.assign(new (BlockIndex as unknown as new () => object)(), { blockIndex: 1 }); + const block = { + id: 'block-1', + name: 'paragraph', + data: {}, + }; + + it('should pass a block-level Added event\'s block as a one-item array when undoing', () => { + const index = blockIndex(); + + fireModelEvent(modelChangedListener, createPayload(EventAction.Added, { index: index as ReturnType, + data: block })); + + manager.undo(); + + expect(model.removeData).toHaveBeenCalledWith(USER_ID, index, [block]); + }); + + it('should pass a block-level Removed event\'s block as a one-item array when undoing', () => { + const index = blockIndex(); + + fireModelEvent(modelChangedListener, createPayload(EventAction.Removed, { index: index as ReturnType, + data: block })); + + manager.undo(); + + expect(model.insertData).toHaveBeenCalledWith(USER_ID, index, [block]); + }); + + it('should pass a block-level event\'s block as a one-item array when redoing', () => { + const index = blockIndex(); + + fireModelEvent(modelChangedListener, createPayload(EventAction.Added, { index: index as ReturnType, + data: block })); + + manager.undo(); + manager.redo(); + + expect(model.insertData).toHaveBeenCalledWith(USER_ID, index, [block]); + }); + + it('should pass text event data unchanged', () => { + const index = createIndex({ textRange: [0, 0] }); + + fireModelEvent(modelChangedListener, createPayload(EventAction.Added, { index, + data: 'a' })); + + manager.undo(); + + expect(model.removeData).toHaveBeenCalledWith(USER_ID, index, 'a'); + }); + }); + + describe('grouping by task', () => { + const textAt = (start: number, end = start): ReturnType => createIndex({ textRange: [start, end] }); + const blockAt = (blockIndex: number): ReturnType => createIndex({ + isTextIndex: false, + blockIndex, + textRange: undefined, + }); + + it('should undo several changes made in one task in a single step', () => { + fireModelEvent(modelChangedListener, createPayload(EventAction.Removed, { index: textAt(2, 5), + data: 'llo' })); + fireModelEvent(modelChangedListener, createPayload(EventAction.Added, { index: blockAt(1), + data: [] })); + endTask(); + jest.runAllTimers(); + + manager.undo(); + + expect(model.removeData).toHaveBeenCalledTimes(1); + expect(model.insertData).toHaveBeenCalledTimes(1); + + manager.undo(); + + expect(model.removeData).toHaveBeenCalledTimes(1); + expect(model.insertData).toHaveBeenCalledTimes(1); + }); + + it('should undo the events of one task in reverse order', () => { + const removed = createPayload(EventAction.Removed, { index: textAt(2, 5), + data: 'llo' }); + const added = createPayload(EventAction.Added, { index: blockAt(1), + data: [] }); + const calls: string[] = []; + + model.removeData = jest.fn(() => calls.push('removeData')); + model.insertData = jest.fn(() => calls.push('insertData')); + + fireModelEvent(modelChangedListener, removed); + fireModelEvent(modelChangedListener, added); + endTask(); + + manager.undo(); + + expect(calls).toEqual(['removeData', 'insertData']); + }); + + it('should redo a whole task in a single step', () => { + fireModelEvent(modelChangedListener, createPayload(EventAction.Removed, { index: textAt(2, 5), + data: 'llo' })); + fireModelEvent(modelChangedListener, createPayload(EventAction.Added, { index: blockAt(1), + data: [] })); + endTask(); + jest.runAllTimers(); + + manager.undo(); + manager.redo(); + + expect(model.removeData).toHaveBeenCalledTimes(2); + expect(model.insertData).toHaveBeenCalledTimes(2); + }); + + it('should keep single keystrokes batched as before', () => { + fireModelEvent(modelChangedListener, createPayload(EventAction.Added, { index: textAt(0), + data: 'a' })); + endTask(); + fireModelEvent(modelChangedListener, createPayload(EventAction.Added, { index: textAt(1), + data: 'b' })); + endTask(); + jest.runAllTimers(); + + manager.undo(); + + expect(model.removeData).toHaveBeenCalledTimes(2); + }); + + it('should keep typing before a multi-change task as a separate step', () => { + const typed = createPayload(EventAction.Added, { index: textAt(0), + data: 'a' }); + + fireModelEvent(modelChangedListener, typed); + endTask(); + + /** + * The first event of the task would continue the typed text on its own + */ + fireModelEvent(modelChangedListener, createPayload(EventAction.Added, { index: textAt(1), + data: 'b' })); + fireModelEvent(modelChangedListener, createPayload(EventAction.Added, { index: blockAt(1), + data: [] })); + endTask(); + jest.runAllTimers(); + + manager.undo(); + + expect(model.removeData).toHaveBeenCalledTimes(2); + expect(model.removeData).not.toHaveBeenCalledWith(USER_ID, typed.index, 'a'); + + manager.undo(); + + expect(model.removeData).toHaveBeenLastCalledWith(USER_ID, typed.index, 'a'); + }); + + it('should start a new step for typing after a task that ended with a block change', () => { + fireModelEvent(modelChangedListener, createPayload(EventAction.Removed, { index: textAt(2, 5), + data: 'llo' })); + fireModelEvent(modelChangedListener, createPayload(EventAction.Added, { index: blockAt(1), + data: [] })); + endTask(); + + const typed = createPayload(EventAction.Added, { index: textAt(0), + data: 'x' }); + + fireModelEvent(modelChangedListener, typed); + endTask(); + jest.runAllTimers(); + + manager.undo(); + + expect(model.removeData).toHaveBeenCalledTimes(1); + expect(model.removeData).toHaveBeenCalledWith(USER_ID, typed.index, 'x'); + expect(model.insertData).not.toHaveBeenCalled(); + }); + + it('should merge typing that continues a replace-selection task into its step', () => { + fireModelEvent(modelChangedListener, createPayload(EventAction.Removed, { index: textAt(0, 3), + data: 'abc' })); + fireModelEvent(modelChangedListener, createPayload(EventAction.Added, { index: textAt(0), + data: 'x' })); + endTask(); + fireModelEvent(modelChangedListener, createPayload(EventAction.Added, { index: textAt(1), + data: 'y' })); + endTask(); + jest.runAllTimers(); + + manager.undo(); + + expect(model.removeData).toHaveBeenCalledTimes(2); + expect(model.insertData).toHaveBeenCalledTimes(1); + }); + + it('should keep consecutive multi-change tasks as separate steps', () => { + fireModelEvent(modelChangedListener, createPayload(EventAction.Added, { index: blockAt(1), + data: [] })); + fireModelEvent(modelChangedListener, createPayload(EventAction.Added, { index: blockAt(2), + data: [] })); + endTask(); + fireModelEvent(modelChangedListener, createPayload(EventAction.Added, { index: blockAt(3), + data: [] })); + fireModelEvent(modelChangedListener, createPayload(EventAction.Added, { index: blockAt(4), + data: [] })); + endTask(); + jest.runAllTimers(); + + manager.undo(); + + expect(model.removeData).toHaveBeenCalledTimes(2); + }); + + it('should record buffered events before undo when the task has not ended', () => { + fireModelEvent(modelChangedListener, createPayload(EventAction.Removed, { index: textAt(2, 5), + data: 'llo' })); + fireModelEvent(modelChangedListener, createPayload(EventAction.Added, { index: blockAt(1), + data: [] })); + + manager.undo(); + + expect(model.removeData).toHaveBeenCalledTimes(1); + expect(model.insertData).toHaveBeenCalledTimes(1); + }); + + it('should record buffered events before redo when the task has not ended', () => { + fireModelEvent(modelChangedListener, createPayload(EventAction.Added, { index: blockAt(1), + data: [] })); + endTask(); + jest.runAllTimers(); + manager.undo(); + + /** + * A new local change clears the redo stack, even if its task has not ended yet + */ + fireModelEvent(modelChangedListener, createPayload(EventAction.Added, { index: blockAt(2), + data: [] })); + + manager.redo(); + manager.undo(); + + expect(model.insertData).not.toHaveBeenCalled(); + expect(model.removeData).toHaveBeenCalledTimes(2); + }); + + it('should ignore remote events while a task is buffered', () => { + fireModelEvent(modelChangedListener, createPayload(EventAction.Added, { index: blockAt(1), + data: ['local-1'] })); + fireModelEvent(modelChangedListener, createPayload(EventAction.Added, { index: blockAt(2), + data: ['remote'], + userId: OTHER_USER_ID })); + fireModelEvent(modelChangedListener, createPayload(EventAction.Added, { index: blockAt(3), + data: ['local-2'] })); + endTask(); + + manager.undo(); + + expect(model.removeData).toHaveBeenCalledTimes(2); + expect(model.removeData).not.toHaveBeenCalledWith(USER_ID, expect.anything(), ['remote']); + }); + }); }); diff --git a/packages/core/src/components/UndoRedoManager.ts b/packages/core/src/components/UndoRedoManager.ts index 3bdf018d..312ee085 100644 --- a/packages/core/src/components/UndoRedoManager.ts +++ b/packages/core/src/components/UndoRedoManager.ts @@ -3,6 +3,8 @@ import 'reflect-metadata'; import { inject, injectable } from 'inversify'; import { EditorJSModel } from '@editorjs/model'; import { + BlockIndex, + type BlockNodeSerialized, CoreConfigValidated, CoreEventType, EventAction, @@ -31,6 +33,10 @@ const DEBOUNCE_TIMEOUT = 500; * debounced steps, and re-applies or inverts them through the Editor API when * undo/redo is requested. * + * Events are first buffered per browser task: all changes a single user action makes + * synchronously (e.g. a block split on Enter, or a paste) end up in one undo step, + * while single changes per task (typing) keep the consecutive-text batching. + * * This component is intentionally designed for single-user scenarios only and * has no dependency on Operational-Transformation (OT) infrastructure. */ @@ -73,6 +79,16 @@ export class UndoRedoManager { */ #debounceTimer?: ReturnType; + /** + * Local events dispatched during the current browser task, not yet added to a batch + */ + #taskEvents: EventPayloadBase[] = []; + + /** + * Timer handle that fires once the current browser task (and its microtasks) is over + */ + #taskTimer?: ReturnType; + /** * Flag to properly handling events that are triggered by undo/redo operations */ @@ -134,9 +150,10 @@ export class UndoRedoManager { /** * Undoes the last recorded group of events. - * Flushes the current debounce group first so it is included in the step. + * Flushes the current task and debounce group first so they are included in the step. */ public undo(): void { + this.#closeTask(); this.#putBatchToUndo(); const events = this.#undoStack.pop(); @@ -160,6 +177,7 @@ export class UndoRedoManager { * Redoes the last undone group of events. */ public redo(): void { + this.#closeTask(); this.#putBatchToUndo(); const events = this.#redoStack.pop(); @@ -184,6 +202,8 @@ export class UndoRedoManager { */ public destroy(): void { clearTimeout(this.#debounceTimer); + clearTimeout(this.#taskTimer); + this.#taskEvents = []; this.#eventBus.removeEventListener(`core:${CoreEventType.Undo}`, this.#undoListener); this.#eventBus.removeEventListener(`core:${CoreEventType.Redo}`, this.#redoListener); this.#model.removeEventListener(EventType.Changed, this.#modelUpdatesListener); @@ -196,16 +216,24 @@ export class UndoRedoManager { #apply(event: EventPayloadBase): void { switch (event.action) { case EventAction.Added: - case EventAction.Removed: + case EventAction.Removed: { + /** + * Block events carry a single serialized block, while the model inserts and removes blocks as a list + */ + const data = event.index instanceof BlockIndex + ? [event.data as BlockNodeSerialized] + : event.data as string; + /** * @todo currently undo of deleting forward sets the caret in the wrong place */ this.#model[event.action === EventAction.Removed ? 'insertData' : 'removeData']( event.userId, event.index, - event.data as string + data ); break; + } case EventAction.Modified: this.#model.modifyData( event.userId, @@ -251,8 +279,8 @@ export class UndoRedoManager { } /** - * Receives a raw model event, converts it to a RecordedEvent, and adds it - * to the current debounce group if it belongs to the current user. + * Receives a raw model event and buffers it for the current browser task + * if it belongs to the current user. * @param e - model event emitted by EditorJSModel */ #handleEvent(e: ModelEvents): void { @@ -271,11 +299,38 @@ export class UndoRedoManager { this.#redoStack = []; - if (this.#canAddToBatch(detail)) { - this.#batch!.push(detail); + this.#taskEvents.push(detail); + + /** + * The first event of a task schedules the task's end. + * Zero-delay timeout runs after the current task and all its microtasks + */ + if (this.#taskEvents.length === 1) { + this.#taskTimer = setTimeout(() => this.#closeTask(), 0); + } + } + + /** + * Adds events of the finished browser task to the batch. + * A single event is batched by the consecutive-text rule (typing). + * Several events are a single user action, so they always start a new batch + */ + #closeTask(): void { + clearTimeout(this.#taskTimer); + + const events = this.#taskEvents; + + if (events.length === 0) { + return; + } + + this.#taskEvents = []; + + if (events.length === 1 && this.#canAddToBatch(events[0])) { + this.#batch!.push(events[0]); } else { this.#putBatchToUndo(); - this.#batch = [detail]; + this.#batch = events; } this.#debounce(); From 6f223090d1bde101973bdf70da3dac7c9dffc24a Mon Sep 17 00:00:00 2001 From: Ilya Maroz <37909603+ilyamore88@users.noreply.github.com> Date: Sat, 10 Oct 2026 13:25:48 +0100 Subject: [PATCH 2/2] docs(openspec): mark undo-group-by-task tasks complete --- openspec/changes/undo-group-by-task/tasks.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/openspec/changes/undo-group-by-task/tasks.md b/openspec/changes/undo-group-by-task/tasks.md index 536122ad..b74c0b17 100644 --- a/openspec/changes/undo-group-by-task/tasks.md +++ b/openspec/changes/undo-group-by-task/tasks.md @@ -30,5 +30,5 @@ - [x] 4.1 Update `docs/diagrams/undo-redo-flow.mmd` with the task buffering step in core's undo manager - [x] 4.2 Note in `docs/collaboration.md` that `collaboration-manager` undo does not group by task yet -- [ ] 4.3 Run `yarn lint` and `yarn test` from the repo root -- [ ] 4.4 Run `openspec validate undo-group-by-task --type change` and fix any issues +- [x] 4.3 Run `yarn lint` and `yarn test` from the repo root +- [x] 4.4 Run `openspec validate undo-group-by-task --type change` and fix any issues