Skip to content
Open
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
2 changes: 2 additions & 0 deletions openspec/changes/undo-group-by-task/.openspec.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
schema: spec-driven
created: 2026-09-29
100 changes: 100 additions & 0 deletions openspec/changes/undo-group-by-task/design.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
## Context

Core's `UndoRedoManager` (`packages/core/src/components/UndoRedoManager.ts`) listens to `EventType.Changed` on `EditorJSModel`.

- **Which events it records.** It ignores remote events (where `detail.userId` isn't the local user) and the events it causes itself while replaying an undo or redo (`#isApplying`).
- **How events become steps.** Recorded events are collected into `#batch`. The batch becomes an undo step (is pushed onto `#undoStack`) either after 500 ms without new events, or when `#canAddToBatch` rejects the next event. `#canAddToBatch` only accepts a text insert or removal that directly continues the previous one in the same `blockIndex`/`dataKey`.
- **A step is already a list of events.** `undo()` and `redo()` replay the whole list, so grouping only depends on where steps are cut.

Every user action in the editor runs synchronously inside one browser task: a keydown or `beforeinput` handler, a `paste` handler, a toolbar click. The model changes it causes are dispatched synchronously within that task. The only deferred events are the `DataNodeAddedEvent`s that `BlockNode` queues with `queueMicrotask` during construction, and microtasks still run before the task's end callback (`setTimeout(0)`). Those events reach the manager without a `userId` (the re-wrap in `EditorJSModel` reads `getContext()` after it has been popped), so they are not recorded today. That is correct, because `BlockAdded` already carries the block's data.

`BlockManager.splitBlock` in the middle of a text emits `TextRemoved`, then `BlockAdded`. With today's rule that is two undo steps for one Enter.

## Goals / Non-Goals

**Goals:**
- A user action that makes several model changes in one task undoes and redoes as one step.
- Typing keeps today's batching exactly.
- A multi-change action is always kept separate from typing that comes before it.
- No public API, no event-payload change, no change outside `UndoRedoManager`.

**Non-Goals:**
- **Grouping across tasks.** Async actions, such as a file paste that waits for an upload, can't be grouped this way.
- **Grouping in `collaboration-manager`'s undo manager.**
- **Fixing `userId` loss for microtask-dispatched events.**

## Decisions

### D1. Buffer the current task, decide when it ends

```
local event ─▶ #taskEvents.push(e)
└─ first event of the task? → #taskTimer = setTimeout(#closeTask, 0)

#closeTask():
events = #taskEvents; #taskEvents = []
events.length === 1 → existing path: #canAddToBatch(e) ? #batch.push(e)
: (#putBatchToUndo(); #batch = [e])
events.length > 1 → #putBatchToUndo(); #batch = events
#debounce()
```

When the first event arrives, the manager can't yet know whether the task will produce more events. So it waits until the task ends before deciding.

`#redoStack` is still cleared as soon as a local event arrives, exactly as today.

### D2. A multi-change step can be continued, but never merges backwards

When a multi-change task ends, it always closes the open batch: earlier typing is never merged into it. Its events then become the open batch. A later single-event task may continue that batch, but only through the existing text rule, which compares against the batch's **last** event.

- After a block-level action (paste of blocks, Enter, conversion) the last event is a block or data event. The text rule never matches those, so the next typing starts a new step.
- After typing over a selection (one task: `TextRemoved` then `TextAdded`), the next keystrokes continue the `TextAdded`. "Replace selection and keep typing" therefore undoes as one step, restoring the selected text. That is how text editors usually behave.

*Alternative considered: seal multi-change steps so that nothing is ever merged into them afterwards.* Rejected. Typing over a selection would undo as "the first character plus the restored selection", and then the rest of the word as a separate step. That is worse than today.

### D3. The end of a task is detected with `setTimeout(0)`

- It runs after the current task and all of its microtasks.
- It works the same in every browser and in Node.
- Jest's fake timers control it.

*Alternative considered: `MessageChannel`, which fires sooner.* Not needed: the extra delay is invisible to users, because undo first records the buffered events (D4). `MessageChannel` is also harder to fake in tests.

### D4. Record buffered events before undo, redo and destroy

- `undo()` and `redo()` call `#closeTask()` before `#putBatchToUndo()`. `#closeTask()` cancels `#taskTimer` and records the buffered events.
- `destroy()` cancels `#taskTimer` as well as the debounce timer.

`undo()` is normally triggered from a later keydown task, so in practice the buffer is already empty. Recording it first covers programmatic `api.document.undo()` called in the same task as the changes.

### D5. Re-applying block events passes a list of blocks

`BlockAddedEvent` and `BlockRemovedEvent` carry one serialized block in `detail.data`. `EditorDocument.insertData`/`removeData` take `BlockNodeInit[]` for a `BlockIndex` and iterate over it. When `#apply` handles an event whose index is a `BlockIndex`, it passes `[event.data]`. Text, data-node and property events are passed through unchanged.

*Alternative considered: let the model accept a single block.* Rejected for this change: it would touch the `model` package and its spec, whereas only the undo manager hands event data back to these methods. If another caller ever needs it, it can move into the model then.

## Alternatives (whole-approach)

- **Explicit `api.document.group(fn)` with a `groupId` on model events.** This was the first draft of this change. Rejected for now:
- It adds public API and requires every tool and plugin author to remember to use it.
- It needs `groupId` on events and changes at 24 places in the model.
- It doesn't fix Enter unless `split` groups its own changes.

It remains the answer if async actions ever need to be one step. It is compatible with this design, because an explicit group would just override task grouping.
- **Move multi-step actions into core methods that group internally.** Rejected: it would pull paste and other plugin logic back into the headless core.

## Risks / Trade-offs

- **[R1] Grouping is implicit.** Two unrelated programmatic changes made in the same task become one step, for example a plugin that edits on `core:ready` while the document is initialized. → Acceptable: it's rare, and one step is usually what's wanted. If it matters, it can be revisited with the explicit API.
- **[R2] Redo still depends on block-construction `DataNodeAddedEvent`s not being recorded.** If `userId` forwarding is ever fixed, they would land in the same task and redo would throw `AlreadyExistingKeyError`. → The spec scenario "Block construction events are not recorded separately" becomes an integration test that fails in that case. Its comment names the proper fix: skip data-node events that are covered by a `BlockAdded` in the same step.
- **[R3] Behaviour change for existing multi-change actions** (Enter, block conversion, inline formatting across inputs if it emits several events in one task). → Intended. The spec scenarios cover Enter, and the proposal states the change.
- **[R4] Timer-based tests.** Existing `UndoRedoManager` tests that dispatch events and immediately call `undo()` still pass, because `undo()` records the buffer first (D4). Tests that inspect batches between events must advance timers. → Use Jest fake timers consistently.
- **[R5] No grouping when collaboration is enabled.** → Documented. `collaboration-manager` can adopt the same per-task buffering later.

## Migration Plan

No API or data migration. Rollback is reverting `UndoRedoManager`.

## Open Questions

None.
35 changes: 35 additions & 0 deletions openspec/changes/undo-group-by-task/proposal.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
## Why

Core's `UndoRedoManager` only merges consecutive text inserts or removals in the same input (within a 500 ms debounce window) into one undo step. Any action that makes several different model changes becomes several undo steps:

- **Enter in the middle of a paragraph** is two steps today. `BlockManager.splitBlock` emits `TextRemoved` and then `BlockAdded`, and `#canAddToBatch` rejects that pair.
- **The upcoming paste** (`clipboard-paste-plain-and-editorjs`) removes the selected text, splits the block and inserts blocks. That would be three or more steps.

From the user's point of view, each of these is a single action. They all have one thing in common: the model changes happen synchronously while the browser handles one input event. Grouping changes by browser task fixes all of them in core, without asking tools or plugins to mark their changes. It adds no public API, no new event fields, and no changes to the model.

## What Changes

- **Group by task.** `UndoRedoManager` buffers the local model events of the current browser task and decides how to record them when the task ends. The task end is detected with `setTimeout(0)`, scheduled when the first event of the task arrives; microtasks, such as `BlockNode`'s deferred `DataNodeAddedEvent`s, run before it.
- **One event in the task** (e.g. a keystroke): recorded exactly as today. It merges into the open step if the existing text-continuation rule allows, otherwise it starts a new step. Typing behaviour does not change.
- **Several events in the task** (e.g. Enter split, paste, block conversion): the open step is closed, and the task's events start a new step together. Typing before the action therefore stays a separate step. Typing after a block-level action starts its own step, because the text rule never continues a block event.
- **`undo()` and `redo()` record the buffer first.** Before acting, they record any events still buffered for the current task, in the same way they already flush the open debounce batch.
- **`destroy()`** also cancels the pending task-end timer and drops the buffered events.
- **Fix: undo and redo of block changes.** `BlockAddedEvent` and `BlockRemovedEvent` carry a single serialized block, but `EditorJSModel.insertData`/`removeData` expect a list of blocks for a `BlockIndex`. Re-applying any block event therefore throws (`data.forEach is not a function`), so undo can't revert a block insert or removal today. `UndoRedoManager` wraps the block in a one-item list when it re-applies it. Without this fix, grouping Enter into one step would only make it fail in one step.
- **Behaviour change (not an API break):** actions that make several model changes in one task, which undo in several steps today, now undo in one. That is the intended effect.
- **Unchanged:** remote events are still ignored, events produced while undo/redo replays are still ignored, and the 500 ms debounce for typing stays.

## Capabilities

### New Capabilities
<!-- none -->

### Modified Capabilities
- `core`: the "Local undo/redo" requirement now groups the local changes of one browser task into one undo step. The new scenarios cover Enter, multi-change tasks around typing, and undo while events are still buffered.

## Impact

- **Code:** `packages/core/src/components/UndoRedoManager.ts` and its `.spec.ts`, plus an integration test with a real model and `BlocksManager`. No other package changes, and no public API changes.
- **Collaboration:** `collaboration-manager` keeps its own undo manager, which takes over `core:undo`/`core:redo` when it is registered. That manager is not changed here, so multi-change actions still undo in several steps when collaboration is enabled. It can adopt the same per-task rule later, without any new event fields.
- **Not covered:** asynchronous actions, such as a file paste that waits for an upload, which span several tasks and cannot be grouped this way. If they ever need to be one step, an explicit `api.document.group(fn)` can be added then (see `design.md`, "Alternatives").
- **Docs:** `docs/diagrams/undo-redo-flow.mmd` (core grouping by task), `docs/collaboration.md` (note that collaboration undo does not group by task yet). Nothing in `docs/` is superseded.
- **Follow-up:** `clipboard-paste-plain-and-editorjs` relies on this behaviour for "a paste is one undo step". It needs no API from this change.
76 changes: 76 additions & 0 deletions openspec/changes/undo-group-by-task/specs/core/spec.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
## MODIFIED Requirements

### Requirement: Local undo/redo
The system SHALL provide `UndoRedoManager`, which batches consecutive model events (debounced) into a single undo step, inverts `Added`/`Removed`/`Modified` events on `undo()`, and responds to cancellable `core:undo`/`core:redo` events. Local events SHALL be grouped by the browser task in which they were dispatched. When a task produced exactly one local event, that event is batched by the existing rule (consecutive text insert/remove in the same input). When a task produced more than one local event, the open batch is closed and the task's events start a new batch together.

#### Scenario: In-progress batch flushed before undo
- **GIVEN** an undo step is mid-batch when `undo()` is triggered
- **WHEN** the undo is processed
- **THEN** the in-progress batch is flushed first, and the manager ignores model events it triggers itself while replaying the undo

#### Scenario: Cancellable undo/redo events
- **GIVEN** a listener calls `preventDefault()` (or equivalent cancellation) on a `core:undo`/`core:redo` event
- **WHEN** the event is dispatched
- **THEN** the default undo/redo behavior is suppressed

#### Scenario: Several changes in one task are one undo step
- **GIVEN** the local user's action makes several model changes synchronously in one task, for example removing text, splitting a block and inserting blocks
- **WHEN** the task has ended and `undo()` is called once
- **THEN** every change made in that task is reverted, and the document equals its state before the task

#### Scenario: Redo re-applies the whole task
- **GIVEN** a multi-change task's step has just been undone
- **WHEN** `redo()` is called once
- **THEN** every change of that task is re-applied without errors, and the document equals its state right after the task

#### Scenario: Splitting a block with Enter is one undo step
- **GIVEN** the caret is in the middle of a paragraph and the user presses Enter, which splits the block
- **WHEN** `undo()` is called once
- **THEN** the paragraph is restored to its single-block state, with no intermediate step that has only the text removed

#### Scenario: Typing keeps its current batching
- **GIVEN** the local user types several characters, each keystroke in its own task, within the debounce window
- **WHEN** `undo()` is called once
- **THEN** all of those characters are removed together, as before this change

#### Scenario: Earlier typing stays a separate step
- **GIVEN** the local user typed text less than 500 ms before a task that makes several changes, so that text is still in the open batch
- **WHEN** that task ends and `undo()` is later called once
- **THEN** only the task's changes are reverted, and the typed text stays

#### Scenario: Typing after a block-level action starts a new step
- **GIVEN** a task that made several changes and ended with a block change (for example `BlockAdded`) has just finished
- **WHEN** the local user types text within 500 ms and `undo()` is called once
- **THEN** only the typed text is reverted, and the earlier task's changes stay

#### Scenario: Consecutive multi-change tasks are separate steps
- **GIVEN** two tasks run one after the other, each making several changes
- **WHEN** `undo()` is called once
- **THEN** only the second task's changes are reverted

#### Scenario: Undo before the current task has ended
- **GIVEN** local events of the current task are still buffered because the task has not ended
- **WHEN** `undo()` is called
- **THEN** the buffered events are recorded first, following the same one-event and several-event rules, and the most recent step is then undone

#### Scenario: Block construction events are not recorded separately
- **GIVEN** a block with text data is added as part of a multi-change task
- **WHEN** that task is undone and then redone
- **THEN** the block is removed and re-added with its data exactly once, with no `AlreadyExistingKeyError`, because the microtask-dispatched `DataNodeAddedEvent`s from block construction are not recorded as undoable changes

#### Scenario: Undoing and redoing a block change
- **GIVEN** a recorded step contains a `BlockAddedEvent` or `BlockRemovedEvent`, whose `data` is a single serialized block
- **WHEN** the step is undone or redone
- **THEN** the manager calls the model's `insertData`/`removeData` with that block wrapped in a one-item list, as the model expects for a `BlockIndex`, and the block is removed or restored without errors

#### Scenario: Remote events do not join a local task
- **GIVEN** a remote user's event arrives while local events of the current task are buffered
- **WHEN** the manager handles it
- **THEN** the event is ignored, as for any remote event, and the local task's grouping is unaffected

#### Scenario: Destroy cancels pending timers
- **GIVEN** a task-end timer or a debounce timer is pending
- **WHEN** `destroy()` is called
- **THEN** both timers are cleared, and no step is recorded afterwards

Implemented in `src/components/UndoRedoManager.ts`, validated by its co-located `.spec.ts` and an integration test through `Core`.
34 changes: 34 additions & 0 deletions openspec/changes/undo-group-by-task/tasks.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
## 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:
- 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
- should keep typing before a multi-change task as a separate step
- should start a new step for typing after a task that ended with a block change
- should merge typing that continues a replace-selection task into its step
- should keep consecutive multi-change tasks as separate steps
- should record buffered events before undo when the task has not ended
- should ignore remote events while a task is buffered
- should clear the task timer and the debounce timer on destroy

## 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`

## 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)

## 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
Loading