From a715bb0097500bf4dfd86d1087b53146539d8df7 Mon Sep 17 00:00:00 2001 From: gohabereg Date: Sat, 17 Oct 2026 04:19:37 +0100 Subject: [PATCH 1/2] docs(openspec): propose block merging via BlocksAPI.merge Add the merge-blocks-on-delete change for #135. A single BlocksAPI.merge overloaded for a block or a cross-block range joins neighbouring blocks; Backspace/Delete at boundaries and deletions over cross-block selections map to it from the DOM adapter. Co-Authored-By: Claude Opus 5.5 --- .../merge-blocks-on-delete/.openspec.yaml | 2 + .../changes/merge-blocks-on-delete/design.md | 175 ++++++++++++++++++ .../merge-blocks-on-delete/proposal.md | 66 +++++++ .../merge-blocks-on-delete/specs/core/spec.md | 105 +++++++++++ .../specs/dom-adapters/spec.md | 71 +++++++ .../merge-blocks-on-delete/specs/sdk/spec.md | 21 +++ .../changes/merge-blocks-on-delete/tasks.md | 56 ++++++ 7 files changed, 496 insertions(+) create mode 100644 openspec/changes/merge-blocks-on-delete/.openspec.yaml create mode 100644 openspec/changes/merge-blocks-on-delete/design.md create mode 100644 openspec/changes/merge-blocks-on-delete/proposal.md create mode 100644 openspec/changes/merge-blocks-on-delete/specs/core/spec.md create mode 100644 openspec/changes/merge-blocks-on-delete/specs/dom-adapters/spec.md create mode 100644 openspec/changes/merge-blocks-on-delete/specs/sdk/spec.md create mode 100644 openspec/changes/merge-blocks-on-delete/tasks.md diff --git a/openspec/changes/merge-blocks-on-delete/.openspec.yaml b/openspec/changes/merge-blocks-on-delete/.openspec.yaml new file mode 100644 index 00000000..0cb47656 --- /dev/null +++ b/openspec/changes/merge-blocks-on-delete/.openspec.yaml @@ -0,0 +1,2 @@ +schema: spec-driven +created: 2026-10-16 diff --git a/openspec/changes/merge-blocks-on-delete/design.md b/openspec/changes/merge-blocks-on-delete/design.md new file mode 100644 index 00000000..12d49dd5 --- /dev/null +++ b/openspec/changes/merge-blocks-on-delete/design.md @@ -0,0 +1,175 @@ +## Context + +v3 renders the whole document inside one `contenteditable` owned by `BlocksUI`. Every `beforeinput` is prevented and re-dispatched as `BeforeInputUIEvent`; **every** block's `DOMBlockToolAdapter` listens and acts on the inputs its target ranges touch. `CaretAdapter` turns the DOM selection into a model `Index`, which is a composite `TextIndex` (one segment per touched input, in document order) when the selection spans inputs. All adapters share one `InputsRegistry`. + +Current deletion behaviour (`BlockToolAdapter#handleDeleteInContentEditable`): + +- In-input range → `api.text.remove`. +- Cross-block range → each adapter clips the range to its own inputs and removes that slice; adapters whose input lies fully in between call `api.blocks.delete` on their whole block. The first and last blocks stay separate (`@todo support input merging`). +- Collapsed caret at a block boundary (Backspace at start / Delete at end) → the clipped ranges are empty, so nothing happens. + +Editor.js v2 had per-block contenteditables and merged only on Backspace/Delete at a boundary: `BlockManager.mergeBlocks(targetBlock, blockToMerge)`, gated by `areBlocksMergeable()` (target has a `merge()` method; different tools need `export`/`import` conversion configs), moving cross-tool content as a plain string. + +`BlocksManager` already implements `splitBlock()` and `convertBlock()` purely from `EditorJSModel` primitives, and `BlocksAPI` wraps them with params objects. Merging is the missing inverse of `split`. + +## Goals / Non-Goals + +**Goals:** + +- One operation that merges two neighbouring blocks, usable both for a block boundary (Backspace/Delete, programmatic calls) and for a cross-block range (selection delete, and typing/paste/Enter over a selection). +- All merge rules in core, so the DOM adapter only maps events to calls. +- Exactly one document-changing call per user action (plus the insert/split follow-up when typing or pressing Enter over a selection), all within one browser task. +- Inline formatting survives the merge, including between different tools. +- No new tool option and no API besides `BlocksAPI.merge`. + +**Non-Goals:** + +- Undo grouping. Today `UndoRedoManager` only groups consecutive text inserts/removals in one input, so a merge would be several undo steps, and undoing a block removal currently throws. Both are addressed by the open `undo-group-by-task` change ([#201](https://github.com/editor-js/document-model/pull/201) / [#203](https://github.com/editor-js/document-model/pull/203)), which records all events of one browser task as one step. This change relies on it and adds nothing to `UndoRedoManager`. +- Selecting non-text neighbours (image, delimiter) on Backspace/Delete — block selection does not exist yet; such neighbours are removed instead (Decision 5). +- A two-step "turn a structured block into plain text first, merge on the next keypress" behaviour, and list-style structural clean-up (removing only `items.0`). Both need a tool-level hook; no tool in this repository needs it yet. +- v2's whitespace/empty-tag special cases (` `, `` before the caret) — those stem from v2 reading the DOM; v3 reads the model. +- `insertCompositionText` over a cross-block selection (composition is already a `@todo`). +- Multi-client concurrency tests for merges. + +## Decisions + +### 1. One method, two forms + +```ts +interface MergeResult { + /** Id of the block the content was merged into */ + block: string; + /** Data key of the text input the content was merged into */ + key: string; + /** Offset in that input where the merged content starts */ + offset: number; +} + +interface BlocksAPI { + merge(params: { block: number | string; userId?: string | number }): MergeResult; + merge(params: { index: Index; userId?: string | number }): MergeResult; +} +``` + +- **`{ block }`** merges `block` into the block before it. Only neighbouring blocks can be merged — joining distant blocks has no meaningful outcome for the blocks between them — so a single block identifies the pair. Backspace at the start of block `b` is `merge({ block: b })`; Delete at the end of block `b` is `merge({ block: b + 1 })`. +- **`{ index }`** takes a text `Index` that starts in one block and ends in a later one (a composite `TextIndex`, as `CaretAdapter` produces for a cross-block selection). It removes the content inside the range, removes the blocks strictly between, and merges the end block into the start block at the range start. + +`{ block }` is defined as `{ index }` over the empty range from the end of the previous block's last text input to the start of `block`'s first text input, so both forms run the same algorithm and cannot drift apart. + +*Why `BlocksAPI`:* merging changes which blocks exist, like `split`, `convert` and `delete`. Putting range deletion with block side effects into `TextAPI.remove` would give a text method block-level effects, and a separate `SelectionAPI` method would partly mirror `TextAPI.remove`. A range-accepting `merge` keeps block structure changes in `BlocksAPI`, and `TextAPI.remove` keeps its single-input contract. + +*Why one name for both forms:* both collapse everything between two points and join what is left on each side. The range form also removes the text inside the range, which its documentation states up front. "Collapse" was considered and rejected: in DOM and selection terminology a collapsed range is a caret, and collapsing never deletes content; it would also read like folding a block. + +*Why a return value:* the junction is the caret position every interactive caller wants, and `merge` computes it anyway. Returning data has precedent (`TextAPI.remove` returns the removed text). `merge` itself does not move the caret — `BlocksManager` deliberately has no caret/adapter dependency (see its class comment about the `BlocksManager → Adapter → EditorAPI → BlocksAPI → BlocksManager` cycle). + +*No direction:* the second block is always converted into the first (Decision 3). Backspace at the start of B and Delete at the end of A delete the same boundary, so they give the same result and `merge` needs no direction parameter. + +### 2. Algorithm + +Let the range start at `(A, keyA, s)` and end at `(B, keyB, e)` with `A < B`. For `{ block: b }`: `A = b - 1`, `keyA` = last text input of `A`, `s` = its length; `B = b`, `keyB` = first text input of `B`, `e = 0`. + +1. **Validate** (Decision 5) before any mutation. +2. **Remove the range content in B** (B has the highest index, so lower indexes stay valid): remove `[0, e]` from `keyB` and empty every text input of B that the range fully covers (the segments before `keyB`). +3. **Remove the blocks strictly between A and B**, by index range in descending order — not by segment, so blocks without text inputs (which produce no segments) are removed too. +4. **Remove the range content in A**: remove `[s, end]` from `keyA` and empty every text input of A the range fully covers (segments after `keyA`). +5. **If A is now empty** (Decision 4): remove A; B survives with its id and tool, changed only by step 2. Junction → `(B, keyB, 0)`. +6. **Otherwise convert B into A**: compute B's absorbed content (Decision 3) from B's **current** state, append it into `keyA` at `s` (Decision 6), and remove B. Junction → `(A, keyA, s)`. +7. Return the junction. + +All mutations are dispatched synchronously within the caller's browser task, which is what `undo-group-by-task` needs to record them — together with the adapter's follow-up insert or split — as one undo step. + +### 3. The second block is converted into the first + +The first block always survives with its id and tool; the second block is absorbed. What is absorbed is decided by the second block's tool through its existing `conversionConfig.export`, read from the model after step 2: + +| `export` of B's tool | Absorbed content | +|---|---| +| key path (e.g. `'text'`, `'items.0.text'`) | that text input's value **and** inline fragments, from `getBlockTextContent` (key paths and model data keys share the dot notation) | +| function | `exportTextContent(data)` — plain string, no fragments | +| absent | B's first text input, value and fragments | + +Anything the export does not carry is dropped with B, exactly as `convertBlock` drops it — e.g. a quote whose export is `'text'` loses its caption, as in v2. A key path that does not resolve to one of B's text inputs absorbs nothing, consistent with `exportTextContent` returning `''` for a missing key; B is still removed. + +`Paragraph` and `@editorjs/header` (on its `v3` branch) both declare `export: 'text'`, so merges between them keep formatting in both directions. + +The content is **appended into A's existing input** rather than going through A's `conversionConfig.import`: import produces a whole new data object, while merging extends the input at the junction. So A's tool needs no conversion config, and neither tool can block a merge — `conversionConfig` only refines what is absorbed. This replaces v2's mergeability gate (`merge()` method + `export`/`import` presence): in v3 the join only moves text between text inputs, which accept text with fragments by definition. + +*Deviation from v2:* v2 round-tripped cross-tool content through a plain string; here formatting survives whenever B's export is a key path or absent. + +### 4. Empty blocks give way + +A block is **empty** when it has at least one text input and all of them are `''`. If A is empty after step 4, A is removed and B is kept as-is (step 5). This gives v2's empty-block behaviour without special cases: + +- Backspace at the start of B when the previous block is an empty line → the empty line is removed, B keeps its tool (v2: "should remove previous Block if Caret at the start of the Block and previous Block is empty"). +- Delete at the end of an empty block A → A is removed, the next block keeps its tool. +- A selection starting at the very beginning of A → A is removed and the trimmed B survives. + +If B has nothing to absorb (empty, or emptied by step 2), step 6 appends nothing and removes B — Backspace in an empty paragraph removes it, with the junction at the end of the previous block. + +### 5. Validation and unmergeable blocks + +A block **without text inputs** (image, delimiter, embed) is **unmergeable**: there is nothing to absorb from it and nothing to append into it. `merge` throws, leaving the document unchanged, when: + +- `{ block }` does not resolve to a block, or resolves to the first block; +- `{ index }` is not a text index, or does not start and end in different blocks (single-block ranges stay on `TextAPI.remove`); +- either block to be joined has no text inputs (for `{ index }` both edges lie in text inputs by construction, so this can only happen with `{ block }`). + +Blocks without text inputs that lie **strictly between** the edges of a range are not joined, only removed (step 3), so they never make a range merge fail. + +On the keyboard, an unmergeable neighbour is **removed** instead of merged: Backspace at the start of a block right after an image, or Delete at the end of a block right before one, deletes the image through the existing `api.blocks.delete`, and the caret stays where it is. This is the adapter's mapping (Decision 7), not a `merge` rule: `merge` keeps one meaning — joining two text blocks — and a programmatic caller that merges an image gets an error rather than a silent deletion. + +There is no `canMerge`: every failure condition is structural and visible to the caller up front. The DOM adapter never hits them, because it checks the neighbour's registered text inputs before choosing between `merge` and `delete`. + +### 6. Appending with formatting hygiene + +`BlocksManager` gets an internal helper (not on `BlocksAPI`): + +```ts +appendTextContent(blockIndex: number, key: DataKey, offset: number, content: { value: string; fragments: InlineFragment[] }, userId): void +``` + +1. If `content.value` is empty, return. +2. `model.insertText(userId, blockIndex, key, content.value, offset)`. +3. Normalize the inserted range: inserted text takes the formatting of the text it is inserted into, so appending at the end of an input that ends with a bold run makes the merged text bold. This holds for the current inline tree (`ParentInlineNode.insertText` inserts into the child found by `findChildByIndex`) and for the run model proposed in [#198](https://github.com/editor-js/document-model/pull/198) (`RunList.insert` extends the run at the offset with its marks). The clean-up only uses the model's public operations, so it works with either: read `model.getFragments(blockIndex, key, undefined, offset, offset + value.length)` and `model.unformat(...)` every tool found there. +4. Re-apply each `content.fragments` entry with `model.format(...)` shifted by `offset`. + +Fragments of inline tools A's tool does not enable are kept, consistent with `splitBlock`. + +### 7. The DOM adapter maps events to calls + +`DOMBlockToolAdapter` decides only *which call* an event maps to, from facts it already has (its DOM, the shared `InputsRegistry`); every document rule is in `merge`. + +**Classifying the target range.** The adapter converts the target range to a model `Index` (`CaretAdapter`'s selection-to-`Index` logic, refactored so it accepts any DOM `Range` — a `beforeinput` target range is not always the current selection, e.g. drag-and-drop). The range **crosses blocks** when its segments belong to more than one block. The `isCrossInputSelection` flag on `BeforeInputUIEvent` is not used for this: `BlocksUI` computes it as `startContainer !== endContainer`, which is also true inside a single input with formatting, because start and end land in different text nodes. The existing `insertParagraph` check on that flag moves to the same `Index`-based test. + +| `beforeinput` | Call | +|---|---| +| delete type, range crossing blocks | adapter owning the range start: `merge({ index })`, caret → junction | +| insert type (`insertText`, `insertFromPaste`, `insertFromDrop`, `insertReplacementText`), range crossing blocks | same, then `api.text.insert` at the junction | +| `insertParagraph`, range crossing blocks | same, then `api.blocks.split` at the junction | +| any type, range across several inputs of one block | unchanged: per-input `api.text.remove` by the block's adapter, then the type's usual insert/split | +| backward delete type, collapsed at offset 0 of the block's first text input | previous block has a registered text input → `merge({ block: current })`, caret → junction; previous block has none → `api.blocks.delete` of the previous block, caret unchanged; no previous block → no-op | +| forward delete type, collapsed at the end of the block's last text input | next block has a registered text input → `merge({ block: next })`, caret → junction; next block has none → `api.blocks.delete` of the next block, caret unchanged; no next block → no-op | +| backward/forward delete type at an edge between two inputs of the same block | caret moves to the end of the previous / start of the next input; no document change | +| anything within one input | unchanged (`api.text.remove` / `insert` / `split`) | + +Backward types are `deleteContentBackward`, `deleteWordBackward`, `deleteSoftLineBackward`, `deleteHardLineBackward`; forward types are their `Forward` counterparts. Boundary detection uses the collapsed DOM selection and the input type, **not** the browser's target range, because browsers disagree on the target range they report for Backspace at the start of a block. Neighbours are found with `api.blocks.getIdByIndex` and their text inputs with `InputsRegistry.getBlockInputs`. + +**Only one adapter acts per event**: the one owning the range start (or the caret). The per-adapter clipping of *cross-block* ranges and the "middle block → `api.blocks.delete`" path in `#handleDeleteInContentEditable` are removed, together with the `@todo support input merging`; per-input clipping within one block stays. + +**The acting adapter may lose its own block.** Backspace at the start of B removes B; a range starting at offset 0 of A removes A. Either way the adapter handling the event is destroyed by the merge it called. Every follow-up — caret placement, `text.insert`, `blocks.split` — therefore addresses `MergeResult.block` and goes through shared services (`CaretAdapter`, the API), never `this.blockId` or the adapter's own inputs. + +## Risks / Trade-offs + +- **Browser differences around boundary events** → boundary detection relies on the collapsed DOM selection and the input type, not on the reported target range; covered by Playwright e2e on chromium and webkit (the browsers the e2e project runs). +- **Caret races with adapter-side caret updates.** The adapter's model-to-DOM text sync also updates the caret index after `TextAddedEvent`/`TextRemovedEvent`. The adapter sets the caret to the returned junction after `merge` returns, so its write is last; e2e tests assert the caret lands at the junction. +- **Formatting bleed at the junction** → explicit unformat-then-reformat step (Decision 6), covered by a test that merges into an input ending with a formatted run. +- **Content outside the export is dropped.** A range ending in a quote's caption, or Backspace into a quote with a caption, drops what the quote's export does not carry. Same rule as `convert`, and v2's behaviour; worth stating in the `merge` docs. +- **Export functions lose formatting.** Tools that want formatting to survive a merge should use a key path. Documented on `conversionConfig.export`. +- **Behaviour change for cross-block selections:** delete/type/paste/Enter now join the edge blocks. Intended, but it changes what current users of the playground see. +- **Collaboration/OT:** only existing operations are emitted, so no new transform support is needed; concurrent edits during a merge go through the existing machinery but are not specifically tested here. +- **Undo depends on `undo-group-by-task`.** Until #201/#203 land, a merge is several undo steps and undoing its block removal throws. Undo tests for merging belong in that change or after it lands; this change only asserts that all of a merge's events are emitted synchronously. +- **Removing non-text neighbours is immediate.** Backspace after an image deletes the image with no intermediate "selected" state. Accepted until block selection exists; the adapter mapping is the only place to change then. + +## Open Questions + +None. diff --git a/openspec/changes/merge-blocks-on-delete/proposal.md b/openspec/changes/merge-blocks-on-delete/proposal.md new file mode 100644 index 00000000..269d12e5 --- /dev/null +++ b/openspec/changes/merge-blocks-on-delete/proposal.md @@ -0,0 +1,66 @@ +## Why + +Tracks [editor-js/document-model#135](https://github.com/editor-js/document-model/issues/135) — "Blocks merge": implement merging in `BlocksManager` and expose it on `BlocksAPI`. + +In Editor.js v2 every block was its own contenteditable, and merging was triggered by Backspace at the start of a block or Delete at the end of one. In v3 the whole document is **one contenteditable with cross-block selection**, so merging is also needed whenever a deletion crosses a block boundary: + +- Backspace at the start of a block deletes the boundary between it and the previous block. +- Delete at the end of a block deletes the boundary between it and the next block. +- Deleting a selection that spans several blocks deletes everything between two points, boundaries included — so the head of the first block and the tail of the last block must end up joined. The same applies to typing, pasting or pressing Enter over such a selection. + +Today none of these join anything. Backspace/Delete at a boundary is a no-op, and a cross-block selection delete is handled independently by every block's `DOMBlockToolAdapter` (edge blocks trim their slice, middle blocks call `blocks.delete`), leaving the two edge blocks apart — there is a `@todo support input merging` at exactly that spot. Several adapters mutating the document for one user action also means no single place owns the outcome. + +## What Changes + +- **One new API method, `BlocksAPI.merge()`**, backed by a new `BlocksManager.mergeBlocks()`, in two forms: + - **`merge({ block })`** merges `block` into the block **before it**. Only neighbouring blocks can be merged, so one block is enough. + - **`merge({ index })`** takes a text range that starts in one block and ends in another: the text inside the range is removed, the blocks strictly between are removed, and the end block is merged into the start block at the range start. `merge({ block })` is exactly `merge({ index })` over the empty range from the end of the previous block to the start of `block`. + - Both return the junction `{ block, key, offset }` — where the two blocks met — so callers can place the caret without re-deriving it. `merge` itself never moves the caret, like `split` and `convert`. +- **The second block is always converted into the first.** The first block survives with its id and tool; the second block's content is appended to it and the second block is removed. There is no separate convert step and no direction: Backspace at the start of B and Delete at the end of A delete the same boundary and give the same result. Blocks of different tools merge in one step, as in v2. +- **The second block's tool decides what is absorbed**, through its existing `conversionConfig.export`: + - a key path → that text input, **with its inline formatting** (read from the model, no plain-string round trip); + - a function → its plain-string result; + - none → its first text input. + Content the export does not carry is dropped with the block, exactly as `convert` drops it. The content lands in the first block's text input at the junction (its last text input for `{ block }`, the range's start input for `{ index }`). +- **Empty blocks give way.** If the first block is empty (after the range is removed), it is removed instead and the second block survives with its id and tool — Backspace after an empty line or Delete in an empty line removes that line, as in v2. If the second block has nothing to absorb, it is simply removed. +- **Blocks without text inputs are unmergeable.** `merge({ block })` throws when either of the two blocks has no text inputs. Backspace right after such a block (an image, a delimiter) or Delete right before it **removes that block** instead, through the existing `blocks.delete`. In a range, blocks without text inputs lying between the edges are removed like any other block in between. +- **Errors:** `merge` throws, leaving the document unchanged, when the block does not exist or is the first block, when the index is not a text index or does not start and end in different blocks, or when either block to be joined has no text inputs. No `canMerge`, no new tool option — `conversionConfig` only refines what is absorbed, it never blocks a merge. +- **Undo grouping is out of scope.** A merge emits several model events, which today's `UndoRedoManager` records as several undo steps. The open `undo-group-by-task` change ([#201](https://github.com/editor-js/document-model/pull/201), implemented in [#203](https://github.com/editor-js/document-model/pull/203)) records all events of one browser task as one undo step, which makes a merge — and a merge plus its follow-up insert — a single step without anything in this change. It also fixes undo of block insertion/removal, which currently throws, so undoing a merge depends on it. +- **`DOMBlockToolAdapter` only maps events to calls; the merge rules live in core:** + - whether a range crosses blocks is decided from its model `Index` (segments in different blocks), not from the `isCrossInputSelection` flag, which is also true inside one formatted input; + - delete input type over a cross-block range → the adapter owning the range start calls `merge({ index })` once and puts the caret at the junction; + - insert types or Enter over a cross-block range → the same, followed by `text.insert` or `blocks.split` at the junction; + - a range across several inputs of the **same** block keeps the existing per-input `text.remove` handling; + - Backspace at the start of a block's first input / Delete at the end of its last input → `merge({ block })` with the current / next block when the neighbour has text inputs, `blocks.delete` of the neighbour when it has none, nothing when there is no neighbour; + - Backspace/Delete at an edge between two inputs of the same block → caret moves to the neighbouring input (no document change). + The merge may remove the acting adapter's own block, so every follow-up (caret, insert, split) addresses the block id returned by `merge`. The per-adapter cross-block slicing and the "middle block → `blocks.delete`" path are removed. +- **Deliberate deviations from v2:** + - inline formatting survives a merge between different tools when the second tool's export is a key path; + - text blocks v2 treated as unmergeable (target without a `merge()` method, or different tools without conversion configs) now merge — v2 only moved the caret; + - Backspace/Delete next to a block without text inputs removes it instead of moving the caret into it (block selection does not exist yet). + +## Capabilities + +### New Capabilities + +None. + +### Modified Capabilities + +- `core`: new "Block merging" requirement (`BlocksManager.mergeBlocks` / `BlocksAPI.merge`, both forms, conversion of the second block, empty and unmergeable blocks, junction); the "EditorAPI surface" requirement lists `merge` on `BlocksAPI`. +- `sdk`: the "EditorAPI surface" requirement gains the `BlocksAPI.merge` signature and its `MergeResult` type. +- `dom-adapters`: the "Block-level DOM binding and input translation" requirement replaces per-adapter cross-block deletion with a single `merge` call, and adds the boundary Backspace/Delete mapping, including removal of neighbours without text inputs. + +## Impact + +- **Code**: + - `packages/sdk/src/api/BlocksAPI.ts` — `merge` signature and `MergeResult` type. + - `packages/core/src/api/BlocksAPI.ts` — thin wrapper. + - `packages/core/src/components/BlockManager.ts` — `mergeBlocks` and the internal content-append helper. + - `packages/dom-adapters/src/BlockToolAdapter/index.ts` (and `CaretAdapter` for range → `Index`) — map events to `merge`; remove per-adapter cross-block slicing. + - Co-located Jest specs; Playwright e2e in `packages/editorjs/e2e/tests`. +- **APIs**: one additive method on `BlocksAPI`. No breaking changes, no tool changes required — `Paragraph` and `@editorjs/header` merge without opting in. +- **Depends on**: `undo-group-by-task` ([#201](https://github.com/editor-js/document-model/pull/201) / [#203](https://github.com/editor-js/document-model/pull/203)) for merges to undo as one step and for undo of the removed blocks to work at all. Related open work: the run-based inline model ([#198](https://github.com/editor-js/document-model/pull/198)) — the junction formatting clean-up is written against the model's public operations, so it holds before and after; clipboard paste ([#191](https://github.com/editor-js/document-model/pull/191)) hands selections across several inputs back to `insertFromPaste`, which this change routes through `merge({ index })`. +- **Model**: no changes to `@editorjs/model`; everything is composed from existing `getBlockTextContent`/`insertText`/`removeText`/`format`/`unformat`/`getFragments`/`removeBlock` operations, so collaboration needs no new OT support. +- **Behaviour users will notice**: deleting, typing, pasting or pressing Enter over a cross-block selection now joins the edge blocks; Backspace/Delete at block boundaries now merge, or remove a neighbouring block that has no text inputs. +- **Docs**: does not supersede any document. `docs/input-handling.md` gains a "Merging blocks" section describing how deletions map to `merge`; its "BeforeInput delegation" section stays accurate. diff --git a/openspec/changes/merge-blocks-on-delete/specs/core/spec.md b/openspec/changes/merge-blocks-on-delete/specs/core/spec.md new file mode 100644 index 00000000..6554f5fa --- /dev/null +++ b/openspec/changes/merge-blocks-on-delete/specs/core/spec.md @@ -0,0 +1,105 @@ +## MODIFIED Requirements + +### Requirement: EditorAPI surface +The system SHALL expose an `EditorAPI` aggregating `BlocksAPI` (insert/insertMany/delete/move/render/clear/getBlocksCount/split/convert/merge), `SelectionAPI` (applyInlineTool, selectedBlocks), `DocumentAPI` (serialized data, onUpdate, insertData/removeData/modifyData, undo/redo), 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 + +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. + +## ADDED Requirements + +### Requirement: Block merging +The system SHALL provide `BlocksManager.mergeBlocks()`, exposed as `BlocksAPI.merge()`, accepting either `{ block, userId? }` or `{ index, userId? }`: + +- `{ block }` SHALL merge the given block into the block immediately before it. +- `{ index }` SHALL accept a text `Index` that starts in one block and ends in a later block; it SHALL remove the content inside the range, remove every block strictly between the two, and merge the end block into the start block at the range start. `{ block }` SHALL behave exactly as `{ index }` over the empty range from the end of the previous block's last text input to the start of the given block's first text input. + +Merging SHALL keep the first block with its id and tool and convert the second block into it: the second block's content selected by its tool's `conversionConfig.export` — the text input at that key path with its inline fragments when it is a key path, the export function's plain-string result when it is a function, or its first text input with its inline fragments when it is absent — SHALL be appended to the first block's text input at the junction (the last text input for `{ block }`, the range's start input for `{ index }`), and the second block SHALL be removed. Appended text SHALL NOT inherit formatting from the text before the junction. When the first block has no text content left, the first block SHALL be removed instead and the second block kept with its id and tool. A block without text inputs SHALL be unmergeable. A `conversionConfig.export` key path that does not resolve to a text input of the second block SHALL absorb nothing, the second block still being removed. + +`merge()` SHALL return the junction `{ block, key, offset }` — the id of the surviving block, the data key and the offset where the merged content starts — and SHALL NOT move the caret. It SHALL throw, leaving the document unchanged, when `{ block }` does not resolve to a block or resolves to the first block, when `{ index }` is not a text index or does not start and end in different blocks, or when either block to be joined has no text inputs. Blocks without text inputs lying strictly between the edges of `{ index }` SHALL be removed and SHALL NOT make the call throw. All mutations of one call SHALL be dispatched synchronously. + +#### Scenario: Merging a paragraph into the previous paragraph +- **GIVEN** two paragraphs "First" and "Second" +- **WHEN** `merge({ block: 1 })` is called +- **THEN** the document holds one paragraph "FirstSecond" with the first block's id, and the result is `{ block: , key: 'text', offset: 5 }` + +#### Scenario: Merging blocks of different tools +- **GIVEN** a header "Title" followed by a paragraph "Body" containing a bold range, the paragraph's `conversionConfig.export` being `'text'` +- **WHEN** `merge({ block: })` is called +- **THEN** the header's text becomes "TitleBody" with the bold range re-applied shifted by 5, the paragraph is removed, and the header keeps its tool + +#### Scenario: Second block exports through a function +- **GIVEN** the second block's tool declares `conversionConfig.export` as a function +- **WHEN** the block is merged +- **THEN** the function's string result is appended without inline fragments + +#### Scenario: Second block without conversion config +- **GIVEN** the second block's tool declares no `conversionConfig` +- **WHEN** the block is merged +- **THEN** its first text input, with its inline fragments, is appended and the merge does not throw + +#### Scenario: Content outside the export is dropped +- **GIVEN** the second block has a second, non-empty text input that its export key path does not point to +- **WHEN** the block is merged +- **THEN** only the exported input is appended and the block is removed together with its other input + +#### Scenario: Formatting before the junction does not spread +- **GIVEN** the first block's text input ends with an italic run +- **WHEN** an unformatted block is merged into it +- **THEN** the appended text carries no italic formatting + +#### Scenario: Previous block is empty +- **GIVEN** an empty paragraph followed by a header "Title" +- **WHEN** `merge({ block:
})` is called +- **THEN** the empty paragraph is removed, the header keeps its id, tool and text, and the result points at offset 0 of the header's text input + +#### Scenario: Merged block is empty +- **GIVEN** a paragraph "First" followed by an empty paragraph +- **WHEN** `merge({ block: 1 })` is called +- **THEN** the empty paragraph is removed, the first paragraph is unchanged, and the result points at offset 5 of it + +#### Scenario: Merging a range across two blocks +- **GIVEN** two paragraphs "Hello world" and "Foo bar" and an index from offset 5 of the first to offset 3 of the second +- **WHEN** `merge({ index })` is called +- **THEN** the document holds one paragraph "Hello bar" with the first block's id, and the result points at offset 5 of it + +#### Scenario: Merging a range across several blocks +- **GIVEN** an index starting in block 0 and ending in block 3, where block 2 has no text inputs +- **WHEN** `merge({ index })` is called +- **THEN** blocks 1 and 2 are removed and block 3's remaining content is merged into block 0 + +#### Scenario: Range starting at the beginning of the first block +- **GIVEN** a paragraph "Hello" followed by a header "World" and an index from offset 0 of the paragraph to offset 2 of the header +- **WHEN** `merge({ index })` is called +- **THEN** the paragraph is removed, the header keeps its id and tool with text "rld", and the result points at offset 0 of the header + +#### Scenario: Invalid merge arguments +- **GIVEN** `{ block }` resolves to no block or to the first block, or `{ index }` is not a text index or starts and ends in the same block +- **WHEN** `merge()` is called +- **THEN** it throws an error describing the problem and the document is unchanged + +#### Scenario: Merging does not move the caret +- **GIVEN** the user's caret is in another block +- **WHEN** `merge()` is called +- **THEN** the caret is not updated by the merge + +#### Scenario: Merging next to a block without text inputs +- **GIVEN** a block without text inputs (e.g. an image) followed by a paragraph +- **WHEN** `merge({ block: })` is called +- **THEN** it throws an error stating the previous block cannot be merged, and both blocks are unchanged + +#### Scenario: Export key path that does not resolve +- **GIVEN** the second block's `conversionConfig.export` is a key path that matches none of its text inputs +- **WHEN** the block is merged +- **THEN** nothing is appended to the first block and the second block is removed + +Implemented in `src/components/BlockManager.ts`, `src/api/BlocksAPI.ts`, validated by co-located `.spec.ts`/`.integration.spec.ts` files. diff --git a/openspec/changes/merge-blocks-on-delete/specs/dom-adapters/spec.md b/openspec/changes/merge-blocks-on-delete/specs/dom-adapters/spec.md new file mode 100644 index 00000000..436ed279 --- /dev/null +++ b/openspec/changes/merge-blocks-on-delete/specs/dom-adapters/spec.md @@ -0,0 +1,71 @@ +## MODIFIED Requirements + +### Requirement: Block-level DOM binding and input translation +The system SHALL provide `DOMBlockToolAdapter`, attached by tools to a contenteditable element for a model data key, which intercepts `beforeinput` events and applies model text-add/remove events back into the DOM. A target range SHALL be treated as crossing blocks when its model `Index` has segments in more than one block. Deletions that cross a block boundary — a target range spanning blocks, or a collapsed caret at the start of a block's first text input or the end of its last text input with a delete input type — SHALL be performed by exactly one adapter: through a single `api.blocks.merge()` call when the blocks on both sides have text inputs, after which the adapter SHALL place the caret at the returned junction, or through `api.blocks.delete()` of the neighbouring block when that block has no text inputs. Adapters SHALL NOT clip cross-block ranges or join blocks themselves, and every follow-up after `merge()` SHALL address the block id it returns, since the merge may remove the acting adapter's own block. + +#### Scenario: Text insertion via beforeinput +- **GIVEN** a `beforeinput` event of type `insertText`, `insertCompositionText`, `insertFromPaste`, `insertFromDrop`, or `insertReplacementText` +- **WHEN** it fires on a bound input +- **THEN** the adapter computes the absolute offset and calls `api.text.insert(...)`, letting the model — not the browser — own the DOM mutation + +#### Scenario: Deleting across a cross-block selection +- **GIVEN** a `beforeinput` event of a delete type whose target range starts in one block and ends in another +- **WHEN** it fires +- **THEN** only the adapter whose input contains the range start acts, converting the target range to an `Index` and calling `api.blocks.merge({ index })` once; no adapter calls `api.blocks.delete` or `api.text.remove` for that event, and the caret is placed at the returned junction + +#### Scenario: Typing over a cross-block selection +- **GIVEN** a `beforeinput` event of an insert type whose target range spans blocks +- **WHEN** it fires +- **THEN** the adapter owning the range start calls `api.blocks.merge({ index })` and then inserts the data at the returned junction + +#### Scenario: Backspace at the start of a block +- **GIVEN** the DOM selection is collapsed at offset 0 of a block's first text input, the input type is `deleteContentBackward`, `deleteWordBackward`, `deleteSoftLineBackward` or `deleteHardLineBackward`, and the previous block has a registered text input +- **WHEN** the `beforeinput` event fires +- **THEN** the adapter calls `api.blocks.merge({ block })` with its own block and places the caret at the returned junction, regardless of the target range reported by the browser + +#### Scenario: Delete at the end of a block +- **GIVEN** the DOM selection is collapsed at the end of a block's last text input, the input type is the forward counterpart of a backward delete type, and the next block has a registered text input +- **WHEN** the `beforeinput` event fires +- **THEN** the adapter calls `api.blocks.merge({ block })` with the next block and places the caret at the returned junction + +#### Scenario: Backspace or Delete next to a block without text inputs +- **GIVEN** the caret is at the start of a block's first text input with a backward delete type, or at the end of its last text input with a forward delete type, and the neighbouring block in that direction has no registered text input +- **WHEN** the `beforeinput` event fires +- **THEN** the adapter calls `api.blocks.delete()` for that neighbouring block, does not call `api.blocks.merge()`, and leaves the caret where it is + +#### Scenario: Backspace or Delete at the edge of the document +- **GIVEN** the caret is at the start of the first block with a backward delete type, or at the end of the last block with a forward delete type +- **WHEN** the `beforeinput` event fires +- **THEN** the adapter makes no API call and the document is unchanged + +#### Scenario: Selection within one formatted input +- **GIVEN** a target range inside a single text input whose start and end lie in different DOM text nodes because of inline formatting +- **WHEN** a delete `beforeinput` event fires +- **THEN** the range is not treated as crossing blocks and the adapter calls `api.text.remove` for that input + +#### Scenario: Selection across inputs of one block +- **GIVEN** a target range spanning two text inputs of the same block +- **WHEN** a delete `beforeinput` event fires +- **THEN** the block's adapter removes the selected text from each input with `api.text.remove` and does not call `api.blocks.merge()` + +#### Scenario: Acting adapter's block is removed by the merge +- **GIVEN** Backspace at the start of a block merges that block into the previous one, or a cross-block range starting at offset 0 of its first block makes that block give way +- **WHEN** the adapter that called `api.blocks.merge()` performs its follow-up +- **THEN** the caret placement and any `text.insert`/`blocks.split` address the block id returned by `merge()` and succeed although the acting adapter's own block no longer exists + +#### Scenario: Moving between inputs of one block +- **GIVEN** the DOM selection is collapsed at offset 0 of a block's non-first text input with a backward delete type, or at the end of its non-last text input with a forward delete type +- **WHEN** the `beforeinput` event fires +- **THEN** the caret moves to the end of the previous or the start of the next text input of the same block and the document is unchanged + +#### Scenario: Splitting a block on Enter +- **GIVEN** the caret is within a bound input +- **WHEN** an `insertParagraph` `beforeinput` event fires +- **THEN** any selected text is removed — through `api.blocks.merge({ index })` when the selection spans blocks — `api.blocks.split` is called at the resulting caret position, and after the next animation frame the caret moves to offset `[0,0]` of the newly created next block + +#### Scenario: Model-to-DOM text sync +- **GIVEN** a `TextAddedEvent` or `TextRemovedEvent` affects a bound input's data key +- **WHEN** the event is received +- **THEN** the adapter inserts/deletes DOM text nodes at the mapped boundary point, normalizes the node, and updates the caret index to the new position + +Implemented in `src/BlockToolAdapter/index.ts`, `src/BlockToolAdapter/types/InputType.ts`. diff --git a/openspec/changes/merge-blocks-on-delete/specs/sdk/spec.md b/openspec/changes/merge-blocks-on-delete/specs/sdk/spec.md new file mode 100644 index 00000000..df94fc9f --- /dev/null +++ b/openspec/changes/merge-blocks-on-delete/specs/sdk/spec.md @@ -0,0 +1,21 @@ +## MODIFIED Requirements + +### Requirement: EditorAPI surface +The system SHALL expose an `EditorAPI` type aggregating `BlocksAPI`, `SelectionAPI`, `DocumentAPI`, `TextAPI`, and `PluginsAPI` — the API object passed into tools, plugins, and adapters. The `BlocksAPI` interface SHALL declare `merge` alongside `split` and `convert` as two overloads — `merge(params: { block: number | string; userId?: string | number }): MergeResult` and `merge(params: { index: Index; userId?: string | number }): MergeResult` — with `MergeResult` exported as `{ block: string; key: string; offset: number }`. + +#### Scenario: Tool receives the aggregated API +- **GIVEN** a tool is constructed by the core orchestrator +- **WHEN** its constructor options are built +- **THEN** it receives a single `EditorAPI` object exposing `blocks`, `selection`, `document`, `text`, and `plugins` sub-APIs + +#### Scenario: Plugins namespace is typed by the plugin API map +- **GIVEN** `EditorjsPluginApiMap` has been augmented by one or more plugin packages +- **WHEN** `api.plugins` is accessed +- **THEN** it is typed as `Partial`, so known ids infer their API type and unknown ids fail to compile + +#### Scenario: Merging blocks through the API +- **GIVEN** an adapter, tool or plugin holds an `EditorAPI` instance +- **WHEN** it needs to merge a block into the previous one, or to remove a cross-block range and join its edges +- **THEN** it calls `api.blocks.merge({ block })` or `api.blocks.merge({ index })` and receives the junction as a `MergeResult` + +Implemented in `src/api/EditorAPI.ts`, `src/api/{BlocksAPI,DocumentAPI,SelectionAPI,TextAPI,PluginsAPI}.ts`. diff --git a/openspec/changes/merge-blocks-on-delete/tasks.md b/openspec/changes/merge-blocks-on-delete/tasks.md new file mode 100644 index 00000000..00040ac9 --- /dev/null +++ b/openspec/changes/merge-blocks-on-delete/tasks.md @@ -0,0 +1,56 @@ +## 1. SDK contract + +- [ ] 1.1 Add `MergeResult` (`{ block: string; key: string; offset: number }`) and two `merge` overloads — `merge(params: { block: number | string; userId?: string | number }): MergeResult` and `merge(params: { index: Index; userId?: string | number }): MergeResult` — to `BlocksAPI` in `packages/sdk/src/api/BlocksAPI.ts`, next to `split`/`convert`; document both forms, that the second block is converted into the first via its `conversionConfig.export`, that the range form removes the content inside the range, that blocks without text inputs are unmergeable, and that it does not move the caret; export `MergeResult` from the package entry +- [ ] 1.2 Note on `conversionConfig.export` in `packages/sdk/src/entities/BlockTool.ts` that it also decides what is absorbed when the block is merged, and that a key path keeps inline formatting while a function does not +- [ ] 1.3 Run `yarn workspace @editorjs/sdk lint` and `build` to confirm the contract compiles + +## 2. Append helper (TDD) + +- [ ] 2.1 Write failing tests in `packages/core/src/components/BlockManager.spec.ts` for an internal `appendTextContent(blockIndex, key, offset, content, userId)`: appends text at the offset, re-applies fragments shifted by the offset, is a no-op for empty content +- [ ] 2.2 Implement it with `model.insertText` + `model.format`, and make the tests pass +- [ ] 2.3 Write a failing test that appending to an input ending with a formatted run does not extend that formatting over the appended text, then implement the normalization step (`model.getFragments` over the appended range → `model.unformat` per tool found) before re-applying the content's fragments + +## 3. mergeBlocks — block form (TDD) + +- [ ] 3.1 Write failing tests for `BlocksManager.mergeBlocks({ block })`: two paragraphs merge into the previous one, which keeps its id, and the junction is returned; the block can be passed by index or id +- [ ] 3.2 Implement the block form on top of `appendTextContent` + `removeBlock`, and make the tests pass +- [ ] 3.3 Write failing tests for what is absorbed: export key path → that input with fragments (including a nested key such as `items.0.text`); export function → its string without fragments; no `conversionConfig` → first text input with fragments; a second input not covered by the export is dropped with the block; an export key path matching none of the block's text inputs absorbs nothing and the block is still removed — then implement the export resolution and make them pass +- [ ] 3.4 Write failing tests for empty blocks: an empty previous block is removed and the merged block keeps its id, tool and text with the junction at its offset 0; an empty merged block is removed and the previous block is unchanged — then make them pass +- [ ] 3.5 Write failing tests that `{ block }` throws, leaving the document unchanged, for an unknown block, the first block, and a block or previous block without text inputs (unmergeable); make them pass +- [ ] 3.6 Write a test that all model events of one `merge` call are emitted synchronously, before `merge` returns (the precondition for `undo-group-by-task` to record them as one step) + +## 4. mergeBlocks — range form (TDD) + +- [ ] 4.1 Write failing tests for `mergeBlocks({ index })` across two blocks: range content removed, end block's remaining content merged at the range start, end block removed, junction at the range start +- [ ] 4.2 Implement the range form in the order end block → blocks strictly between (descending, by index range) → start block → empty-start check → convert end block into start block, and make the tests pass +- [ ] 4.3 Write failing tests for: blocks without text inputs between the edges are removed; a range starting at offset 0 of the first block removes that block and keeps the trimmed end block with its tool; a range ending in a non-exported input of the end block absorbs only what the export carries — then make them pass +- [ ] 4.4 Write failing tests that `{ index }` throws for a non-text index and for a range within a single block; make them pass +- [ ] 4.5 Write a test that `merge({ block: b })` produces the same document as `merge({ index })` over the empty boundary range before block `b` + +## 5. BlocksAPI wiring and integration + +- [ ] 5.1 Write failing tests in `packages/core/src/api/BlocksAPI.spec.ts` that `merge()` delegates both forms to `BlocksManager.mergeBlocks` with the config's `userId` by default and an explicit one when passed, and returns its result +- [ ] 5.2 Implement `merge()` in `packages/core/src/api/BlocksAPI.ts` as a thin params-object wrapper mirroring `split`/`convert`, and make the tests pass +- [ ] 5.3 Add integration tests in `packages/core/src/api/BlocksAPI.integration.spec.ts` (real model, mocked DOM adapters) for: paragraph → paragraph merge; paragraph merged into a header-like tool keeps formatting; header-like block merged into a paragraph; cross-block range across three blocks, one of them without text inputs, with formatting preserved; the caret is not moved by `merge` + +## 6. DOMBlockToolAdapter + +- [ ] 6.1 Refactor `CaretAdapter`'s selection-to-`Index` logic so it can convert an arbitrary DOM `Range` (from a `beforeinput` target range), keeping `selectionchange` behaviour unchanged; cover with a test +- [ ] 6.2 Write failing tests for classifying a target range from its `Index`: a range inside one formatted input (start and end in different text nodes) does not cross blocks; a range across two inputs of one block does not cross blocks; a range whose segments belong to two blocks does — then implement the check and switch the existing `insertParagraph` condition from `isCrossInputSelection` to it +- [ ] 6.3 Write failing tests that a delete `beforeinput` with a cross-block target range leads to exactly one `api.blocks.merge({ index })` call, from the adapter owning the range start, no `api.blocks.delete`/`api.text.remove` calls, and the caret placed at the returned junction +- [ ] 6.4 Write failing tests that an insert-type `beforeinput` over a cross-block range calls `merge({ index })` then `api.text.insert` at the junction, and that `insertParagraph` over it calls `merge({ index })` then `api.blocks.split` at the junction +- [ ] 6.5 Write failing tests that a collapsed selection at offset 0 of a block's first input with a backward delete type calls `merge({ block })` with its own block, and at the end of its last input with a forward type calls it with the next block — regardless of the reported target range; that `api.blocks.delete` is called for a neighbour without registered text inputs, with the caret left in place; and that nothing is called at the start of the first or the end of the last block +- [ ] 6.6 Write failing tests that a backward/forward delete at an edge between two inputs of the same block only moves the caret to the neighbouring input, and that a delete over a range across two inputs of one block still removes text per input without calling `merge` +- [ ] 6.7 Write failing tests that when `merge` removes the acting adapter's own block (Backspace at a block's start; a cross-block range starting at offset 0), the caret placement and the follow-up `text.insert`/`blocks.split` address `MergeResult.block` and succeed +- [ ] 6.8 Implement the mapping in `packages/dom-adapters/src/BlockToolAdapter/index.ts`, remove the per-adapter clipping of cross-block ranges (keeping per-input clipping within one block), the "middle block → `blocks.delete`" path and the `@todo support input merging`, and make the tests pass + +## 7. End-to-end + +- [ ] 7.1 Register a minimal header-like text tool with `conversionConfig` and a minimal tool without text inputs (delimiter-like) in `packages/editorjs/e2e/fixtures/main.ts` so cross-tool and unmergeable cases can be driven from the UI +- [ ] 7.2 Add `packages/editorjs/e2e/tests/merge.spec.ts` covering, on chromium and webkit: Backspace at the start of a paragraph merges it into the previous paragraph with the caret at the junction; Backspace at the start of the header-like block merges it into the previous paragraph in one step; Backspace in an empty paragraph removes it; Backspace after an empty paragraph removes that one and keeps the current block's tool; Delete at the end of a paragraph merges the next block; deleting and typing over a cross-block selection joins the edge blocks; Enter over a cross-block selection leaves two blocks; Backspace at the start of a block's second input moves the caret to its first input; Backspace right after and Delete right before the delimiter-like block remove it and leave the caret in place + +## 8. Docs and verification + +- [ ] 8.1 Add a "Merging blocks" section to `docs/input-handling.md` describing how cross-block and boundary deletions map to `BlocksAPI.merge` (and to `blocks.delete` for blocks without text inputs), the conversion of the second block, the empty-block rules and the reliance on `undo-group-by-task` for undo, and a diagram in `docs/diagrams/` if the existing ones no longer match +- [ ] 8.2 Run `yarn workspace @editorjs/core test`, `yarn workspace @editorjs/dom-adapters test`, `yarn workspace @editorjs/sdk test`, `yarn workspace @editorjs/editorjs test:e2e` and `yarn lint` across the affected workspaces; fix any fallout +- [ ] 8.3 Run `openspec validate merge-blocks-on-delete --type change` and fix any reported issues From 77a1716f081397b5ea96ceadec4ab1d43b650d34 Mon Sep 17 00:00:00 2001 From: gohabereg Date: Thu, 5 Nov 2026 00:28:46 +0000 Subject: [PATCH 2/2] docs(openspec): address review on merge-blocks-on-delete - Resolve merged blocks by id up front so later steps never act on a shifted index - Fix getFragments argument order; unformat exactly the appended range - BlocksAPI.merge keeps the caller's caret despite adapter-driven caret updates - Re-set the caret after blocks.delete of a neighbour, always passing its id - Add read-only BlocksAPI.getTextKeys so the adapter decides from the model, not from a DOM registry that is empty until the block renders - Clarify synchronous dispatch and its relation to undo-group-by-task - List all BlocksAPI methods; record word/line boundary deletes and multi-field export as follow-ups Co-Authored-By: Claude Opus 5.5 --- .../changes/merge-blocks-on-delete/design.md | 65 +++++++++++++------ .../merge-blocks-on-delete/proposal.md | 19 +++--- .../merge-blocks-on-delete/specs/core/spec.md | 42 +++++++++--- .../specs/dom-adapters/spec.md | 15 +++-- .../merge-blocks-on-delete/specs/sdk/spec.md | 7 +- .../changes/merge-blocks-on-delete/tasks.md | 25 +++---- 6 files changed, 119 insertions(+), 54 deletions(-) diff --git a/openspec/changes/merge-blocks-on-delete/design.md b/openspec/changes/merge-blocks-on-delete/design.md index 12d49dd5..23d3bae9 100644 --- a/openspec/changes/merge-blocks-on-delete/design.md +++ b/openspec/changes/merge-blocks-on-delete/design.md @@ -20,7 +20,7 @@ Editor.js v2 had per-block contenteditables and merged only on Backspace/Delete - All merge rules in core, so the DOM adapter only maps events to calls. - Exactly one document-changing call per user action (plus the insert/split follow-up when typing or pressing Enter over a selection), all within one browser task. - Inline formatting survives the merge, including between different tools. -- No new tool option and no API besides `BlocksAPI.merge`. +- No new tool option, and no new API besides `BlocksAPI.merge` and the read-only `BlocksAPI.getTextKeys` it needs for the keyboard mapping (Decision 7). **Non-Goals:** @@ -28,6 +28,8 @@ Editor.js v2 had per-block contenteditables and merged only on Backspace/Delete - Selecting non-text neighbours (image, delimiter) on Backspace/Delete — block selection does not exist yet; such neighbours are removed instead (Decision 5). - A two-step "turn a structured block into plain text first, merge on the next keypress" behaviour, and list-style structural clean-up (removing only `items.0`). Both need a tool-level hook; no tool in this repository needs it yet. - v2's whitespace/empty-tag special cases (` `, `` before the caret) — those stem from v2 reading the DOM; v3 reads the model. +- Word and line deletes at a block boundary. `deleteWordBackward`/`deleteSoftLineBackward`/`deleteHardLineBackward` at offset 0 (and their forward counterparts at the end) do a plain merge here; the expected follow-up also removes the word or line on the other side of the boundary (`Hello world` + `|Foo` → `Hello |Foo`). +- Keeping more than the `export` field. A merge keeps only what the second block's `conversionConfig.export` carries; preserving the end block's other text fields (e.g. a quote's caption), and the tail of a non-exported input that a range ends in, is a follow-up that needs a multi-field export. - `insertCompositionText` over a cross-block selection (composition is already a `@todo`). - Multi-client concurrency tests for merges. @@ -48,6 +50,9 @@ interface MergeResult { interface BlocksAPI { merge(params: { block: number | string; userId?: string | number }): MergeResult; merge(params: { index: Index; userId?: string | number }): MergeResult; + + /** Data keys of the block's text inputs in the model, in document order; [] for a block without text inputs */ + getTextKeys(params: { block: number | string }): string[]; } ``` @@ -60,7 +65,9 @@ interface BlocksAPI { *Why one name for both forms:* both collapse everything between two points and join what is left on each side. The range form also removes the text inside the range, which its documentation states up front. "Collapse" was considered and rejected: in DOM and selection terminology a collapsed range is a caret, and collapsing never deletes content; it would also read like folding a block. -*Why a return value:* the junction is the caret position every interactive caller wants, and `merge` computes it anyway. Returning data has precedent (`TextAPI.remove` returns the removed text). `merge` itself does not move the caret — `BlocksManager` deliberately has no caret/adapter dependency (see its class comment about the `BlocksManager → Adapter → EditorAPI → BlocksAPI → BlocksManager` cycle). +*Why a return value:* the junction is the caret position every interactive caller wants, and `merge` computes it anyway. Returning data has precedent (`TextAPI.remove` returns the removed text). `merge` does not place the caret at the junction itself — `BlocksManager` deliberately has no caret/adapter dependency (see its class comment about the `BlocksManager → Adapter → EditorAPI → BlocksAPI → BlocksManager` cycle) — but `BlocksAPI.merge` keeps the caller's caret from being dragged along by the merge's own text events (Decision 8). + +*Why `getTextKeys`:* the adapter has to know whether a neighbour has text inputs before choosing between `merge` and `delete` (Decision 7), and the DOM cannot tell it reliably. The existing `getData` needs a key, so nothing on `BlocksAPI` lists a block's text inputs today. `getTextKeys` is the same check `merge` validates with, exposed read-only; it throws for an unknown block, like `getData`. *No direction:* the second block is always converted into the first (Decision 3). Backspace at the start of B and Delete at the end of A delete the same boundary, so they give the same result and `merge` needs no direction parameter. @@ -68,15 +75,15 @@ interface BlocksAPI { Let the range start at `(A, keyA, s)` and end at `(B, keyB, e)` with `A < B`. For `{ block: b }`: `A = b - 1`, `keyA` = last text input of `A`, `s` = its length; `B = b`, `keyB` = first text input of `B`, `e = 0`. -1. **Validate** (Decision 5) before any mutation. -2. **Remove the range content in B** (B has the highest index, so lower indexes stay valid): remove `[0, e]` from `keyB` and empty every text input of B that the range fully covers (the segments before `keyB`). -3. **Remove the blocks strictly between A and B**, by index range in descending order — not by segment, so blocks without text inputs (which produce no segments) are removed too. +1. **Validate** (Decision 5) before any mutation, and **resolve every block involved to its id**: A, B, and each block strictly between them (by index range, not by segment, so blocks without text inputs — which produce no segments — are included). Indexes shift as soon as step 3 removes a block, so every later step resolves the block's current index from its id right before it mutates. +2. **Remove the range content in B**: remove `[0, e]` from `keyB` and empty every text input of B that the range fully covers (the segments before `keyB`). +3. **Remove the blocks strictly between A and B**, by the ids taken in step 1. 4. **Remove the range content in A**: remove `[s, end]` from `keyA` and empty every text input of A the range fully covers (segments after `keyA`). 5. **If A is now empty** (Decision 4): remove A; B survives with its id and tool, changed only by step 2. Junction → `(B, keyB, 0)`. -6. **Otherwise convert B into A**: compute B's absorbed content (Decision 3) from B's **current** state, append it into `keyA` at `s` (Decision 6), and remove B. Junction → `(A, keyA, s)`. +6. **Otherwise convert B into A**: compute B's absorbed content (Decision 3) from B's **current** state, append it into `keyA` at `s` (Decision 6), and remove B by its id. Junction → `(A, keyA, s)`. 7. Return the junction. -All mutations are dispatched synchronously within the caller's browser task, which is what `undo-group-by-task` needs to record them — together with the adapter's follow-up insert or split — as one undo step. +`merge` is built only from synchronous model operations — `removeText`, `insertText`, `format`, `unformat`, `removeBlock` — so every event it causes is dispatched before it returns and the document is final when the caller gets the junction. It must not be built on `addBlock`, `createDataNode` or `convertBlock`: `BlockNode.createDataNode` dispatches `DataNodeAddedEvent` from a microtask, the only deferred dispatch in the model. That is not an undo problem — `undo-group-by-task` closes a step at `setTimeout(0)`, after the task's microtasks, and those microtask events carry no `userId`, so they are not recorded — which is also why the adapter's follow-up `split` (built on `addBlock`) still groups with the merge. The restriction keeps the "final when it returns" guarantee testable. ### 3. The second block is converted into the first @@ -86,9 +93,9 @@ The first block always survives with its id and tool; the second block is absorb |---|---| | key path (e.g. `'text'`, `'items.0.text'`) | that text input's value **and** inline fragments, from `getBlockTextContent` (key paths and model data keys share the dot notation) | | function | `exportTextContent(data)` — plain string, no fragments | -| absent | B's first text input, value and fragments | +| absent | B's first text input, value and fragments, read directly from the model — never through `exportTextContent`, which throws for a tool without `conversionConfig` | -Anything the export does not carry is dropped with B, exactly as `convertBlock` drops it — e.g. a quote whose export is `'text'` loses its caption, as in v2. A key path that does not resolve to one of B's text inputs absorbs nothing, consistent with `exportTextContent` returning `''` for a missing key; B is still removed. +Anything the export does not carry is dropped with B, exactly as `convertBlock` drops it — e.g. a quote whose export is `'text'` loses its caption, as in v2 (keeping it is a Non-Goal). A key path that does not resolve to one of B's text inputs absorbs nothing, consistent with `exportTextContent` returning `''` for a missing key; B is still removed. `Paragraph` and `@editorjs/header` (on its `v3` branch) both declare `export: 'text'`, so merges between them keep formatting in both directions. @@ -108,7 +115,7 @@ If B has nothing to absorb (empty, or emptied by step 2), step 6 appends nothing ### 5. Validation and unmergeable blocks -A block **without text inputs** (image, delimiter, embed) is **unmergeable**: there is nothing to absorb from it and nothing to append into it. `merge` throws, leaving the document unchanged, when: +A block **without text inputs** in the model (image, delimiter, embed — `getTextKeys` returns `[]`) is **unmergeable**: there is nothing to absorb from it and nothing to append into it. `merge` throws, leaving the document unchanged, when: - `{ block }` does not resolve to a block, or resolves to the first block; - `{ index }` is not a text index, or does not start and end in different blocks (single-block ranges stay on `TextAPI.remove`); @@ -116,9 +123,9 @@ A block **without text inputs** (image, delimiter, embed) is **unmergeable**: th Blocks without text inputs that lie **strictly between** the edges of a range are not joined, only removed (step 3), so they never make a range merge fail. -On the keyboard, an unmergeable neighbour is **removed** instead of merged: Backspace at the start of a block right after an image, or Delete at the end of a block right before one, deletes the image through the existing `api.blocks.delete`, and the caret stays where it is. This is the adapter's mapping (Decision 7), not a `merge` rule: `merge` keeps one meaning — joining two text blocks — and a programmatic caller that merges an image gets an error rather than a silent deletion. +On the keyboard, an unmergeable neighbour is **removed** instead of merged: Backspace at the start of a block right after an image, or Delete at the end of a block right before one, deletes the image through the existing `api.blocks.delete({ block: })` — always with the explicit id, because `delete()` without one deletes the caret's block — and the caret stays at the same block id, key and offset (Decision 8). This is the adapter's mapping (Decision 7), not a `merge` rule: `merge` keeps one meaning — joining two text blocks — and a programmatic caller that merges an image gets an error rather than a silent deletion. -There is no `canMerge`: every failure condition is structural and visible to the caller up front. The DOM adapter never hits them, because it checks the neighbour's registered text inputs before choosing between `merge` and `delete`. +There is no `canMerge`: every failure condition is structural and visible to the caller up front. The DOM adapter never hits them, because it checks the neighbour's text inputs with `getTextKeys` before choosing between `merge` and `delete`. ### 6. Appending with formatting hygiene @@ -130,14 +137,14 @@ appendTextContent(blockIndex: number, key: DataKey, offset: number, content: { v 1. If `content.value` is empty, return. 2. `model.insertText(userId, blockIndex, key, content.value, offset)`. -3. Normalize the inserted range: inserted text takes the formatting of the text it is inserted into, so appending at the end of an input that ends with a bold run makes the merged text bold. This holds for the current inline tree (`ParentInlineNode.insertText` inserts into the child found by `findChildByIndex`) and for the run model proposed in [#198](https://github.com/editor-js/document-model/pull/198) (`RunList.insert` extends the run at the offset with its marks). The clean-up only uses the model's public operations, so it works with either: read `model.getFragments(blockIndex, key, undefined, offset, offset + value.length)` and `model.unformat(...)` every tool found there. +3. Normalize the inserted range: inserted text takes the formatting of the text it is inserted into, so appending at the end of an input that ends with a bold run makes the merged text bold. This holds for the current inline tree (`ParentInlineNode.insertText` inserts into the child found by `findChildByIndex`) and for the run model proposed in [#198](https://github.com/editor-js/document-model/pull/198) (`RunList.insert` extends the run at the offset with its marks). The clean-up only uses the model's public operations, so it works with either: read `model.getFragments(blockIndex, key, offset, offset + value.length)` and, for every tool found there, `model.unformat(...)` over exactly `[offset, offset + value.length)` — not over the fragment's own bounds, which may start before the junction and would strip formatting from text that was already there. 4. Re-apply each `content.fragments` entry with `model.format(...)` shifted by `offset`. Fragments of inline tools A's tool does not enable are kept, consistent with `splitBlock`. ### 7. The DOM adapter maps events to calls -`DOMBlockToolAdapter` decides only *which call* an event maps to, from facts it already has (its DOM, the shared `InputsRegistry`); every document rule is in `merge`. +`DOMBlockToolAdapter` decides only *which call* an event maps to, from its own DOM and inputs and, for its neighbours, from the model through the API; every document rule is in `merge`. **Classifying the target range.** The adapter converts the target range to a model `Index` (`CaretAdapter`'s selection-to-`Index` logic, refactored so it accepts any DOM `Range` — a `beforeinput` target range is not always the current selection, e.g. drag-and-drop). The range **crosses blocks** when its segments belong to more than one block. The `isCrossInputSelection` flag on `BeforeInputUIEvent` is not used for this: `BlocksUI` computes it as `startContainer !== endContainer`, which is also true inside a single input with formatting, because start and end land in different text nodes. The existing `insertParagraph` check on that flag moves to the same `Index`-based test. @@ -147,27 +154,45 @@ Fragments of inline tools A's tool does not enable are kept, consistent with `sp | insert type (`insertText`, `insertFromPaste`, `insertFromDrop`, `insertReplacementText`), range crossing blocks | same, then `api.text.insert` at the junction | | `insertParagraph`, range crossing blocks | same, then `api.blocks.split` at the junction | | any type, range across several inputs of one block | unchanged: per-input `api.text.remove` by the block's adapter, then the type's usual insert/split | -| backward delete type, collapsed at offset 0 of the block's first text input | previous block has a registered text input → `merge({ block: current })`, caret → junction; previous block has none → `api.blocks.delete` of the previous block, caret unchanged; no previous block → no-op | -| forward delete type, collapsed at the end of the block's last text input | next block has a registered text input → `merge({ block: next })`, caret → junction; next block has none → `api.blocks.delete` of the next block, caret unchanged; no next block → no-op | +| backward delete type, collapsed at offset 0 of the block's first text input | previous block has a text input → `merge({ block: current })`, caret → junction; previous block has none → `api.blocks.delete({ block: })`, caret re-set to the same block id, key and offset; no previous block → no-op | +| forward delete type, collapsed at the end of the block's last text input | next block has a text input → `merge({ block: next })`, caret → junction; next block has none → `api.blocks.delete({ block: })`, caret re-set to the same block id, key and offset; no next block → no-op | | backward/forward delete type at an edge between two inputs of the same block | caret moves to the end of the previous / start of the next input; no document change | | anything within one input | unchanged (`api.text.remove` / `insert` / `split`) | -Backward types are `deleteContentBackward`, `deleteWordBackward`, `deleteSoftLineBackward`, `deleteHardLineBackward`; forward types are their `Forward` counterparts. Boundary detection uses the collapsed DOM selection and the input type, **not** the browser's target range, because browsers disagree on the target range they report for Backspace at the start of a block. Neighbours are found with `api.blocks.getIdByIndex` and their text inputs with `InputsRegistry.getBlockInputs`. +Backward types are `deleteContentBackward`, `deleteWordBackward`, `deleteSoftLineBackward`, `deleteHardLineBackward`; forward types are their `Forward` counterparts. Boundary detection uses the collapsed DOM selection and the input type, **not** the browser's target range, because browsers disagree on the target range they report for Backspace at the start of a block. Neighbours are found with `api.blocks.getIdByIndex`, and whether they have text inputs with `api.blocks.getTextKeys` — from the model, **not** `InputsRegistry.getBlockInputs`. Blocks render asynchronously (`BlockRenderer` awaits the tool's `render()`), and a block's inputs are registered only once its tool attaches them, so an empty registry entry can mean "not rendered yet". Deciding from the registry would turn Delete before a still-rendering paragraph into deleting that paragraph and its persisted text. The adapter's own block is rendered (the event fired in it), so its own first/last input still comes from its own inputs. **Only one adapter acts per event**: the one owning the range start (or the caret). The per-adapter clipping of *cross-block* ranges and the "middle block → `api.blocks.delete`" path in `#handleDeleteInContentEditable` are removed, together with the `@todo support input merging`; per-input clipping within one block stays. **The acting adapter may lose its own block.** Backspace at the start of B removes B; a range starting at offset 0 of A removes A. Either way the adapter handling the event is destroyed by the merge it called. Every follow-up — caret placement, `text.insert`, `blocks.split` — therefore addresses `MergeResult.block` and goes through shared services (`CaretAdapter`, the API), never `this.blockId` or the adapter's own inputs. +### 8. Caret + +Two existing behaviours would move the caret wrongly around a merge or a neighbour removal: + +- **Adapter-driven caret updates.** `appendTextContent` calls `insertText`, whose `TextAddedEvent` carries the merge's `userId`. The DOM adapter's model-to-DOM sync moves that user's caret to the end of the inserted text (`BlockToolAdapter#handleModelUpdateForContentEditableElement`) — so a programmatic `merge` would pull the local caret into the merged input even when it was in a block the merge never touched. +- **Local block removal does not shift the local caret.** `EditorJSModel` adjusts the caret only for remote changes (`#updateUserCaretByRemoteChange`). After a local `removeBlock` of a block before the caret, the caret's `blockIndex` points one block too far. + +**`BlocksAPI.merge` keeps the caret.** Before delegating to `BlocksManager.mergeBlocks`, the wrapper reads the caret of `userId` from the model and records the block id of each of its segments. After the merge it re-sets that caret: + +- to the same block ids, keys and offsets, with indexes re-resolved, when the caret lies in blocks the merge does not change, or in A at or before the junction; +- to the junction otherwise — when it was in a removed block, in removed content, or in B (whose content moved or shifted); +- not at all when the user has no caret. + +This is done in the core `BlocksAPI` wrapper, which already holds the model, so `BlocksManager` stays free of caret logic. It is scoped to `merge` on purpose: the same model-to-DOM caret update is what places the caret after typing and after undo/redo, so suppressing it in the adapter in general would break those. + +**The adapter re-sets the caret after removing a neighbour.** After `api.blocks.delete({ block: })` (Decision 7), the adapter sets the caret explicitly to the same block id, key and offset it had before, resolving the block's index after the deletion. After `merge` it sets it to the junction, as before. + ## Risks / Trade-offs - **Browser differences around boundary events** → boundary detection relies on the collapsed DOM selection and the input type, not on the reported target range; covered by Playwright e2e on chromium and webkit (the browsers the e2e project runs). -- **Caret races with adapter-side caret updates.** The adapter's model-to-DOM text sync also updates the caret index after `TextAddedEvent`/`TextRemovedEvent`. The adapter sets the caret to the returned junction after `merge` returns, so its write is last; e2e tests assert the caret lands at the junction. +- **Caret races with adapter-side caret updates.** The adapter's model-to-DOM text sync moves the caret after `TextAddedEvent`. `BlocksAPI.merge` re-sets the caret after the merge's events (Decision 8), and the adapter sets it to the junction after `merge` returns, so the intended write is always last. Integration tests with real DOM adapters assert a caret in an untouched block stays put; e2e tests assert it lands at the junction on the keyboard. +- **Unrendered neighbours.** Choosing between `merge` and `delete` from the model means a neighbour that has not finished rendering is merged like any text block; its DOM catches up when it renders from the merged model state. - **Formatting bleed at the junction** → explicit unformat-then-reformat step (Decision 6), covered by a test that merges into an input ending with a formatted run. -- **Content outside the export is dropped.** A range ending in a quote's caption, or Backspace into a quote with a caption, drops what the quote's export does not carry. Same rule as `convert`, and v2's behaviour; worth stating in the `merge` docs. +- **Content outside the export is dropped.** A range ending in a quote's caption, or Backspace into a quote with a caption, drops what the quote's export does not carry. Same rule as `convert`, and v2's behaviour; worth stating in the `merge` docs. Acceptable for this change; a multi-field export is the follow-up (Non-Goals). - **Export functions lose formatting.** Tools that want formatting to survive a merge should use a key path. Documented on `conversionConfig.export`. - **Behaviour change for cross-block selections:** delete/type/paste/Enter now join the edge blocks. Intended, but it changes what current users of the playground see. - **Collaboration/OT:** only existing operations are emitted, so no new transform support is needed; concurrent edits during a merge go through the existing machinery but are not specifically tested here. -- **Undo depends on `undo-group-by-task`.** Until #201/#203 land, a merge is several undo steps and undoing its block removal throws. Undo tests for merging belong in that change or after it lands; this change only asserts that all of a merge's events are emitted synchronously. +- **Undo depends on `undo-group-by-task`.** Until #201/#203 land, a merge is several undo steps and undoing its block removal throws. Undo tests for merging belong in that change or after it lands; this change only asserts that all of a merge's events are emitted before `merge` returns. - **Removing non-text neighbours is immediate.** Backspace after an image deletes the image with no intermediate "selected" state. Accepted until block selection exists; the adapter mapping is the only place to change then. ## Open Questions diff --git a/openspec/changes/merge-blocks-on-delete/proposal.md b/openspec/changes/merge-blocks-on-delete/proposal.md index 269d12e5..2a6024bc 100644 --- a/openspec/changes/merge-blocks-on-delete/proposal.md +++ b/openspec/changes/merge-blocks-on-delete/proposal.md @@ -15,7 +15,9 @@ Today none of these join anything. Backspace/Delete at a boundary is a no-op, an - **One new API method, `BlocksAPI.merge()`**, backed by a new `BlocksManager.mergeBlocks()`, in two forms: - **`merge({ block })`** merges `block` into the block **before it**. Only neighbouring blocks can be merged, so one block is enough. - **`merge({ index })`** takes a text range that starts in one block and ends in another: the text inside the range is removed, the blocks strictly between are removed, and the end block is merged into the start block at the range start. `merge({ block })` is exactly `merge({ index })` over the empty range from the end of the previous block to the start of `block`. - - Both return the junction `{ block, key, offset }` — where the two blocks met — so callers can place the caret without re-deriving it. `merge` itself never moves the caret, like `split` and `convert`. + - Both return the junction `{ block, key, offset }` — where the two blocks met — so callers can place the caret without re-deriving it. + - **The caret is kept.** The merge's own text events would otherwise let the DOM adapter drag the caller's caret into the merged input; `merge` restores a caret that was outside the joined blocks (or in the first block before the junction) to the same position, and puts any other caret of that user at the junction. +- **One read-only helper, `BlocksAPI.getTextKeys({ block })`**, lists a block's text inputs from the model. The DOM adapter needs it to tell a block without text inputs from one that simply has not rendered yet. - **The second block is always converted into the first.** The first block survives with its id and tool; the second block's content is appended to it and the second block is removed. There is no separate convert step and no direction: Backspace at the start of B and Delete at the end of A delete the same boundary and give the same result. Blocks of different tools merge in one step, as in v2. - **The second block's tool decides what is absorbed**, through its existing `conversionConfig.export`: - a key path → that text input, **with its inline formatting** (read from the model, no plain-string round trip); @@ -23,7 +25,7 @@ Today none of these join anything. Backspace/Delete at a boundary is a no-op, an - none → its first text input. Content the export does not carry is dropped with the block, exactly as `convert` drops it. The content lands in the first block's text input at the junction (its last text input for `{ block }`, the range's start input for `{ index }`). - **Empty blocks give way.** If the first block is empty (after the range is removed), it is removed instead and the second block survives with its id and tool — Backspace after an empty line or Delete in an empty line removes that line, as in v2. If the second block has nothing to absorb, it is simply removed. -- **Blocks without text inputs are unmergeable.** `merge({ block })` throws when either of the two blocks has no text inputs. Backspace right after such a block (an image, a delimiter) or Delete right before it **removes that block** instead, through the existing `blocks.delete`. In a range, blocks without text inputs lying between the edges are removed like any other block in between. +- **Blocks without text inputs are unmergeable.** `merge({ block })` throws when either of the two blocks has no text inputs. Backspace right after such a block (an image, a delimiter) or Delete right before it **removes that block** instead, through the existing `blocks.delete({ block: })`, and the caret stays where it was. In a range, blocks without text inputs lying between the edges are removed like any other block in between. - **Errors:** `merge` throws, leaving the document unchanged, when the block does not exist or is the first block, when the index is not a text index or does not start and end in different blocks, or when either block to be joined has no text inputs. No `canMerge`, no new tool option — `conversionConfig` only refines what is absorbed, it never blocks a merge. - **Undo grouping is out of scope.** A merge emits several model events, which today's `UndoRedoManager` records as several undo steps. The open `undo-group-by-task` change ([#201](https://github.com/editor-js/document-model/pull/201), implemented in [#203](https://github.com/editor-js/document-model/pull/203)) records all events of one browser task as one undo step, which makes a merge — and a merge plus its follow-up insert — a single step without anything in this change. It also fixes undo of block insertion/removal, which currently throws, so undoing a merge depends on it. - **`DOMBlockToolAdapter` only maps events to calls; the merge rules live in core:** @@ -31,9 +33,10 @@ Today none of these join anything. Backspace/Delete at a boundary is a no-op, an - delete input type over a cross-block range → the adapter owning the range start calls `merge({ index })` once and puts the caret at the junction; - insert types or Enter over a cross-block range → the same, followed by `text.insert` or `blocks.split` at the junction; - a range across several inputs of the **same** block keeps the existing per-input `text.remove` handling; - - Backspace at the start of a block's first input / Delete at the end of its last input → `merge({ block })` with the current / next block when the neighbour has text inputs, `blocks.delete` of the neighbour when it has none, nothing when there is no neighbour; + - Backspace at the start of a block's first input / Delete at the end of its last input → `merge({ block })` with the current / next block when the neighbour has text inputs in the model (`getTextKeys`, not the DOM registry, which is empty until the block renders), `blocks.delete({ block })` of the neighbour when it has none, nothing when there is no neighbour; - Backspace/Delete at an edge between two inputs of the same block → caret moves to the neighbouring input (no document change). The merge may remove the acting adapter's own block, so every follow-up (caret, insert, split) addresses the block id returned by `merge`. The per-adapter cross-block slicing and the "middle block → `blocks.delete`" path are removed. +- **Left for follow-ups:** word/line deletes at a block boundary also removing the word or line on the other side (they do a plain merge here), and keeping the end block's text fields beyond its `export`. - **Deliberate deviations from v2:** - inline formatting survives a merge between different tools when the second tool's export is a key path; - text blocks v2 treated as unmergeable (target without a `merge()` method, or different tools without conversion configs) now merge — v2 only moved the caret; @@ -47,19 +50,19 @@ None. ### Modified Capabilities -- `core`: new "Block merging" requirement (`BlocksManager.mergeBlocks` / `BlocksAPI.merge`, both forms, conversion of the second block, empty and unmergeable blocks, junction); the "EditorAPI surface" requirement lists `merge` on `BlocksAPI`. -- `sdk`: the "EditorAPI surface" requirement gains the `BlocksAPI.merge` signature and its `MergeResult` type. +- `core`: new "Block merging" requirement (`BlocksManager.mergeBlocks` / `BlocksAPI.merge`, both forms, conversion of the second block, empty and unmergeable blocks, junction, caret, `getTextKeys`); the "EditorAPI surface" requirement lists every `BlocksAPI` method, `merge` and `getTextKeys` included. +- `sdk`: the "EditorAPI surface" requirement gains the `BlocksAPI.merge` and `getTextKeys` signatures and the `MergeResult` type. - `dom-adapters`: the "Block-level DOM binding and input translation" requirement replaces per-adapter cross-block deletion with a single `merge` call, and adds the boundary Backspace/Delete mapping, including removal of neighbours without text inputs. ## Impact - **Code**: - - `packages/sdk/src/api/BlocksAPI.ts` — `merge` signature and `MergeResult` type. - - `packages/core/src/api/BlocksAPI.ts` — thin wrapper. + - `packages/sdk/src/api/BlocksAPI.ts` — `merge` and `getTextKeys` signatures, `MergeResult` type. + - `packages/core/src/api/BlocksAPI.ts` — thin wrappers; `merge` keeps the caller's caret. - `packages/core/src/components/BlockManager.ts` — `mergeBlocks` and the internal content-append helper. - `packages/dom-adapters/src/BlockToolAdapter/index.ts` (and `CaretAdapter` for range → `Index`) — map events to `merge`; remove per-adapter cross-block slicing. - Co-located Jest specs; Playwright e2e in `packages/editorjs/e2e/tests`. -- **APIs**: one additive method on `BlocksAPI`. No breaking changes, no tool changes required — `Paragraph` and `@editorjs/header` merge without opting in. +- **APIs**: two additive methods on `BlocksAPI` (`merge`, read-only `getTextKeys`). No breaking changes, no tool changes required — `Paragraph` and `@editorjs/header` merge without opting in. - **Depends on**: `undo-group-by-task` ([#201](https://github.com/editor-js/document-model/pull/201) / [#203](https://github.com/editor-js/document-model/pull/203)) for merges to undo as one step and for undo of the removed blocks to work at all. Related open work: the run-based inline model ([#198](https://github.com/editor-js/document-model/pull/198)) — the junction formatting clean-up is written against the model's public operations, so it holds before and after; clipboard paste ([#191](https://github.com/editor-js/document-model/pull/191)) hands selections across several inputs back to `insertFromPaste`, which this change routes through `merge({ index })`. - **Model**: no changes to `@editorjs/model`; everything is composed from existing `getBlockTextContent`/`insertText`/`removeText`/`format`/`unformat`/`getFragments`/`removeBlock` operations, so collaboration needs no new OT support. - **Behaviour users will notice**: deleting, typing, pasting or pressing Enter over a cross-block selection now joins the edge blocks; Backspace/Delete at block boundaries now merge, or remove a neighbouring block that has no text inputs. diff --git a/openspec/changes/merge-blocks-on-delete/specs/core/spec.md b/openspec/changes/merge-blocks-on-delete/specs/core/spec.md index 6554f5fa..991d5ad6 100644 --- a/openspec/changes/merge-blocks-on-delete/specs/core/spec.md +++ b/openspec/changes/merge-blocks-on-delete/specs/core/spec.md @@ -1,7 +1,7 @@ ## MODIFIED Requirements ### Requirement: EditorAPI surface -The system SHALL expose an `EditorAPI` aggregating `BlocksAPI` (insert/insertMany/delete/move/render/clear/getBlocksCount/split/convert/merge), `SelectionAPI` (applyInlineTool, selectedBlocks), `DocumentAPI` (serialized data, onUpdate, insertData/removeData/modifyData, undo/redo), and `TextAPI` (insert/remove/format/unformat/getFragments/get) to tools, plugins, and adapters. +The system SHALL expose an `EditorAPI` aggregating `BlocksAPI` (insert/insertMany/delete/move/render/clear/getBlocksCount/getIndexById/getIdByIndex/getData/createData/removeData/updateValue/split/convert/merge/getTextKeys), `SelectionAPI` (applyInlineTool, selectedBlocks), `DocumentAPI` (serialized data, onUpdate, insertData/removeData/modifyData, undo/redo), 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 @@ -23,9 +23,13 @@ The system SHALL provide `BlocksManager.mergeBlocks()`, exposed as `BlocksAPI.me - `{ block }` SHALL merge the given block into the block immediately before it. - `{ index }` SHALL accept a text `Index` that starts in one block and ends in a later block; it SHALL remove the content inside the range, remove every block strictly between the two, and merge the end block into the start block at the range start. `{ block }` SHALL behave exactly as `{ index }` over the empty range from the end of the previous block's last text input to the start of the given block's first text input. -Merging SHALL keep the first block with its id and tool and convert the second block into it: the second block's content selected by its tool's `conversionConfig.export` — the text input at that key path with its inline fragments when it is a key path, the export function's plain-string result when it is a function, or its first text input with its inline fragments when it is absent — SHALL be appended to the first block's text input at the junction (the last text input for `{ block }`, the range's start input for `{ index }`), and the second block SHALL be removed. Appended text SHALL NOT inherit formatting from the text before the junction. When the first block has no text content left, the first block SHALL be removed instead and the second block kept with its id and tool. A block without text inputs SHALL be unmergeable. A `conversionConfig.export` key path that does not resolve to a text input of the second block SHALL absorb nothing, the second block still being removed. +Merging SHALL keep the first block with its id and tool and convert the second block into it: the second block's content selected by its tool's `conversionConfig.export` — the text input at that key path with its inline fragments when it is a key path, the export function's plain-string result when it is a function, or its first text input with its inline fragments, read from the model without calling `exportTextContent`, when it is absent — SHALL be appended to the first block's text input at the junction (the last text input for `{ block }`, the range's start input for `{ index }`), and the second block SHALL be removed. Appended text SHALL NOT inherit formatting from the text before the junction. When the first block has no text content left, the first block SHALL be removed instead and the second block kept with its id and tool. A block without text inputs SHALL be unmergeable. A `conversionConfig.export` key path that does not resolve to a text input of the second block SHALL absorb nothing, the second block still being removed. -`merge()` SHALL return the junction `{ block, key, offset }` — the id of the surviving block, the data key and the offset where the merged content starts — and SHALL NOT move the caret. It SHALL throw, leaving the document unchanged, when `{ block }` does not resolve to a block or resolves to the first block, when `{ index }` is not a text index or does not start and end in different blocks, or when either block to be joined has no text inputs. Blocks without text inputs lying strictly between the edges of `{ index }` SHALL be removed and SHALL NOT make the call throw. All mutations of one call SHALL be dispatched synchronously. +The blocks involved SHALL be resolved to their ids before the first mutation, and each later mutation SHALL address its block by id, so that removing a block does not make a later step act on a shifted index. + +`merge()` SHALL return the junction `{ block, key, offset }` — the id of the surviving block, the data key and the offset where the merged content starts. It SHALL NOT let its own text events move the caret of `userId`: a caret lying in blocks the merge does not change, or in the first block at or before the junction, SHALL be left at the same block ids, keys and offsets; any other caret of that user SHALL be placed at the junction. It SHALL throw, leaving the document unchanged, when `{ block }` does not resolve to a block or resolves to the first block, when `{ index }` is not a text index or does not start and end in different blocks, or when either block to be joined has no text inputs. Blocks without text inputs lying strictly between the edges of `{ index }` SHALL be removed and SHALL NOT make the call throw. `merge()` SHALL be composed of synchronous model operations only, so that every event it causes is dispatched before it returns. + +The system SHALL provide `BlocksAPI.getTextKeys({ block })`, returning the data keys of the block's text inputs in the model in document order, or an empty array for a block without text inputs, and throwing for an unknown block. #### Scenario: Merging a paragraph into the previous paragraph - **GIVEN** two paragraphs "First" and "Second" @@ -45,7 +49,7 @@ Merging SHALL keep the first block with its id and tool and convert the second b #### Scenario: Second block without conversion config - **GIVEN** the second block's tool declares no `conversionConfig` - **WHEN** the block is merged -- **THEN** its first text input, with its inline fragments, is appended and the merge does not throw +- **THEN** its first text input, with its inline fragments, is appended, `exportTextContent` is not called, and the merge does not throw #### Scenario: Content outside the export is dropped - **GIVEN** the second block has a second, non-empty text input that its export key path does not point to @@ -57,6 +61,11 @@ Merging SHALL keep the first block with its id and tool and convert the second b - **WHEN** an unformatted block is merged into it - **THEN** the appended text carries no italic formatting +#### Scenario: Formatting before the junction is kept +- **GIVEN** the first block's text input ends with a bold run that starts before the junction +- **WHEN** a block is merged into it +- **THEN** the text before the junction stays bold up to the junction and the appended text is not bold + #### Scenario: Previous block is empty - **GIVEN** an empty paragraph followed by a header "Title" - **WHEN** `merge({ block:
})` is called @@ -75,7 +84,12 @@ Merging SHALL keep the first block with its id and tool and convert the second b #### Scenario: Merging a range across several blocks - **GIVEN** an index starting in block 0 and ending in block 3, where block 2 has no text inputs - **WHEN** `merge({ index })` is called -- **THEN** blocks 1 and 2 are removed and block 3's remaining content is merged into block 0 +- **THEN** blocks 1 and 2 are removed, block 3's remaining content is merged into block 0, and block 3 itself is removed — no other block is + +#### Scenario: Merge events are dispatched before it returns +- **GIVEN** a listener on model events +- **WHEN** `merge()` is called +- **THEN** every event the merge causes has been received when `merge()` returns #### Scenario: Range starting at the beginning of the first block - **GIVEN** a paragraph "Hello" followed by a header "World" and an index from offset 0 of the paragraph to offset 2 of the header @@ -87,10 +101,20 @@ Merging SHALL keep the first block with its id and tool and convert the second b - **WHEN** `merge()` is called - **THEN** it throws an error describing the problem and the document is unchanged -#### Scenario: Merging does not move the caret -- **GIVEN** the user's caret is in another block -- **WHEN** `merge()` is called -- **THEN** the caret is not updated by the merge +#### Scenario: Merging keeps a caret in an untouched block +- **GIVEN** real DOM adapters and the user's caret in a block after the two blocks being merged +- **WHEN** `merge()` is called for that user +- **THEN** the caret stays at the same block id, key and offset, although the merge's `TextAddedEvent` reached the adapter of the merged input + +#### Scenario: Caret inside the merged blocks +- **GIVEN** the user's caret is in the second block of the merge +- **WHEN** `merge()` is called for that user +- **THEN** the caret is placed at the returned junction + +#### Scenario: Listing a block's text inputs +- **GIVEN** a paragraph and a block without text inputs +- **WHEN** `getTextKeys()` is called for each +- **THEN** it returns `['text']` for the paragraph and `[]` for the other block, whether or not the block has finished rendering #### Scenario: Merging next to a block without text inputs - **GIVEN** a block without text inputs (e.g. an image) followed by a paragraph diff --git a/openspec/changes/merge-blocks-on-delete/specs/dom-adapters/spec.md b/openspec/changes/merge-blocks-on-delete/specs/dom-adapters/spec.md index 436ed279..16633c18 100644 --- a/openspec/changes/merge-blocks-on-delete/specs/dom-adapters/spec.md +++ b/openspec/changes/merge-blocks-on-delete/specs/dom-adapters/spec.md @@ -1,7 +1,7 @@ ## MODIFIED Requirements ### Requirement: Block-level DOM binding and input translation -The system SHALL provide `DOMBlockToolAdapter`, attached by tools to a contenteditable element for a model data key, which intercepts `beforeinput` events and applies model text-add/remove events back into the DOM. A target range SHALL be treated as crossing blocks when its model `Index` has segments in more than one block. Deletions that cross a block boundary — a target range spanning blocks, or a collapsed caret at the start of a block's first text input or the end of its last text input with a delete input type — SHALL be performed by exactly one adapter: through a single `api.blocks.merge()` call when the blocks on both sides have text inputs, after which the adapter SHALL place the caret at the returned junction, or through `api.blocks.delete()` of the neighbouring block when that block has no text inputs. Adapters SHALL NOT clip cross-block ranges or join blocks themselves, and every follow-up after `merge()` SHALL address the block id it returns, since the merge may remove the acting adapter's own block. +The system SHALL provide `DOMBlockToolAdapter`, attached by tools to a contenteditable element for a model data key, which intercepts `beforeinput` events and applies model text-add/remove events back into the DOM. A target range SHALL be treated as crossing blocks when its model `Index` has segments in more than one block. Deletions that cross a block boundary — a target range spanning blocks, or a collapsed caret at the start of a block's first text input or the end of its last text input with a delete input type — SHALL be performed by exactly one adapter: through a single `api.blocks.merge()` call when the blocks on both sides have text inputs, after which the adapter SHALL place the caret at the returned junction, or through `api.blocks.delete({ block })` with the neighbouring block's id when that block has no text inputs, after which the adapter SHALL re-set the caret to the same block id, key and offset. Whether a neighbouring block has text inputs SHALL be decided from the model with `api.blocks.getTextKeys()`, not from the inputs registered in the DOM, which stay empty until the block has rendered. Adapters SHALL NOT clip cross-block ranges or join blocks themselves, and every follow-up after `merge()` SHALL address the block id it returns, since the merge may remove the acting adapter's own block. #### Scenario: Text insertion via beforeinput - **GIVEN** a `beforeinput` event of type `insertText`, `insertCompositionText`, `insertFromPaste`, `insertFromDrop`, or `insertReplacementText` @@ -19,19 +19,24 @@ The system SHALL provide `DOMBlockToolAdapter`, attached by tools to a contented - **THEN** the adapter owning the range start calls `api.blocks.merge({ index })` and then inserts the data at the returned junction #### Scenario: Backspace at the start of a block -- **GIVEN** the DOM selection is collapsed at offset 0 of a block's first text input, the input type is `deleteContentBackward`, `deleteWordBackward`, `deleteSoftLineBackward` or `deleteHardLineBackward`, and the previous block has a registered text input +- **GIVEN** the DOM selection is collapsed at offset 0 of a block's first text input, the input type is `deleteContentBackward`, `deleteWordBackward`, `deleteSoftLineBackward` or `deleteHardLineBackward`, and the previous block has a text input in the model - **WHEN** the `beforeinput` event fires - **THEN** the adapter calls `api.blocks.merge({ block })` with its own block and places the caret at the returned junction, regardless of the target range reported by the browser #### Scenario: Delete at the end of a block -- **GIVEN** the DOM selection is collapsed at the end of a block's last text input, the input type is the forward counterpart of a backward delete type, and the next block has a registered text input +- **GIVEN** the DOM selection is collapsed at the end of a block's last text input, the input type is the forward counterpart of a backward delete type, and the next block has a text input in the model - **WHEN** the `beforeinput` event fires - **THEN** the adapter calls `api.blocks.merge({ block })` with the next block and places the caret at the returned junction +#### Scenario: Delete before a block that has not rendered yet +- **GIVEN** the caret is at the end of a block's last text input, and the next block has persisted text in the model but its `render()` has not finished, so it has no registered inputs +- **WHEN** a forward delete `beforeinput` event fires +- **THEN** the adapter calls `api.blocks.merge({ block })` with the next block and does not call `api.blocks.delete` + #### Scenario: Backspace or Delete next to a block without text inputs -- **GIVEN** the caret is at the start of a block's first text input with a backward delete type, or at the end of its last text input with a forward delete type, and the neighbouring block in that direction has no registered text input +- **GIVEN** the caret is at the start of a block's first text input with a backward delete type, or at the end of its last text input with a forward delete type, and the neighbouring block in that direction has no text input in the model - **WHEN** the `beforeinput` event fires -- **THEN** the adapter calls `api.blocks.delete()` for that neighbouring block, does not call `api.blocks.merge()`, and leaves the caret where it is +- **THEN** the adapter calls `api.blocks.delete({ block })` with that neighbouring block's id, does not call `api.blocks.merge()`, and re-sets the caret to the same block id, key and offset, so that after removing the previous block it is not left one block too far #### Scenario: Backspace or Delete at the edge of the document - **GIVEN** the caret is at the start of the first block with a backward delete type, or at the end of the last block with a forward delete type diff --git a/openspec/changes/merge-blocks-on-delete/specs/sdk/spec.md b/openspec/changes/merge-blocks-on-delete/specs/sdk/spec.md index df94fc9f..472f2f00 100644 --- a/openspec/changes/merge-blocks-on-delete/specs/sdk/spec.md +++ b/openspec/changes/merge-blocks-on-delete/specs/sdk/spec.md @@ -1,7 +1,7 @@ ## MODIFIED Requirements ### Requirement: EditorAPI surface -The system SHALL expose an `EditorAPI` type aggregating `BlocksAPI`, `SelectionAPI`, `DocumentAPI`, `TextAPI`, and `PluginsAPI` — the API object passed into tools, plugins, and adapters. The `BlocksAPI` interface SHALL declare `merge` alongside `split` and `convert` as two overloads — `merge(params: { block: number | string; userId?: string | number }): MergeResult` and `merge(params: { index: Index; userId?: string | number }): MergeResult` — with `MergeResult` exported as `{ block: string; key: string; offset: number }`. +The system SHALL expose an `EditorAPI` type aggregating `BlocksAPI`, `SelectionAPI`, `DocumentAPI`, `TextAPI`, and `PluginsAPI` — the API object passed into tools, plugins, and adapters. The `BlocksAPI` interface SHALL declare `merge` alongside `split` and `convert` as two overloads — `merge(params: { block: number | string; userId?: string | number }): MergeResult` and `merge(params: { index: Index; userId?: string | number }): MergeResult` — with `MergeResult` exported as `{ block: string; key: string; offset: number }`, and SHALL declare `getTextKeys(params: { block: number | string }): string[]`. #### Scenario: Tool receives the aggregated API - **GIVEN** a tool is constructed by the core orchestrator @@ -18,4 +18,9 @@ The system SHALL expose an `EditorAPI` type aggregating `BlocksAPI`, `SelectionA - **WHEN** it needs to merge a block into the previous one, or to remove a cross-block range and join its edges - **THEN** it calls `api.blocks.merge({ block })` or `api.blocks.merge({ index })` and receives the junction as a `MergeResult` +#### Scenario: Checking whether a block has text inputs +- **GIVEN** an adapter, tool or plugin holds an `EditorAPI` instance +- **WHEN** it needs to know a block's text inputs regardless of whether the block is rendered +- **THEN** it calls `api.blocks.getTextKeys({ block })` and receives their data keys from the model + Implemented in `src/api/EditorAPI.ts`, `src/api/{BlocksAPI,DocumentAPI,SelectionAPI,TextAPI,PluginsAPI}.ts`. diff --git a/openspec/changes/merge-blocks-on-delete/tasks.md b/openspec/changes/merge-blocks-on-delete/tasks.md index 00040ac9..e08db416 100644 --- a/openspec/changes/merge-blocks-on-delete/tasks.md +++ b/openspec/changes/merge-blocks-on-delete/tasks.md @@ -1,6 +1,6 @@ ## 1. SDK contract -- [ ] 1.1 Add `MergeResult` (`{ block: string; key: string; offset: number }`) and two `merge` overloads — `merge(params: { block: number | string; userId?: string | number }): MergeResult` and `merge(params: { index: Index; userId?: string | number }): MergeResult` — to `BlocksAPI` in `packages/sdk/src/api/BlocksAPI.ts`, next to `split`/`convert`; document both forms, that the second block is converted into the first via its `conversionConfig.export`, that the range form removes the content inside the range, that blocks without text inputs are unmergeable, and that it does not move the caret; export `MergeResult` from the package entry +- [ ] 1.1 Add `MergeResult` (`{ block: string; key: string; offset: number }`) and two `merge` overloads — `merge(params: { block: number | string; userId?: string | number }): MergeResult` and `merge(params: { index: Index; userId?: string | number }): MergeResult` — to `BlocksAPI` in `packages/sdk/src/api/BlocksAPI.ts`, next to `split`/`convert`, plus `getTextKeys(params: { block: number | string }): string[]`; document both `merge` forms, that the second block is converted into the first via its `conversionConfig.export`, that the range form removes the content inside the range, that blocks without text inputs are unmergeable, that the caret is kept unless it was inside the joined blocks (then it goes to the junction), and that `getTextKeys` reads the model and works for blocks that have not rendered yet; export `MergeResult` from the package entry - [ ] 1.2 Note on `conversionConfig.export` in `packages/sdk/src/entities/BlockTool.ts` that it also decides what is absorbed when the block is merged, and that a key path keeps inline formatting while a function does not - [ ] 1.3 Run `yarn workspace @editorjs/sdk lint` and `build` to confirm the contract compiles @@ -8,30 +8,33 @@ - [ ] 2.1 Write failing tests in `packages/core/src/components/BlockManager.spec.ts` for an internal `appendTextContent(blockIndex, key, offset, content, userId)`: appends text at the offset, re-applies fragments shifted by the offset, is a no-op for empty content - [ ] 2.2 Implement it with `model.insertText` + `model.format`, and make the tests pass -- [ ] 2.3 Write a failing test that appending to an input ending with a formatted run does not extend that formatting over the appended text, then implement the normalization step (`model.getFragments` over the appended range → `model.unformat` per tool found) before re-applying the content's fragments +- [ ] 2.3 Write failing tests that appending to an input ending with a formatted run does not extend that formatting over the appended text, and that a run starting before the junction stays formatted up to it; then implement the normalization step (`model.getFragments(blockIndex, key, offset, offset + value.length)` → `model.unformat` per tool found, over exactly `[offset, offset + value.length)`) before re-applying the content's fragments ## 3. mergeBlocks — block form (TDD) - [ ] 3.1 Write failing tests for `BlocksManager.mergeBlocks({ block })`: two paragraphs merge into the previous one, which keeps its id, and the junction is returned; the block can be passed by index or id - [ ] 3.2 Implement the block form on top of `appendTextContent` + `removeBlock`, and make the tests pass -- [ ] 3.3 Write failing tests for what is absorbed: export key path → that input with fragments (including a nested key such as `items.0.text`); export function → its string without fragments; no `conversionConfig` → first text input with fragments; a second input not covered by the export is dropped with the block; an export key path matching none of the block's text inputs absorbs nothing and the block is still removed — then implement the export resolution and make them pass +- [ ] 3.3 Write failing tests for what is absorbed: export key path → that input with fragments (including a nested key such as `items.0.text`); export function → its string without fragments; no `conversionConfig` → first text input with fragments, without calling `exportTextContent`; a second input not covered by the export is dropped with the block; an export key path matching none of the block's text inputs absorbs nothing and the block is still removed — then implement the export resolution and make them pass - [ ] 3.4 Write failing tests for empty blocks: an empty previous block is removed and the merged block keeps its id, tool and text with the junction at its offset 0; an empty merged block is removed and the previous block is unchanged — then make them pass - [ ] 3.5 Write failing tests that `{ block }` throws, leaving the document unchanged, for an unknown block, the first block, and a block or previous block without text inputs (unmergeable); make them pass -- [ ] 3.6 Write a test that all model events of one `merge` call are emitted synchronously, before `merge` returns (the precondition for `undo-group-by-task` to record them as one step) +- [ ] 3.6 Write a test that every model event of one `merge` call has been dispatched when `merge` returns, and keep `mergeBlocks` free of `addBlock`/`createDataNode`/`convertBlock` (the only microtask-deferred dispatch in the model) +- [ ] 3.7 Write failing tests for `getTextKeys({ block })` in `BlocksManager`: text keys in document order (including nested keys), `[]` for a block without text inputs, throws for an unknown block; implement it and use it for `mergeBlocks`' own unmergeable check ## 4. mergeBlocks — range form (TDD) - [ ] 4.1 Write failing tests for `mergeBlocks({ index })` across two blocks: range content removed, end block's remaining content merged at the range start, end block removed, junction at the range start -- [ ] 4.2 Implement the range form in the order end block → blocks strictly between (descending, by index range) → start block → empty-start check → convert end block into start block, and make the tests pass -- [ ] 4.3 Write failing tests for: blocks without text inputs between the edges are removed; a range starting at offset 0 of the first block removes that block and keeps the trimmed end block with its tool; a range ending in a non-exported input of the end block absorbs only what the export carries — then make them pass +- [ ] 4.2 Implement the range form: resolve the start block, end block and every block strictly between (by index range) to ids up front, then end block → blocks between → start block → empty-start check → convert end block into start block, resolving each block's current index from its id right before mutating it; make the tests pass +- [ ] 4.3 Write failing tests for: a range across four or more blocks removes exactly the blocks between and the end block, and keeps every block after it (guards against stale indexes); blocks without text inputs between the edges are removed; a range starting at offset 0 of the first block removes that block and keeps the trimmed end block with its tool; a range ending in a non-exported input of the end block absorbs only what the export carries — then make them pass - [ ] 4.4 Write failing tests that `{ index }` throws for a non-text index and for a range within a single block; make them pass - [ ] 4.5 Write a test that `merge({ block: b })` produces the same document as `merge({ index })` over the empty boundary range before block `b` ## 5. BlocksAPI wiring and integration - [ ] 5.1 Write failing tests in `packages/core/src/api/BlocksAPI.spec.ts` that `merge()` delegates both forms to `BlocksManager.mergeBlocks` with the config's `userId` by default and an explicit one when passed, and returns its result -- [ ] 5.2 Implement `merge()` in `packages/core/src/api/BlocksAPI.ts` as a thin params-object wrapper mirroring `split`/`convert`, and make the tests pass -- [ ] 5.3 Add integration tests in `packages/core/src/api/BlocksAPI.integration.spec.ts` (real model, mocked DOM adapters) for: paragraph → paragraph merge; paragraph merged into a header-like tool keeps formatting; header-like block merged into a paragraph; cross-block range across three blocks, one of them without text inputs, with formatting preserved; the caret is not moved by `merge` +- [ ] 5.2 Implement `merge()` and `getTextKeys()` in `packages/core/src/api/BlocksAPI.ts` as thin params-object wrappers mirroring `split`/`convert`, and make the tests pass +- [ ] 5.3 Add integration tests in `packages/core/src/api/BlocksAPI.integration.spec.ts` (real model, mocked DOM adapters) for: paragraph → paragraph merge; paragraph merged into a header-like tool keeps formatting; header-like block merged into a paragraph; cross-block range across three blocks, one of them without text inputs, with formatting preserved +- [ ] 5.4 Write failing tests that `BlocksAPI.merge` keeps the caret of `userId`: a caret in an untouched block stays at the same block id, key and offset (index re-resolved when a block before it was removed); a caret in the first block at or before the junction stays; a caret in the second block, a removed block or removed content goes to the junction; no caret stays none — then implement the snapshot-and-restore around `mergeBlocks` and make them pass +- [ ] 5.5 Add an integration test with real DOM adapters: with the caret in a block after the merged pair, a programmatic `merge` leaves the caret there although the merge's `TextAddedEvent` reached the merged input's adapter ## 6. DOMBlockToolAdapter @@ -39,10 +42,10 @@ - [ ] 6.2 Write failing tests for classifying a target range from its `Index`: a range inside one formatted input (start and end in different text nodes) does not cross blocks; a range across two inputs of one block does not cross blocks; a range whose segments belong to two blocks does — then implement the check and switch the existing `insertParagraph` condition from `isCrossInputSelection` to it - [ ] 6.3 Write failing tests that a delete `beforeinput` with a cross-block target range leads to exactly one `api.blocks.merge({ index })` call, from the adapter owning the range start, no `api.blocks.delete`/`api.text.remove` calls, and the caret placed at the returned junction - [ ] 6.4 Write failing tests that an insert-type `beforeinput` over a cross-block range calls `merge({ index })` then `api.text.insert` at the junction, and that `insertParagraph` over it calls `merge({ index })` then `api.blocks.split` at the junction -- [ ] 6.5 Write failing tests that a collapsed selection at offset 0 of a block's first input with a backward delete type calls `merge({ block })` with its own block, and at the end of its last input with a forward type calls it with the next block — regardless of the reported target range; that `api.blocks.delete` is called for a neighbour without registered text inputs, with the caret left in place; and that nothing is called at the start of the first or the end of the last block +- [ ] 6.5 Write failing tests that a collapsed selection at offset 0 of a block's first input with a backward delete type calls `merge({ block })` with its own block, and at the end of its last input with a forward type calls it with the next block — regardless of the reported target range; that `api.blocks.delete({ block: })` is called for a neighbour whose `getTextKeys` is `[]`, after which the caret is re-set to the same block id, key and offset (not left one block too far after removing the previous block); that a next block with persisted text whose `render()` has not finished (no registered inputs) is merged, not deleted; and that nothing is called at the start of the first or the end of the last block - [ ] 6.6 Write failing tests that a backward/forward delete at an edge between two inputs of the same block only moves the caret to the neighbouring input, and that a delete over a range across two inputs of one block still removes text per input without calling `merge` - [ ] 6.7 Write failing tests that when `merge` removes the acting adapter's own block (Backspace at a block's start; a cross-block range starting at offset 0), the caret placement and the follow-up `text.insert`/`blocks.split` address `MergeResult.block` and succeed -- [ ] 6.8 Implement the mapping in `packages/dom-adapters/src/BlockToolAdapter/index.ts`, remove the per-adapter clipping of cross-block ranges (keeping per-input clipping within one block), the "middle block → `blocks.delete`" path and the `@todo support input merging`, and make the tests pass +- [ ] 6.8 Implement the mapping in `packages/dom-adapters/src/BlockToolAdapter/index.ts`, decide neighbours' text inputs with `api.blocks.getTextKeys` (not `InputsRegistry`), remove the per-adapter clipping of cross-block ranges (keeping per-input clipping within one block), the "middle block → `blocks.delete`" path and the `@todo support input merging`, and make the tests pass ## 7. End-to-end @@ -51,6 +54,6 @@ ## 8. Docs and verification -- [ ] 8.1 Add a "Merging blocks" section to `docs/input-handling.md` describing how cross-block and boundary deletions map to `BlocksAPI.merge` (and to `blocks.delete` for blocks without text inputs), the conversion of the second block, the empty-block rules and the reliance on `undo-group-by-task` for undo, and a diagram in `docs/diagrams/` if the existing ones no longer match +- [ ] 8.1 Add a "Merging blocks" section to `docs/input-handling.md` describing how cross-block and boundary deletions map to `BlocksAPI.merge` (and to `blocks.delete` for blocks without text inputs), the conversion of the second block, the empty-block rules, how the caret is kept, and the reliance on `undo-group-by-task` for undo, and a diagram in `docs/diagrams/` if the existing ones no longer match - [ ] 8.2 Run `yarn workspace @editorjs/core test`, `yarn workspace @editorjs/dom-adapters test`, `yarn workspace @editorjs/sdk test`, `yarn workspace @editorjs/editorjs test:e2e` and `yarn lint` across the affected workspaces; fix any fallout - [ ] 8.3 Run `openspec validate merge-blocks-on-delete --type change` and fix any reported issues