Skip to content
Draft
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
4 changes: 4 additions & 0 deletions docs/collaboration.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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.
Expand Down
7 changes: 7 additions & 0 deletions docs/diagrams/undo-redo-flow.mmd
Original file line number Diff line number Diff line change
Expand Up @@ -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
26 changes: 13 additions & 13 deletions openspec/changes/undo-group-by-task/tasks.md
Original file line number Diff line number Diff line change
@@ -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
Expand All @@ -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
- [ ] 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.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
- [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
132 changes: 132 additions & 0 deletions packages/core/src/components/UndoRedoManager.integration.spec.ts
Original file line number Diff line number Diff line change
@@ -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<typeof EditorJSModel>;
let blocksManager: BlocksManager;
let undoRedoManager: InstanceType<typeof UndoRedoManager>;

const config = {
defaultBlock: 'paragraph',
userId: USER_ID,
documentId: DOCUMENT_ID,
holder: {} as HTMLElement,
} as CoreConfigValidated;

const paragraph = (value: string): Record<string, unknown> => ({
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);
});
});
Loading
Loading