From 917a89e7400430236856f3552ff75204bb7dbee2 Mon Sep 17 00:00:00 2001 From: Ilya Maroz <37909603+ilyamore88@users.noreply.github.com> Date: Sat, 10 Oct 2026 12:48:57 +0100 Subject: [PATCH 1/3] docs(openspec): propose undo-grouping change Add the undo-grouping OpenSpec change: api.document.group(fn) and group ids on model events so a multi-operation action (e.g. paste) is a single undo step. Prerequisite for clipboard paste (#137). --- openspec/changes/undo-grouping/.openspec.yaml | 2 + openspec/changes/undo-grouping/design.md | 103 ++++++++++++++++++ openspec/changes/undo-grouping/proposal.md | 41 +++++++ .../changes/undo-grouping/specs/core/spec.md | 71 ++++++++++++ .../undo-grouping/specs/model-types/spec.md | 24 ++++ .../changes/undo-grouping/specs/model/spec.md | 36 ++++++ .../changes/undo-grouping/specs/sdk/spec.md | 16 +++ openspec/changes/undo-grouping/tasks.md | 49 +++++++++ 8 files changed, 342 insertions(+) create mode 100644 openspec/changes/undo-grouping/.openspec.yaml create mode 100644 openspec/changes/undo-grouping/design.md create mode 100644 openspec/changes/undo-grouping/proposal.md create mode 100644 openspec/changes/undo-grouping/specs/core/spec.md create mode 100644 openspec/changes/undo-grouping/specs/model-types/spec.md create mode 100644 openspec/changes/undo-grouping/specs/model/spec.md create mode 100644 openspec/changes/undo-grouping/specs/sdk/spec.md create mode 100644 openspec/changes/undo-grouping/tasks.md diff --git a/openspec/changes/undo-grouping/.openspec.yaml b/openspec/changes/undo-grouping/.openspec.yaml new file mode 100644 index 00000000..29382a2c --- /dev/null +++ b/openspec/changes/undo-grouping/.openspec.yaml @@ -0,0 +1,2 @@ +schema: spec-driven +created: 2026-09-29 diff --git a/openspec/changes/undo-grouping/design.md b/openspec/changes/undo-grouping/design.md new file mode 100644 index 00000000..a4987203 --- /dev/null +++ b/openspec/changes/undo-grouping/design.md @@ -0,0 +1,103 @@ +## Context + +Core's `UndoRedoManager` (`packages/core/src/components/UndoRedoManager.ts`) listens to `EventType.Changed` on `EditorJSModel`. It ignores events whose `detail.userId` isn't the local user. It collects the rest into `#batch` and moves the batch onto `#undoStack` either after 500 ms without new events, or when `#canAddToBatch` rejects the next event. `#canAddToBatch` accepts only a text insert or remove that directly continues the previous one in the same `blockIndex`/`dataKey`. An undo step is already a list of events, and `undo()`/`redo()` replay the whole list. So the only thing preventing a multi-operation action from being a single step is the batching rule. + +How the model attributes events: + +- `utils/Context.ts` keeps a module-level stack. `@WithContext` pushes each `EditorJSModel` method's first argument (the `userId`) onto it for the duration of the call. +- Event-creation sites read `getContext()` (21 sites across `EditorDocument`, `BlockNode`, `BlockTune`, `ValueNode`, `ParentInlineNode` and `EditorJSModel`). +- Events are **re-created** at each bubbling level: + - `BlockNode` for text, value and tune events; + - `EditorDocument.#listenAndBubbleBlockEvent`, which passes only `(index, data)`; + - `EditorJSModel.#listenAndBubbleDocumentEvents`, which passes `(index, data, getContext())`. + So any payload field has to be forwarded explicitly at each level, or it is lost. +- `BlockNode.#initialize` → `createDataNode` queues each `DataNodeAddedEvent` in a `queueMicrotask`. By the time it reaches `EditorJSModel`, the context stack has been popped, so its `userId` is `undefined`. Core's undo manager therefore never records these events. That is correct for undo, because the preceding `BlockAddedEvent` already carries the block's full serialized data. Recording both would make redo re-create data nodes that already exist and throw `AlreadyExistingKeyError`. + +`collaboration-manager` has its own undo manager, which takes over `core:undo`/`core:redo` when it is registered. It is out of scope here (see Non-Goals). + +## Goals / Non-Goals + +**Goals:** +- `api.document.group(fn)`: synchronous, returns `fn`'s result, re-throws its error, and nested calls join the outer group. +- All local changes made inside a group are one undo step, kept separate from the steps before and after it. +- The group id is captured when an event is created, so it is correct even for events dispatched in a microtask. +- Undo and redo of a group work without errors, including groups that add blocks. +- Ungrouped behaviour is unchanged. + +**Non-Goals:** +- Grouping in `collaboration-manager`'s undo manager. Grouped actions still undo in several steps when collaboration is enabled. That manager can later adopt the same batching rule using `groupId`. +- Fixing `userId` loss for microtask-dispatched events, or making the exclusion of block-construction `DataNodeAddedEvent`s explicit. The current behaviour is pinned by a test. +- Asynchronous groups (an `fn` that returns a promise, or changes made after an `await`). +- Sending `groupId` to the OT server or including it in serialized operations. + +## Decisions + +### D1. Batching by id, driven only by events (no open/close signal) + +`#canAddToBatch(payload)` gains one rule, checked before the existing ones: + +``` +if (payload.groupId !== undefined || lastEvent.groupId !== undefined) { + return payload.groupId === lastEvent.groupId; +} +// …existing text-continuation rule, unchanged +``` + +With this rule: + +- **Earlier typing is closed off.** The group's first event has an id the open, ungrouped batch doesn't have, so the batch is moved to the stack. +- **Later typing is closed off.** The first ungrouped event after the group doesn't match, so the group's batch is moved to the stack. +- **Consecutive groups stay separate**, because their ids differ. + +The debounce is unchanged. A group's events are all dispatched synchronously, plus any microtasks that follow immediately, so they fit well inside the 500 ms window. + +*Alternative considered:* `DocumentAPI.group` calls `UndoRedoManager.beginGroup()`/`endGroup()` around `fn`. This was rejected for three reasons: +- It couples the API layer to the undo implementation. +- It would bypass `collaboration-manager`, which can't see those calls but can see event payloads. +- It still needs the id to place microtask events correctly. + +With the event-driven rule, `UndoRedoManager` needs no new public API. + +### D2. A separate group stack in `utils/Context.ts` + +Add `runInGroup(fn)` and `getGroupId()`, backed by a second module-level stack, alongside the existing `userId` stack: + +- `runInGroup` pushes a new id when the stack is empty, and pushes the current top when a group is already open, so nested calls reuse the outer id. +- It pops in `finally`, so a throw still closes the group. +- Ids come from a module-level counter (`'g1'`, `'g2'`, …). They only need to be unique within one JS realm for local undo. They are never serialized. + +`EditorJSModel.group(fn: () => T): T` wraps `runInGroup`. It is **not** decorated with `@WithContext`, because it takes no `userId`. The model calls inside `fn` still push their own `userId` as they do today. + +*Alternative considered:* change the context value from `userId` to `{ userId, groupId }`. Rejected: it changes the meaning of every `getContext()` call site and every `@WithContext` method, which is wider than necessary. A separate stack is an additive change. + +### D3. Capture at creation, forward on re-dispatch + +- `BaseDocumentEvent` and every concrete event constructor take an optional trailing `groupId?: string`, stored in `detail.groupId`. +- **Creation sites** (the 21 `getContext()` reads) also pass `getGroupId()`. `BlockNode.createDataNode` reads it **before** `queueMicrotask`, next to the existing `userId` capture. +- **Re-dispatch sites** pass `event.detail.groupId`, never `getGroupId()`. There are three: + - `BlockNode` bubbling for text, value and tune events; + - `EditorDocument.#listenAndBubbleBlockEvent`; + - `EditorJSModel.#listenAndBubbleDocumentEvents`. + The id always comes from where the event was created, never from where it is re-dispatched. This is what makes microtask events come out right. + +`userId` handling at the re-dispatch sites is left unchanged (see the Non-Goals and R2). + +### D4. `DocumentAPI.group` delegates to the model + +The core `DocumentAPI` already holds `EditorJSModel`. `group(fn)` returns `this.#model.group(fn)`. The SDK interface gets the matching signature. No change to `EventBus`. + +## Risks / Trade-offs + +- **[R1] A group event arriving after the debounce flushed the batch starts a new step.** It would need a local, grouped event dispatched more than 500 ms after the group. Nothing produces that today, since microtasks run immediately. → Accepted. If async groups are ever added, revisit with "append to the top step when its `groupId` matches". +- **[R2] Block-construction `DataNodeAddedEvent`s are kept out of undo only because they lose their `userId`.** If someone fixes `userId` forwarding in `EditorJSModel`, these events would start being recorded, and redo would throw. → The core spec scenario "Block construction events are not recorded separately" becomes a test that fails in that case. The test's comment will point to the proper fix: skip events for data that a `BlockAdded` in the same step already covers. +- **[R3] 21 creation sites plus 3 re-dispatch sites to update.** A missed creation site silently produces `groupId: undefined` in the middle of a group, which would split the step. → An integration test runs a group covering every kind of mutation (text insert/remove/format, value modify, data node add/remove, block add/remove, tune modify) and asserts that every dispatched event carries the group's id. +- **[R4] Collaboration users don't get grouping.** → Documented in the proposal. `groupId` is on the event, so extending `collaboration-manager` later is a contained change. +- **[R5] A module-level group stack is shared by all model instances in one realm.** It behaves the same way as the existing `userId` stack. Group ids stay unique because the counter is global, and nesting across instances within one synchronous call is harmless. → Accepted. + +## Migration Plan + +Additive only. `groupId` is optional on events, constructors take it as an optional last argument, and `DocumentAPI.group` is a new method. Third-party `DocumentAPI` implementations, if any exist, would need to add `group`. Rollback is reverting the change; no data or format migration is involved. + +## Open Questions + +- Should `group` be available through `api.document` only, or also through `BlocksAPI` helpers such as `split` (i.e. should `split` group itself)? This design keeps it on `api.document` only. The paste change will wrap its whole sequence of calls in one `group`. diff --git a/openspec/changes/undo-grouping/proposal.md b/openspec/changes/undo-grouping/proposal.md new file mode 100644 index 00000000..9497d94d --- /dev/null +++ b/openspec/changes/undo-grouping/proposal.md @@ -0,0 +1,41 @@ +## Why + +Core's `UndoRedoManager` only groups consecutive text inserts or removals in the same input, within a 500 ms debounce window. Any action that makes several kinds of model change becomes several undo steps. A paste, for example, removes the selected text, splits the block, and inserts blocks. The upcoming paste change (`clipboard-paste-plain-and-editorjs`) needs a whole paste to undo with one Ctrl+Z. Cut, drop and block conversion will need the same, so it belongs in core as a general primitive, not inside the paste code. + +## What Changes + +- Add `api.document.group(fn)` to the SDK `DocumentAPI` contract and implement it in core. Model changes made synchronously inside `fn` by the local user form exactly one undo step: + - Any in-progress debounce batch is closed before the group opens, so earlier typing stays a separate step. + - The group's step is closed when `fn` returns, so later typing starts a new step. + - Nested `group()` calls join the outermost group. + - If `fn` throws, the group still closes and the error is re-thrown. +- The model carries a **group id** on every document event. It is captured synchronously when the event is created and kept as the event bubbles up the model tree (`BlockNode` → `EditorDocument` → `EditorJSModel`). This includes events dispatched later in a microtask, such as the `DataNodeAddedEvent`s `BlockNode` emits during construction. +- `EditorJSModel` gets a way to run a function inside a group context (a new group id, or the enclosing one when nested). +- `EventPayloadBase` gains an optional `groupId` field. The change is additive; events created outside a group leave it `undefined`. +- `UndoRedoManager` groups by id. A local event carrying a group id joins the current batch only if the batch has the same group id. Otherwise the batch is closed and a new one starts. An event without a group id never joins a grouped batch. Ungrouped events keep today's batching exactly. As a result, the group's step is closed before and after the group with no extra signals between core and the model. +- Record one fact the change depends on: `DataNodeAddedEvent`s that `BlockNode` fires in a microtask while it is being constructed reach `EditorJSModel` with no `userId`, because the re-wrap reads `getContext()` after the context has been popped. Core's `UndoRedoManager` therefore never records them. This is correct for undo: the preceding `BlockAddedEvent` already holds the block's data, and recording both would break redo with `AlreadyExistingKeyError`. This change adds a test that pins the behaviour (a grouped block insert undoes and redoes cleanly) and records it in the design. Making the exclusion explicit, instead of a side effect of the missing `userId`, is left for later. + +## Capabilities + +### New Capabilities + + +### Modified Capabilities +- `core`: "Local undo/redo" batches by group id: a group's events form one step, closed off from the changes before and after it. "EditorAPI surface" lists `DocumentAPI.group`. +- `sdk`: new requirement "Grouped document changes" for the `group(fn)` contract on `DocumentAPI`. +- `model`: new requirement "Grouped mutations": `EditorJSModel` can run a function inside a group context, and document events carry the group id that was active when they were created, including events dispatched in a microtask, and keep it while bubbling. +- `model-types`: "Base document event and event bus" adds the optional `groupId` field to `EventPayloadBase` and the `BaseDocumentEvent` constructor. + +## Impact + +- **Packages**: + - `model-types`: event payload and base event. + - `model`: the context utilities in `utils/Context.ts`, every event-creation site that reads `getContext()` (21 sites), and the bubbling re-wraps in `BlockNode`, `EditorDocument` and `EditorJSModel`. + - `sdk`: the `DocumentAPI` interface. + - `core`: `DocumentAPI` and `UndoRedoManager`. `UndoRedoManager` only changes its batching rule; no new calls from `DocumentAPI` into it. +- **API**: additive only. There are no **BREAKING** changes. Events without a group behave as they do today. +- **Collaboration**: `collaboration-manager` keeps its own `UndoRedoManager`, which takes over `core:undo`/`core:redo` when it is registered (see the `architecture` spec). That manager does not read `groupId` in this change, so a grouped action still undoes in several steps when collaboration is enabled. Because the group id is now on every event, supporting it there later only needs a change to that manager. The OT server and operation serialization are unaffected; `groupId` is not sent over the wire. +- **Docs**: + - `docs/diagrams/undo-redo-flow.mmd` and `docs/events.md` (the `BaseDocumentEvent` payload fields) need to show the group id and grouping. + - Nothing in `docs/` is replaced by this change. +- **Follow-up**: `clipboard-paste-plain-and-editorjs` depends on this change. diff --git a/openspec/changes/undo-grouping/specs/core/spec.md b/openspec/changes/undo-grouping/specs/core/spec.md new file mode 100644 index 00000000..7977201f --- /dev/null +++ b/openspec/changes/undo-grouping/specs/core/spec.md @@ -0,0 +1,71 @@ +## MODIFIED Requirements + +### Requirement: EditorAPI surface +The system SHALL expose an `EditorAPI` aggregating `BlocksAPI` (insert/insertMany/delete/move/render/clear/getBlocksCount), `SelectionAPI` (applyInlineTool, selectedBlocks), `DocumentAPI` (serialized data, onUpdate, insertData/removeData/modifyData, undo/redo, group), and `TextAPI` (insert/remove/format/unformat/getFragments/get) to tools, plugins, and adapters. + +#### Scenario: Deleting with no block selected +- **GIVEN** no block is currently selected/no caret is set +- **WHEN** `BlocksAPI.delete()` or `move()` is called without an explicit index +- **THEN** it throws an error ("No block selected to delete" / "No block selected to move") + +#### Scenario: Splitting or converting with an unknown tool +- **GIVEN** a `splitBlock`/`convertBlock` call references a `dataKey` that doesn't exist, or a source/target tool that isn't registered +- **WHEN** the operation is attempted +- **THEN** it throws an error identifying the missing key or tool + +#### Scenario: Grouping delegates to the model +- **GIVEN** a caller invokes `DocumentAPI.group(fn)` +- **WHEN** the call runs +- **THEN** `fn` is executed inside the model's group context (`EditorJSModel.group`), and its return value or thrown error is passed back to the caller + +Implemented in `src/api/index.ts`, `src/api/BlocksAPI.ts`, `src/api/SelectionAPI.ts`, `src/api/DocumentAPI/DocumentAPI.ts`, `src/api/TextAPI.ts`, `src/components/BlockManager.ts`, validated by co-located `.spec.ts`/`.integration.spec.ts` files. + +### 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. Batching SHALL respect group ids: an event with a `groupId` joins the current batch only if the batch has the same `groupId`, and an event without one never joins a grouped batch. Ungrouped events are batched by the existing rule (consecutive text insert/remove in the same input). + +#### 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: A group is one undo step +- **GIVEN** the local user runs `api.document.group(fn)`, where `fn` removes text, splits a block and inserts several blocks +- **WHEN** `undo()` is called once +- **THEN** every change made inside `fn` is reverted, and the document equals its state before `group` was called + +#### Scenario: Redo re-applies the whole group +- **GIVEN** a grouped step has just been undone +- **WHEN** `redo()` is called once +- **THEN** every change of the group is re-applied, without errors, and the document equals its state right after `group` returned + +#### Scenario: Earlier typing stays a separate step +- **GIVEN** the local user typed text less than 500 ms before a group starts, so that text is still in the open batch +- **WHEN** the group's first event arrives and `undo()` is later called once +- **THEN** only the group's changes are reverted, and the typed text stays + +#### Scenario: Later typing starts a new step +- **GIVEN** a group 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 group's changes stay + +#### Scenario: Consecutive groups are separate steps +- **GIVEN** two `api.document.group` calls run one after the other +- **WHEN** `undo()` is called once +- **THEN** only the second group's changes are reverted + +#### Scenario: Block construction events are not recorded separately +- **GIVEN** a block with text data is added inside a group +- **WHEN** the group 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: Remote events do not join a local group +- **GIVEN** a remote user's event arrives while a local group's batch is open +- **WHEN** the manager handles it +- **THEN** the event is ignored, as for any remote event, and the local group's step is unaffected + +Implemented in `src/components/UndoRedoManager.ts`, validated by its co-located `.spec.ts`. diff --git a/openspec/changes/undo-grouping/specs/model-types/spec.md b/openspec/changes/undo-grouping/specs/model-types/spec.md new file mode 100644 index 00000000..e046afee --- /dev/null +++ b/openspec/changes/undo-grouping/specs/model-types/spec.md @@ -0,0 +1,24 @@ +## MODIFIED Requirements + +### Requirement: Base document event and event bus +The system SHALL provide a `BaseDocumentEvent` base class carrying `{ index, action, data, userId, groupId }` that fires under the `EventType.Changed` DOM event type, concrete event subclasses for each kind of document mutation (block/data/text add/remove/modify, tune/property modification), and a thin `EventBus` (`EventTarget` subclass) used to dispatch them. `groupId` is optional: it identifies the group of changes the mutation belongs to, and is `undefined` for mutations made outside a group. + +#### Scenario: Emitting a document mutation event +- **GIVEN** a block, text, or value node is added, removed, or modified +- **THEN** the corresponding concrete event (e.g. `DataNodeAddedEvent`, `TextFormattedEvent`, `BlockAddedEvent`, `PropertyModifiedEvent`, `TuneModifiedEvent`) is dispatched as `EventType.Changed`, carrying an `EventAction` (`Added`/`Removed`/`Modified`) and the affected `Index` + +#### Scenario: Carrying a group id +- **GIVEN** a concrete document event is constructed with a group id argument +- **WHEN** a listener reads the event's `detail` +- **THEN** `detail.groupId` equals the id that was passed + +#### Scenario: Event created without a group id +- **GIVEN** a concrete document event is constructed without a group id argument +- **WHEN** a listener reads the event's `detail` +- **THEN** `detail.groupId` is `undefined`, and every other field is the same as before this field existed + +#### Scenario: Emitting a caret event +- **GIVEN** a caret is added, removed, or updated +- **THEN** the corresponding caret event (`CaretManagerCaretAddedEvent`, `CaretManagerCaretRemovedEvent`, `CaretManagerCaretUpdatedEvent`) is dispatched as `EventType.CaretManagerUpdated`, carrying the serialized `Caret` + +Implemented in `src/BaseDocumentEvent.ts`, `src/EventBus.ts`, `src/EventType.ts`, `src/EventAction.ts`, `src/EventMap.ts`, `src/events/*`. diff --git a/openspec/changes/undo-grouping/specs/model/spec.md b/openspec/changes/undo-grouping/specs/model/spec.md new file mode 100644 index 00000000..154a38eb --- /dev/null +++ b/openspec/changes/undo-grouping/specs/model/spec.md @@ -0,0 +1,36 @@ +## ADDED Requirements + +### Requirement: Grouped mutations +`EditorJSModel` SHALL provide `group(fn)`, which runs `fn` synchronously inside a group context and returns its result. Every document event created while the context is active SHALL carry that group's id in `detail.groupId`. The id is captured when the event is created and kept unchanged as the event is re-dispatched by `BlockNode`, `EditorDocument` and `EditorJSModel`. Events created outside any group SHALL carry `groupId: undefined`. + +#### Scenario: Mutations inside a group share one id +- **GIVEN** `model.group(fn)` is called +- **WHEN** `fn` inserts text, splits a block and adds blocks +- **THEN** every `EventType.Changed` event the model dispatches for those mutations carries the same, defined `groupId` + +#### Scenario: Separate groups get different ids +- **GIVEN** `model.group(fnA)` completes +- **WHEN** `model.group(fnB)` is called afterwards +- **THEN** the events of `fnB` carry a `groupId` different from the events of `fnA` + +#### Scenario: Nested groups join the outer group +- **GIVEN** `model.group(outer)` is running +- **WHEN** `outer` calls `model.group(inner)` +- **THEN** the events created inside `inner` carry the same `groupId` as the events created directly inside `outer` + +#### Scenario: Group id survives microtask-deferred dispatch +- **GIVEN** a block is added inside `model.group(fn)`, and `BlockNode` queues its `DataNodeAddedEvent`s in a microtask +- **WHEN** those events are dispatched after `fn` has returned +- **THEN** they carry the `groupId` that was active when the block was constructed + +#### Scenario: Group context closes on throw +- **GIVEN** `fn` throws inside `model.group(fn)` +- **WHEN** the error propagates out of `group` +- **THEN** the group context is no longer active, so events created afterwards carry `groupId: undefined` + +#### Scenario: Mutations outside a group +- **GIVEN** no group is active +- **WHEN** any mutation is made +- **THEN** its events carry `groupId: undefined` + +Implemented in `src/EditorJSModel.ts` and `src/utils/Context.ts`, with ids captured at the event-creation sites in `src/entities/**`, validated by `src/EditorJSModel.spec.ts` and `src/EditorJSModel.integration.spec.ts`. diff --git a/openspec/changes/undo-grouping/specs/sdk/spec.md b/openspec/changes/undo-grouping/specs/sdk/spec.md new file mode 100644 index 00000000..f99f49db --- /dev/null +++ b/openspec/changes/undo-grouping/specs/sdk/spec.md @@ -0,0 +1,16 @@ +## ADDED Requirements + +### Requirement: Grouped document changes +The `DocumentAPI` contract SHALL declare `group(fn: () => T): T`, which runs `fn` synchronously and returns its result. All document changes that `fn` makes through the `EditorAPI` are treated as one unit of history: a single undo step. + +#### Scenario: Plugin groups a multi-operation action +- **GIVEN** a plugin holds an `EditorAPI` +- **WHEN** it calls `api.document.group(() => { api.blocks.split(...); api.blocks.insertMany(...); })` +- **THEN** the call type-checks and returns the callback's return value + +#### Scenario: Errors propagate +- **GIVEN** the callback passed to `api.document.group` throws +- **WHEN** `group` is called +- **THEN** the same error is re-thrown to the caller + +Implemented in `src/api/DocumentAPI.ts`. diff --git a/openspec/changes/undo-grouping/tasks.md b/openspec/changes/undo-grouping/tasks.md new file mode 100644 index 00000000..b7b145a8 --- /dev/null +++ b/openspec/changes/undo-grouping/tasks.md @@ -0,0 +1,49 @@ +## 1. model-types: groupId on events + +- [ ] 1.1 Write failing tests in `packages/model-types`: "should expose detail.groupId when constructed with a group id" and "should leave detail.groupId undefined when constructed without one", for `BaseDocumentEvent` and one concrete event (e.g. `TextAddedEvent`) +- [ ] 1.2 Add optional `groupId?: string` to `EventPayloadBase`, and an optional trailing `groupId` parameter to `BaseDocumentEvent` and every concrete event in `src/events/*`, forwarded to `super` +- [ ] 1.3 Run `yarn test` and `yarn lint` in `packages/model-types` + +## 2. model: group context + +- [ ] 2.1 Write failing tests for `utils/Context.ts`: "should return undefined from getGroupId outside a group", "should return the same id for nested runInGroup calls", "should return different ids for consecutive groups", "should close the group when fn throws" +- [ ] 2.2 Implement the group stack, `runInGroup(fn)` and `getGroupId()` in `packages/model/src/utils/Context.ts` (counter-based ids, nested calls reuse the outer id, pop in `finally`) +- [ ] 2.3 Write failing `EditorJSModel.spec.ts` tests for `group(fn)`: returns `fn`'s result, re-throws its error +- [ ] 2.4 Add `EditorJSModel.group(fn: () => T): T` wrapping `runInGroup` (without `@WithContext`) + +## 3. model: capture and forward the group id + +- [ ] 3.1 Write a failing integration test in `EditorJSModel.integration.spec.ts`: "should tag every event with the active group id", running one group that covers text insert/remove/format/unformat, value modify, data node add/remove, block add/remove and tune modify, and asserting that every `EventType.Changed` event (including ones dispatched in microtasks) carries the group's id +- [ ] 3.2 Write a failing integration test: "should keep the group id on DataNodeAddedEvents dispatched in a microtask after the group returned" +- [ ] 3.3 Write a failing integration test: "should leave groupId undefined for mutations outside a group" +- [ ] 3.4 Pass `getGroupId()` at every event-creation site that reads `getContext()` (`EditorDocument`, `BlockNode`, `BlockTune`, `ValueNode`, `ParentInlineNode`, `EditorJSModel`). In `BlockNode.createDataNode`, capture it before `queueMicrotask` +- [ ] 3.5 Forward `event.detail.groupId` at the three re-dispatch sites: `BlockNode` bubbling for text, value and tune events, `EditorDocument.#listenAndBubbleBlockEvent`, and `EditorJSModel.#listenAndBubbleDocumentEvents` +- [ ] 3.6 Run `yarn test`, `yarn lint` and `yarn test:mutations` (if configured) in `packages/model` + +## 4. sdk: DocumentAPI contract + +- [ ] 4.1 Add `group(fn: () => T): T` with TSDoc to `packages/sdk/src/api/DocumentAPI.ts` +- [ ] 4.2 Update any SDK mocks/stubs of `DocumentAPI` so that `yarn test` and `yarn lint` pass in `packages/sdk` + +## 5. core: DocumentAPI.group and batching by group id + +- [ ] 5.1 Write failing `DocumentAPI` tests: "should run fn inside model.group and return its result", "should re-throw errors from fn" +- [ ] 5.2 Implement `DocumentAPI.group` in `packages/core/src/api/DocumentAPI/DocumentAPI.ts` by delegating to `EditorJSModel.group` +- [ ] 5.3 Write failing `UndoRedoManager.spec.ts` tests matching the core spec scenarios: + - should undo a whole group in one step + - should redo a whole group in one step + - should keep earlier typing as a separate step + - should start a new step for typing after a group + - should keep consecutive groups as separate steps + - should ignore remote events during a group +- [ ] 5.4 Add the group-id rule to `#canAddToBatch` in `packages/core/src/components/UndoRedoManager.ts`, checked before the existing text-continuation rule (design D1) +- [ ] 5.5 Write an integration test through `Core`: "should undo and redo a grouped block insert without AlreadyExistingKeyError", covering design R2. Its comment should explain why block-construction `DataNodeAddedEvent`s must stay out of undo +- [ ] 5.6 Add an integration test that pins current behaviour: an ungrouped `blocks.split` still produces its current number of undo steps +- [ ] 5.7 Run `yarn test`, `yarn lint` and `yarn test:mutations` (if configured) in `packages/core` + +## 6. Docs and wrap-up + +- [ ] 6.1 Update `docs/events.md` (add `detail.groupId` to the `BaseDocumentEvent` payload list) and `docs/diagrams/undo-redo-flow.mmd` (add a grouped-action sequence to the core undo manager) +- [ ] 6.2 Note in `docs/collaboration.md` that `collaboration-manager` undo does not yet honour `groupId` +- [ ] 6.3 Run `yarn lint` and `yarn test` from the repo root +- [ ] 6.4 Run `openspec validate undo-grouping --type change` and fix any issues From c721d4ca9b75a9041b928efe100c97925000a234 Mon Sep 17 00:00:00 2001 From: Ilya Maroz <37909603+ilyamore88@users.noreply.github.com> Date: Sat, 10 Oct 2026 13:00:23 +0100 Subject: [PATCH 2/3] docs(openspec): rework undo grouping proposal to group by browser task Replace the explicit api.document.group(fn) + groupId design with implicit grouping in core's UndoRedoManager: local events of one browser task are buffered and become one undo step when the task made several changes. No public API, no model or event-payload changes. Rename the change to undo-group-by-task. --- .../.openspec.yaml | 0 openspec/changes/undo-group-by-task/design.md | 94 ++++++++++++++++ .../changes/undo-group-by-task/proposal.md | 34 ++++++ .../undo-group-by-task/specs/core/spec.md | 71 ++++++++++++ openspec/changes/undo-group-by-task/tasks.md | 33 ++++++ openspec/changes/undo-grouping/design.md | 103 ------------------ openspec/changes/undo-grouping/proposal.md | 41 ------- .../changes/undo-grouping/specs/core/spec.md | 71 ------------ .../undo-grouping/specs/model-types/spec.md | 24 ---- .../changes/undo-grouping/specs/model/spec.md | 36 ------ .../changes/undo-grouping/specs/sdk/spec.md | 16 --- openspec/changes/undo-grouping/tasks.md | 49 --------- 12 files changed, 232 insertions(+), 340 deletions(-) rename openspec/changes/{undo-grouping => undo-group-by-task}/.openspec.yaml (100%) create mode 100644 openspec/changes/undo-group-by-task/design.md create mode 100644 openspec/changes/undo-group-by-task/proposal.md create mode 100644 openspec/changes/undo-group-by-task/specs/core/spec.md create mode 100644 openspec/changes/undo-group-by-task/tasks.md delete mode 100644 openspec/changes/undo-grouping/design.md delete mode 100644 openspec/changes/undo-grouping/proposal.md delete mode 100644 openspec/changes/undo-grouping/specs/core/spec.md delete mode 100644 openspec/changes/undo-grouping/specs/model-types/spec.md delete mode 100644 openspec/changes/undo-grouping/specs/model/spec.md delete mode 100644 openspec/changes/undo-grouping/specs/sdk/spec.md delete mode 100644 openspec/changes/undo-grouping/tasks.md diff --git a/openspec/changes/undo-grouping/.openspec.yaml b/openspec/changes/undo-group-by-task/.openspec.yaml similarity index 100% rename from openspec/changes/undo-grouping/.openspec.yaml rename to openspec/changes/undo-group-by-task/.openspec.yaml diff --git a/openspec/changes/undo-group-by-task/design.md b/openspec/changes/undo-group-by-task/design.md new file mode 100644 index 00000000..1aa018ff --- /dev/null +++ b/openspec/changes/undo-group-by-task/design.md @@ -0,0 +1,94 @@ +## 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. + +## 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. diff --git a/openspec/changes/undo-group-by-task/proposal.md b/openspec/changes/undo-group-by-task/proposal.md new file mode 100644 index 00000000..ef9866d8 --- /dev/null +++ b/openspec/changes/undo-group-by-task/proposal.md @@ -0,0 +1,34 @@ +## 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. +- **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 + + +### 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 one integration test through `Core`. 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. diff --git a/openspec/changes/undo-group-by-task/specs/core/spec.md b/openspec/changes/undo-group-by-task/specs/core/spec.md new file mode 100644 index 00000000..43dc34f2 --- /dev/null +++ b/openspec/changes/undo-group-by-task/specs/core/spec.md @@ -0,0 +1,71 @@ +## 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: 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`. diff --git a/openspec/changes/undo-group-by-task/tasks.md b/openspec/changes/undo-group-by-task/tasks.md new file mode 100644 index 00000000..6f9ad6dd --- /dev/null +++ b/openspec/changes/undo-group-by-task/tasks.md @@ -0,0 +1,33 @@ +## 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 Run `yarn test`, `yarn lint` and `yarn test:mutations` (if configured) in `packages/core` + +## 3. Integration tests through Core + +- [ ] 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 diff --git a/openspec/changes/undo-grouping/design.md b/openspec/changes/undo-grouping/design.md deleted file mode 100644 index a4987203..00000000 --- a/openspec/changes/undo-grouping/design.md +++ /dev/null @@ -1,103 +0,0 @@ -## Context - -Core's `UndoRedoManager` (`packages/core/src/components/UndoRedoManager.ts`) listens to `EventType.Changed` on `EditorJSModel`. It ignores events whose `detail.userId` isn't the local user. It collects the rest into `#batch` and moves the batch onto `#undoStack` either after 500 ms without new events, or when `#canAddToBatch` rejects the next event. `#canAddToBatch` accepts only a text insert or remove that directly continues the previous one in the same `blockIndex`/`dataKey`. An undo step is already a list of events, and `undo()`/`redo()` replay the whole list. So the only thing preventing a multi-operation action from being a single step is the batching rule. - -How the model attributes events: - -- `utils/Context.ts` keeps a module-level stack. `@WithContext` pushes each `EditorJSModel` method's first argument (the `userId`) onto it for the duration of the call. -- Event-creation sites read `getContext()` (21 sites across `EditorDocument`, `BlockNode`, `BlockTune`, `ValueNode`, `ParentInlineNode` and `EditorJSModel`). -- Events are **re-created** at each bubbling level: - - `BlockNode` for text, value and tune events; - - `EditorDocument.#listenAndBubbleBlockEvent`, which passes only `(index, data)`; - - `EditorJSModel.#listenAndBubbleDocumentEvents`, which passes `(index, data, getContext())`. - So any payload field has to be forwarded explicitly at each level, or it is lost. -- `BlockNode.#initialize` → `createDataNode` queues each `DataNodeAddedEvent` in a `queueMicrotask`. By the time it reaches `EditorJSModel`, the context stack has been popped, so its `userId` is `undefined`. Core's undo manager therefore never records these events. That is correct for undo, because the preceding `BlockAddedEvent` already carries the block's full serialized data. Recording both would make redo re-create data nodes that already exist and throw `AlreadyExistingKeyError`. - -`collaboration-manager` has its own undo manager, which takes over `core:undo`/`core:redo` when it is registered. It is out of scope here (see Non-Goals). - -## Goals / Non-Goals - -**Goals:** -- `api.document.group(fn)`: synchronous, returns `fn`'s result, re-throws its error, and nested calls join the outer group. -- All local changes made inside a group are one undo step, kept separate from the steps before and after it. -- The group id is captured when an event is created, so it is correct even for events dispatched in a microtask. -- Undo and redo of a group work without errors, including groups that add blocks. -- Ungrouped behaviour is unchanged. - -**Non-Goals:** -- Grouping in `collaboration-manager`'s undo manager. Grouped actions still undo in several steps when collaboration is enabled. That manager can later adopt the same batching rule using `groupId`. -- Fixing `userId` loss for microtask-dispatched events, or making the exclusion of block-construction `DataNodeAddedEvent`s explicit. The current behaviour is pinned by a test. -- Asynchronous groups (an `fn` that returns a promise, or changes made after an `await`). -- Sending `groupId` to the OT server or including it in serialized operations. - -## Decisions - -### D1. Batching by id, driven only by events (no open/close signal) - -`#canAddToBatch(payload)` gains one rule, checked before the existing ones: - -``` -if (payload.groupId !== undefined || lastEvent.groupId !== undefined) { - return payload.groupId === lastEvent.groupId; -} -// …existing text-continuation rule, unchanged -``` - -With this rule: - -- **Earlier typing is closed off.** The group's first event has an id the open, ungrouped batch doesn't have, so the batch is moved to the stack. -- **Later typing is closed off.** The first ungrouped event after the group doesn't match, so the group's batch is moved to the stack. -- **Consecutive groups stay separate**, because their ids differ. - -The debounce is unchanged. A group's events are all dispatched synchronously, plus any microtasks that follow immediately, so they fit well inside the 500 ms window. - -*Alternative considered:* `DocumentAPI.group` calls `UndoRedoManager.beginGroup()`/`endGroup()` around `fn`. This was rejected for three reasons: -- It couples the API layer to the undo implementation. -- It would bypass `collaboration-manager`, which can't see those calls but can see event payloads. -- It still needs the id to place microtask events correctly. - -With the event-driven rule, `UndoRedoManager` needs no new public API. - -### D2. A separate group stack in `utils/Context.ts` - -Add `runInGroup(fn)` and `getGroupId()`, backed by a second module-level stack, alongside the existing `userId` stack: - -- `runInGroup` pushes a new id when the stack is empty, and pushes the current top when a group is already open, so nested calls reuse the outer id. -- It pops in `finally`, so a throw still closes the group. -- Ids come from a module-level counter (`'g1'`, `'g2'`, …). They only need to be unique within one JS realm for local undo. They are never serialized. - -`EditorJSModel.group(fn: () => T): T` wraps `runInGroup`. It is **not** decorated with `@WithContext`, because it takes no `userId`. The model calls inside `fn` still push their own `userId` as they do today. - -*Alternative considered:* change the context value from `userId` to `{ userId, groupId }`. Rejected: it changes the meaning of every `getContext()` call site and every `@WithContext` method, which is wider than necessary. A separate stack is an additive change. - -### D3. Capture at creation, forward on re-dispatch - -- `BaseDocumentEvent` and every concrete event constructor take an optional trailing `groupId?: string`, stored in `detail.groupId`. -- **Creation sites** (the 21 `getContext()` reads) also pass `getGroupId()`. `BlockNode.createDataNode` reads it **before** `queueMicrotask`, next to the existing `userId` capture. -- **Re-dispatch sites** pass `event.detail.groupId`, never `getGroupId()`. There are three: - - `BlockNode` bubbling for text, value and tune events; - - `EditorDocument.#listenAndBubbleBlockEvent`; - - `EditorJSModel.#listenAndBubbleDocumentEvents`. - The id always comes from where the event was created, never from where it is re-dispatched. This is what makes microtask events come out right. - -`userId` handling at the re-dispatch sites is left unchanged (see the Non-Goals and R2). - -### D4. `DocumentAPI.group` delegates to the model - -The core `DocumentAPI` already holds `EditorJSModel`. `group(fn)` returns `this.#model.group(fn)`. The SDK interface gets the matching signature. No change to `EventBus`. - -## Risks / Trade-offs - -- **[R1] A group event arriving after the debounce flushed the batch starts a new step.** It would need a local, grouped event dispatched more than 500 ms after the group. Nothing produces that today, since microtasks run immediately. → Accepted. If async groups are ever added, revisit with "append to the top step when its `groupId` matches". -- **[R2] Block-construction `DataNodeAddedEvent`s are kept out of undo only because they lose their `userId`.** If someone fixes `userId` forwarding in `EditorJSModel`, these events would start being recorded, and redo would throw. → The core spec scenario "Block construction events are not recorded separately" becomes a test that fails in that case. The test's comment will point to the proper fix: skip events for data that a `BlockAdded` in the same step already covers. -- **[R3] 21 creation sites plus 3 re-dispatch sites to update.** A missed creation site silently produces `groupId: undefined` in the middle of a group, which would split the step. → An integration test runs a group covering every kind of mutation (text insert/remove/format, value modify, data node add/remove, block add/remove, tune modify) and asserts that every dispatched event carries the group's id. -- **[R4] Collaboration users don't get grouping.** → Documented in the proposal. `groupId` is on the event, so extending `collaboration-manager` later is a contained change. -- **[R5] A module-level group stack is shared by all model instances in one realm.** It behaves the same way as the existing `userId` stack. Group ids stay unique because the counter is global, and nesting across instances within one synchronous call is harmless. → Accepted. - -## Migration Plan - -Additive only. `groupId` is optional on events, constructors take it as an optional last argument, and `DocumentAPI.group` is a new method. Third-party `DocumentAPI` implementations, if any exist, would need to add `group`. Rollback is reverting the change; no data or format migration is involved. - -## Open Questions - -- Should `group` be available through `api.document` only, or also through `BlocksAPI` helpers such as `split` (i.e. should `split` group itself)? This design keeps it on `api.document` only. The paste change will wrap its whole sequence of calls in one `group`. diff --git a/openspec/changes/undo-grouping/proposal.md b/openspec/changes/undo-grouping/proposal.md deleted file mode 100644 index 9497d94d..00000000 --- a/openspec/changes/undo-grouping/proposal.md +++ /dev/null @@ -1,41 +0,0 @@ -## Why - -Core's `UndoRedoManager` only groups consecutive text inserts or removals in the same input, within a 500 ms debounce window. Any action that makes several kinds of model change becomes several undo steps. A paste, for example, removes the selected text, splits the block, and inserts blocks. The upcoming paste change (`clipboard-paste-plain-and-editorjs`) needs a whole paste to undo with one Ctrl+Z. Cut, drop and block conversion will need the same, so it belongs in core as a general primitive, not inside the paste code. - -## What Changes - -- Add `api.document.group(fn)` to the SDK `DocumentAPI` contract and implement it in core. Model changes made synchronously inside `fn` by the local user form exactly one undo step: - - Any in-progress debounce batch is closed before the group opens, so earlier typing stays a separate step. - - The group's step is closed when `fn` returns, so later typing starts a new step. - - Nested `group()` calls join the outermost group. - - If `fn` throws, the group still closes and the error is re-thrown. -- The model carries a **group id** on every document event. It is captured synchronously when the event is created and kept as the event bubbles up the model tree (`BlockNode` → `EditorDocument` → `EditorJSModel`). This includes events dispatched later in a microtask, such as the `DataNodeAddedEvent`s `BlockNode` emits during construction. -- `EditorJSModel` gets a way to run a function inside a group context (a new group id, or the enclosing one when nested). -- `EventPayloadBase` gains an optional `groupId` field. The change is additive; events created outside a group leave it `undefined`. -- `UndoRedoManager` groups by id. A local event carrying a group id joins the current batch only if the batch has the same group id. Otherwise the batch is closed and a new one starts. An event without a group id never joins a grouped batch. Ungrouped events keep today's batching exactly. As a result, the group's step is closed before and after the group with no extra signals between core and the model. -- Record one fact the change depends on: `DataNodeAddedEvent`s that `BlockNode` fires in a microtask while it is being constructed reach `EditorJSModel` with no `userId`, because the re-wrap reads `getContext()` after the context has been popped. Core's `UndoRedoManager` therefore never records them. This is correct for undo: the preceding `BlockAddedEvent` already holds the block's data, and recording both would break redo with `AlreadyExistingKeyError`. This change adds a test that pins the behaviour (a grouped block insert undoes and redoes cleanly) and records it in the design. Making the exclusion explicit, instead of a side effect of the missing `userId`, is left for later. - -## Capabilities - -### New Capabilities - - -### Modified Capabilities -- `core`: "Local undo/redo" batches by group id: a group's events form one step, closed off from the changes before and after it. "EditorAPI surface" lists `DocumentAPI.group`. -- `sdk`: new requirement "Grouped document changes" for the `group(fn)` contract on `DocumentAPI`. -- `model`: new requirement "Grouped mutations": `EditorJSModel` can run a function inside a group context, and document events carry the group id that was active when they were created, including events dispatched in a microtask, and keep it while bubbling. -- `model-types`: "Base document event and event bus" adds the optional `groupId` field to `EventPayloadBase` and the `BaseDocumentEvent` constructor. - -## Impact - -- **Packages**: - - `model-types`: event payload and base event. - - `model`: the context utilities in `utils/Context.ts`, every event-creation site that reads `getContext()` (21 sites), and the bubbling re-wraps in `BlockNode`, `EditorDocument` and `EditorJSModel`. - - `sdk`: the `DocumentAPI` interface. - - `core`: `DocumentAPI` and `UndoRedoManager`. `UndoRedoManager` only changes its batching rule; no new calls from `DocumentAPI` into it. -- **API**: additive only. There are no **BREAKING** changes. Events without a group behave as they do today. -- **Collaboration**: `collaboration-manager` keeps its own `UndoRedoManager`, which takes over `core:undo`/`core:redo` when it is registered (see the `architecture` spec). That manager does not read `groupId` in this change, so a grouped action still undoes in several steps when collaboration is enabled. Because the group id is now on every event, supporting it there later only needs a change to that manager. The OT server and operation serialization are unaffected; `groupId` is not sent over the wire. -- **Docs**: - - `docs/diagrams/undo-redo-flow.mmd` and `docs/events.md` (the `BaseDocumentEvent` payload fields) need to show the group id and grouping. - - Nothing in `docs/` is replaced by this change. -- **Follow-up**: `clipboard-paste-plain-and-editorjs` depends on this change. diff --git a/openspec/changes/undo-grouping/specs/core/spec.md b/openspec/changes/undo-grouping/specs/core/spec.md deleted file mode 100644 index 7977201f..00000000 --- a/openspec/changes/undo-grouping/specs/core/spec.md +++ /dev/null @@ -1,71 +0,0 @@ -## MODIFIED Requirements - -### Requirement: EditorAPI surface -The system SHALL expose an `EditorAPI` aggregating `BlocksAPI` (insert/insertMany/delete/move/render/clear/getBlocksCount), `SelectionAPI` (applyInlineTool, selectedBlocks), `DocumentAPI` (serialized data, onUpdate, insertData/removeData/modifyData, undo/redo, group), and `TextAPI` (insert/remove/format/unformat/getFragments/get) to tools, plugins, and adapters. - -#### Scenario: Deleting with no block selected -- **GIVEN** no block is currently selected/no caret is set -- **WHEN** `BlocksAPI.delete()` or `move()` is called without an explicit index -- **THEN** it throws an error ("No block selected to delete" / "No block selected to move") - -#### Scenario: Splitting or converting with an unknown tool -- **GIVEN** a `splitBlock`/`convertBlock` call references a `dataKey` that doesn't exist, or a source/target tool that isn't registered -- **WHEN** the operation is attempted -- **THEN** it throws an error identifying the missing key or tool - -#### Scenario: Grouping delegates to the model -- **GIVEN** a caller invokes `DocumentAPI.group(fn)` -- **WHEN** the call runs -- **THEN** `fn` is executed inside the model's group context (`EditorJSModel.group`), and its return value or thrown error is passed back to the caller - -Implemented in `src/api/index.ts`, `src/api/BlocksAPI.ts`, `src/api/SelectionAPI.ts`, `src/api/DocumentAPI/DocumentAPI.ts`, `src/api/TextAPI.ts`, `src/components/BlockManager.ts`, validated by co-located `.spec.ts`/`.integration.spec.ts` files. - -### 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. Batching SHALL respect group ids: an event with a `groupId` joins the current batch only if the batch has the same `groupId`, and an event without one never joins a grouped batch. Ungrouped events are batched by the existing rule (consecutive text insert/remove in the same input). - -#### 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: A group is one undo step -- **GIVEN** the local user runs `api.document.group(fn)`, where `fn` removes text, splits a block and inserts several blocks -- **WHEN** `undo()` is called once -- **THEN** every change made inside `fn` is reverted, and the document equals its state before `group` was called - -#### Scenario: Redo re-applies the whole group -- **GIVEN** a grouped step has just been undone -- **WHEN** `redo()` is called once -- **THEN** every change of the group is re-applied, without errors, and the document equals its state right after `group` returned - -#### Scenario: Earlier typing stays a separate step -- **GIVEN** the local user typed text less than 500 ms before a group starts, so that text is still in the open batch -- **WHEN** the group's first event arrives and `undo()` is later called once -- **THEN** only the group's changes are reverted, and the typed text stays - -#### Scenario: Later typing starts a new step -- **GIVEN** a group 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 group's changes stay - -#### Scenario: Consecutive groups are separate steps -- **GIVEN** two `api.document.group` calls run one after the other -- **WHEN** `undo()` is called once -- **THEN** only the second group's changes are reverted - -#### Scenario: Block construction events are not recorded separately -- **GIVEN** a block with text data is added inside a group -- **WHEN** the group 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: Remote events do not join a local group -- **GIVEN** a remote user's event arrives while a local group's batch is open -- **WHEN** the manager handles it -- **THEN** the event is ignored, as for any remote event, and the local group's step is unaffected - -Implemented in `src/components/UndoRedoManager.ts`, validated by its co-located `.spec.ts`. diff --git a/openspec/changes/undo-grouping/specs/model-types/spec.md b/openspec/changes/undo-grouping/specs/model-types/spec.md deleted file mode 100644 index e046afee..00000000 --- a/openspec/changes/undo-grouping/specs/model-types/spec.md +++ /dev/null @@ -1,24 +0,0 @@ -## MODIFIED Requirements - -### Requirement: Base document event and event bus -The system SHALL provide a `BaseDocumentEvent` base class carrying `{ index, action, data, userId, groupId }` that fires under the `EventType.Changed` DOM event type, concrete event subclasses for each kind of document mutation (block/data/text add/remove/modify, tune/property modification), and a thin `EventBus` (`EventTarget` subclass) used to dispatch them. `groupId` is optional: it identifies the group of changes the mutation belongs to, and is `undefined` for mutations made outside a group. - -#### Scenario: Emitting a document mutation event -- **GIVEN** a block, text, or value node is added, removed, or modified -- **THEN** the corresponding concrete event (e.g. `DataNodeAddedEvent`, `TextFormattedEvent`, `BlockAddedEvent`, `PropertyModifiedEvent`, `TuneModifiedEvent`) is dispatched as `EventType.Changed`, carrying an `EventAction` (`Added`/`Removed`/`Modified`) and the affected `Index` - -#### Scenario: Carrying a group id -- **GIVEN** a concrete document event is constructed with a group id argument -- **WHEN** a listener reads the event's `detail` -- **THEN** `detail.groupId` equals the id that was passed - -#### Scenario: Event created without a group id -- **GIVEN** a concrete document event is constructed without a group id argument -- **WHEN** a listener reads the event's `detail` -- **THEN** `detail.groupId` is `undefined`, and every other field is the same as before this field existed - -#### Scenario: Emitting a caret event -- **GIVEN** a caret is added, removed, or updated -- **THEN** the corresponding caret event (`CaretManagerCaretAddedEvent`, `CaretManagerCaretRemovedEvent`, `CaretManagerCaretUpdatedEvent`) is dispatched as `EventType.CaretManagerUpdated`, carrying the serialized `Caret` - -Implemented in `src/BaseDocumentEvent.ts`, `src/EventBus.ts`, `src/EventType.ts`, `src/EventAction.ts`, `src/EventMap.ts`, `src/events/*`. diff --git a/openspec/changes/undo-grouping/specs/model/spec.md b/openspec/changes/undo-grouping/specs/model/spec.md deleted file mode 100644 index 154a38eb..00000000 --- a/openspec/changes/undo-grouping/specs/model/spec.md +++ /dev/null @@ -1,36 +0,0 @@ -## ADDED Requirements - -### Requirement: Grouped mutations -`EditorJSModel` SHALL provide `group(fn)`, which runs `fn` synchronously inside a group context and returns its result. Every document event created while the context is active SHALL carry that group's id in `detail.groupId`. The id is captured when the event is created and kept unchanged as the event is re-dispatched by `BlockNode`, `EditorDocument` and `EditorJSModel`. Events created outside any group SHALL carry `groupId: undefined`. - -#### Scenario: Mutations inside a group share one id -- **GIVEN** `model.group(fn)` is called -- **WHEN** `fn` inserts text, splits a block and adds blocks -- **THEN** every `EventType.Changed` event the model dispatches for those mutations carries the same, defined `groupId` - -#### Scenario: Separate groups get different ids -- **GIVEN** `model.group(fnA)` completes -- **WHEN** `model.group(fnB)` is called afterwards -- **THEN** the events of `fnB` carry a `groupId` different from the events of `fnA` - -#### Scenario: Nested groups join the outer group -- **GIVEN** `model.group(outer)` is running -- **WHEN** `outer` calls `model.group(inner)` -- **THEN** the events created inside `inner` carry the same `groupId` as the events created directly inside `outer` - -#### Scenario: Group id survives microtask-deferred dispatch -- **GIVEN** a block is added inside `model.group(fn)`, and `BlockNode` queues its `DataNodeAddedEvent`s in a microtask -- **WHEN** those events are dispatched after `fn` has returned -- **THEN** they carry the `groupId` that was active when the block was constructed - -#### Scenario: Group context closes on throw -- **GIVEN** `fn` throws inside `model.group(fn)` -- **WHEN** the error propagates out of `group` -- **THEN** the group context is no longer active, so events created afterwards carry `groupId: undefined` - -#### Scenario: Mutations outside a group -- **GIVEN** no group is active -- **WHEN** any mutation is made -- **THEN** its events carry `groupId: undefined` - -Implemented in `src/EditorJSModel.ts` and `src/utils/Context.ts`, with ids captured at the event-creation sites in `src/entities/**`, validated by `src/EditorJSModel.spec.ts` and `src/EditorJSModel.integration.spec.ts`. diff --git a/openspec/changes/undo-grouping/specs/sdk/spec.md b/openspec/changes/undo-grouping/specs/sdk/spec.md deleted file mode 100644 index f99f49db..00000000 --- a/openspec/changes/undo-grouping/specs/sdk/spec.md +++ /dev/null @@ -1,16 +0,0 @@ -## ADDED Requirements - -### Requirement: Grouped document changes -The `DocumentAPI` contract SHALL declare `group(fn: () => T): T`, which runs `fn` synchronously and returns its result. All document changes that `fn` makes through the `EditorAPI` are treated as one unit of history: a single undo step. - -#### Scenario: Plugin groups a multi-operation action -- **GIVEN** a plugin holds an `EditorAPI` -- **WHEN** it calls `api.document.group(() => { api.blocks.split(...); api.blocks.insertMany(...); })` -- **THEN** the call type-checks and returns the callback's return value - -#### Scenario: Errors propagate -- **GIVEN** the callback passed to `api.document.group` throws -- **WHEN** `group` is called -- **THEN** the same error is re-thrown to the caller - -Implemented in `src/api/DocumentAPI.ts`. diff --git a/openspec/changes/undo-grouping/tasks.md b/openspec/changes/undo-grouping/tasks.md deleted file mode 100644 index b7b145a8..00000000 --- a/openspec/changes/undo-grouping/tasks.md +++ /dev/null @@ -1,49 +0,0 @@ -## 1. model-types: groupId on events - -- [ ] 1.1 Write failing tests in `packages/model-types`: "should expose detail.groupId when constructed with a group id" and "should leave detail.groupId undefined when constructed without one", for `BaseDocumentEvent` and one concrete event (e.g. `TextAddedEvent`) -- [ ] 1.2 Add optional `groupId?: string` to `EventPayloadBase`, and an optional trailing `groupId` parameter to `BaseDocumentEvent` and every concrete event in `src/events/*`, forwarded to `super` -- [ ] 1.3 Run `yarn test` and `yarn lint` in `packages/model-types` - -## 2. model: group context - -- [ ] 2.1 Write failing tests for `utils/Context.ts`: "should return undefined from getGroupId outside a group", "should return the same id for nested runInGroup calls", "should return different ids for consecutive groups", "should close the group when fn throws" -- [ ] 2.2 Implement the group stack, `runInGroup(fn)` and `getGroupId()` in `packages/model/src/utils/Context.ts` (counter-based ids, nested calls reuse the outer id, pop in `finally`) -- [ ] 2.3 Write failing `EditorJSModel.spec.ts` tests for `group(fn)`: returns `fn`'s result, re-throws its error -- [ ] 2.4 Add `EditorJSModel.group(fn: () => T): T` wrapping `runInGroup` (without `@WithContext`) - -## 3. model: capture and forward the group id - -- [ ] 3.1 Write a failing integration test in `EditorJSModel.integration.spec.ts`: "should tag every event with the active group id", running one group that covers text insert/remove/format/unformat, value modify, data node add/remove, block add/remove and tune modify, and asserting that every `EventType.Changed` event (including ones dispatched in microtasks) carries the group's id -- [ ] 3.2 Write a failing integration test: "should keep the group id on DataNodeAddedEvents dispatched in a microtask after the group returned" -- [ ] 3.3 Write a failing integration test: "should leave groupId undefined for mutations outside a group" -- [ ] 3.4 Pass `getGroupId()` at every event-creation site that reads `getContext()` (`EditorDocument`, `BlockNode`, `BlockTune`, `ValueNode`, `ParentInlineNode`, `EditorJSModel`). In `BlockNode.createDataNode`, capture it before `queueMicrotask` -- [ ] 3.5 Forward `event.detail.groupId` at the three re-dispatch sites: `BlockNode` bubbling for text, value and tune events, `EditorDocument.#listenAndBubbleBlockEvent`, and `EditorJSModel.#listenAndBubbleDocumentEvents` -- [ ] 3.6 Run `yarn test`, `yarn lint` and `yarn test:mutations` (if configured) in `packages/model` - -## 4. sdk: DocumentAPI contract - -- [ ] 4.1 Add `group(fn: () => T): T` with TSDoc to `packages/sdk/src/api/DocumentAPI.ts` -- [ ] 4.2 Update any SDK mocks/stubs of `DocumentAPI` so that `yarn test` and `yarn lint` pass in `packages/sdk` - -## 5. core: DocumentAPI.group and batching by group id - -- [ ] 5.1 Write failing `DocumentAPI` tests: "should run fn inside model.group and return its result", "should re-throw errors from fn" -- [ ] 5.2 Implement `DocumentAPI.group` in `packages/core/src/api/DocumentAPI/DocumentAPI.ts` by delegating to `EditorJSModel.group` -- [ ] 5.3 Write failing `UndoRedoManager.spec.ts` tests matching the core spec scenarios: - - should undo a whole group in one step - - should redo a whole group in one step - - should keep earlier typing as a separate step - - should start a new step for typing after a group - - should keep consecutive groups as separate steps - - should ignore remote events during a group -- [ ] 5.4 Add the group-id rule to `#canAddToBatch` in `packages/core/src/components/UndoRedoManager.ts`, checked before the existing text-continuation rule (design D1) -- [ ] 5.5 Write an integration test through `Core`: "should undo and redo a grouped block insert without AlreadyExistingKeyError", covering design R2. Its comment should explain why block-construction `DataNodeAddedEvent`s must stay out of undo -- [ ] 5.6 Add an integration test that pins current behaviour: an ungrouped `blocks.split` still produces its current number of undo steps -- [ ] 5.7 Run `yarn test`, `yarn lint` and `yarn test:mutations` (if configured) in `packages/core` - -## 6. Docs and wrap-up - -- [ ] 6.1 Update `docs/events.md` (add `detail.groupId` to the `BaseDocumentEvent` payload list) and `docs/diagrams/undo-redo-flow.mmd` (add a grouped-action sequence to the core undo manager) -- [ ] 6.2 Note in `docs/collaboration.md` that `collaboration-manager` undo does not yet honour `groupId` -- [ ] 6.3 Run `yarn lint` and `yarn test` from the repo root -- [ ] 6.4 Run `openspec validate undo-grouping --type change` and fix any issues From 32e85f48dc2e3efb92d74cd3ad23c62311b1105b Mon Sep 17 00:00:00 2001 From: Ilya Maroz <37909603+ilyamore88@users.noreply.github.com> Date: Sat, 10 Oct 2026 13:23:17 +0100 Subject: [PATCH 3/3] docs(openspec): cover undo of block changes in undo-group-by-task Block events carry a single serialized block while the model's insertData/removeData expect a list, so undoing any block add/remove throws. Add the fix (wrap in a one-item list in UndoRedoManager) to the proposal, design, core spec and tasks. --- openspec/changes/undo-group-by-task/design.md | 6 ++++++ openspec/changes/undo-group-by-task/proposal.md | 5 +++-- openspec/changes/undo-group-by-task/specs/core/spec.md | 5 +++++ openspec/changes/undo-group-by-task/tasks.md | 5 +++-- 4 files changed, 17 insertions(+), 4 deletions(-) diff --git a/openspec/changes/undo-group-by-task/design.md b/openspec/changes/undo-group-by-task/design.md index 1aa018ff..6ca237f1 100644 --- a/openspec/changes/undo-group-by-task/design.md +++ b/openspec/changes/undo-group-by-task/design.md @@ -67,6 +67,12 @@ When a multi-change task ends, it always closes the open batch: earlier typing i `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: diff --git a/openspec/changes/undo-group-by-task/proposal.md b/openspec/changes/undo-group-by-task/proposal.md index ef9866d8..11128b88 100644 --- a/openspec/changes/undo-group-by-task/proposal.md +++ b/openspec/changes/undo-group-by-task/proposal.md @@ -13,7 +13,8 @@ From the user's point of view, each of these is a single action. They all have o - **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. +- **`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. @@ -27,7 +28,7 @@ From the user's point of view, each of these is a single action. They all have o ## Impact -- **Code:** `packages/core/src/components/UndoRedoManager.ts` and its `.spec.ts`, plus one integration test through `Core`. No other package changes, and no public API changes. +- **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. diff --git a/openspec/changes/undo-group-by-task/specs/core/spec.md b/openspec/changes/undo-group-by-task/specs/core/spec.md index 43dc34f2..c9d5e2b6 100644 --- a/openspec/changes/undo-group-by-task/specs/core/spec.md +++ b/openspec/changes/undo-group-by-task/specs/core/spec.md @@ -58,6 +58,11 @@ The system SHALL provide `UndoRedoManager`, which batches consecutive model even - **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 diff --git a/openspec/changes/undo-group-by-task/tasks.md b/openspec/changes/undo-group-by-task/tasks.md index 6f9ad6dd..2671f1c6 100644 --- a/openspec/changes/undo-group-by-task/tasks.md +++ b/openspec/changes/undo-group-by-task/tasks.md @@ -18,9 +18,10 @@ - [ ] 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 Run `yarn test`, `yarn lint` and `yarn test:mutations` (if configured) in `packages/core` +- [ ] 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 through 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)