Skip to content

docs(openspec): propose block merging via BlocksAPI.merge - #208

Open
gohabereg wants to merge 2 commits into
mainfrom
feat/blocks-merge
Open

gohabereg wants to merge 2 commits into
mainfrom
feat/blocks-merge

Conversation

@gohabereg

Copy link
Copy Markdown
Member

What

Planning only. This PR adds the merge-blocks-on-delete OpenSpec change for #135. It contains no code changes.

One new API method, BlocksAPI.merge, with two overloads:

  • merge({ block }) merges a block into the block before it. Only neighbouring blocks can be merged, so one block is enough.
  • merge({ index }) takes a range that crosses blocks. It removes the content inside the range and the blocks in between, then joins the end block into the start block.
  • Both return where the blocks joined ({ block, key, offset }). merge never moves the caret, like split and convert.

How merging works:

  • The second block is always converted into the first. The first block keeps its id and tool. What the second block contributes is chosen by its conversionConfig.export: a key path keeps formatting, a function gives plain text, and with no config the first text input is used. There's no direction and no separate convert step.
  • Empty blocks give way. If the first block is empty, it's removed instead and the second block survives.
  • Blocks without text inputs are unmergeable. merge throws for them. On the keyboard, Backspace or Delete next to such a block removes it.

The DOM adapter only maps events to calls:

  • Deleting, typing, pasting or pressing Enter over a cross-block selection makes one merge({ index }) call, then the insert or split where the blocks joined.
  • Backspace and Delete at block edges call merge({ block }).
  • The current per-adapter cross-block slicing is removed.

There's no canMerge, no new tool option, and no change to SelectionAPI, TextAPI or the model.

Why

v3 is one contenteditable with cross-block selection, so merging is also needed whenever a deletion crosses a block boundary, not only on Backspace/Delete as in v2. Today none of these cases join anything:

  • Backspace and Delete at a boundary do nothing.
  • A cross-block selection delete leaves the two edge blocks apart. There's a @todo support input merging in BlockToolAdapter at that spot.

Notes for reviewers

🤖 Generated with Claude Code

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 <noreply@anthropic.com>
@gohabereg
gohabereg requested a balanced review from Copilot October 17, 2026 03:20

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

An organization owner can choose the repository organization as the billing source for reviews requested by members with a paid Copilot license. Learn about Copilot code review billing.

- **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.

@neSpecc neSpecc Oct 30, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Dropping fields outside export on merge is fine for the MVP.

TODO: multi-field export. merge({ index }) should keep the unselected tail and the neighbouring text fields, not only the export key.

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

@neSpecc neSpecc Oct 30, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

TODO: word/line delete at a block boundary.

Right now any backward delete at offset 0 does a full merge({ block }). For

Hello world
|Foo

Option+Backspace (deleteWordBackward) should also remove world and leave Hello|Foo. Same for line-delete in either direction. For the MVP we keep the full merge, as written here.


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.

@neSpecc neSpecc Oct 30, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

On main the signature is getFragments(blockIndexOrId, dataKey, start?, end?, tool?). Passing undefined as the third argument shifts the rest: end becomes offset, and tool receives a number.

It should be getFragments(blockIndex, key, offset, offset + value.length). Call unformat on [offset, offset + length), not on the fragment bounds. A fragment can start before the junction, which would strip formatting from text that was already there.


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.

@neSpecc neSpecc Oct 30, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

After the blocks strictly between A and B are removed, B's index has already changed. Capture both edges' ids before any mutation, then delete and append by id rather than by the indexes taken at the start.


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.

@neSpecc neSpecc Oct 30, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

EditorDocument.removeBlock does not rewrite the caret, and the caret is stored as a blockIndex. After deleting the previous block, that index shifts.

"Caret stays where it is" means the same block id and offset. Set that explicitly. The old index no longer points at the right place.

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.

@neSpecc neSpecc Oct 30, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Some model events are already dispatched as microtasks (DataNodeAddedEvent while a block is constructed; see the comment in addBlock). Task 3.6 requires every event of one merge to be emitted synchronously, before merge returns.

Otherwise undo-group-by-task will not group them, and the adapter's follow-up insert will run before merge's own microtasks. Worth checking up front whether insertText / format go through that same queue.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Merge uses only synchronous events, so it's safe here. I've changed the wording a bit though

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

@neSpecc neSpecc Oct 30, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Once this requirement is archived, the list still omits methods that already exist: getIndexById, getIdByIndex, getData, createData, removeData, updateValue.

On main, blocks.delete is delete({ block }), not a bare delete() (same in the dom-adapters scenarios).

exportTextContent throws when there is no conversionConfig. The "no config → first text input" branch must not go through it. Decision 3 already says so; an implementation can easily do the opposite.

- 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 <noreply@anthropic.com>
@gohabereg
gohabereg requested a review from Reversean November 5, 2026 00:31
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants