Skip to content

fix(muya): keep list spacing consistent through edit transactions - #5872

Merged
Jocs merged 6 commits into
developfrom
codex/fix-5297-list-looseness
Oct 24, 2026
Merged

Jocs merged 6 commits into
developfrom
codex/fix-5297-list-looseness

Conversation

@Jocs

@Jocs Jocs commented Oct 23, 2026 •

Copy link
Copy Markdown
Member

Closes #5297

Summary

Adding a paragraph to a list item could leave the editor tight while saving Markdown that reopened loose. Complete each edit through a shared transaction coordinator so the operation, document state, live Block tree, and history agree before notifying consumers.

  • EditTransactions owns synchronous command scopes, nested batching, deferred Block edits, and pre-commit editing rules. Block mutations and API operations can join one scope; transient move/replace structures are never normalized. Failed command scopes restore the committed document without publishing partial changes.
  • Derived inline rendering reads a cached immutable transaction candidate before provisional Block projection; reference-definition caches follow document identity through scoped edits and rollback. Pure API scopes retain API source; mixed User/API scopes have User source regardless of nesting or operation order.
  • Whole-document replacement and rebuilds, including forced render-only options and locale changes, enforce standalone boundaries before changing configuration. Rebuilds flush pending edits before replacing Blocks. Internal rollback can restore a locked document through the existing document-update authority while preserving read-only mode.
  • Checkbox-only operations skip list export/import, and checkbox state/DOM updates share one projection method for edits and undo/redo.
  • JSONState.apply applies the supplied operation literally. It no longer queues edits, schedules frames, runs list rules, emits changes, or calls back into the Editor.
  • Reuse one Block operation walker and recovery path for API edits, transaction completion, and history replay. Whole-document replacements enter the same commit pipeline and record the completed operation.
  • Explicit commands isolate their undo step from adjacent typing; nested commands share the outer selection and boundary. Undo/redo replay recorded operations without running editing rules. Replay and history recording are independent policies.
  • Scope history suppression to an individual change event, so a listener can start a new edit during replay without losing that edit's history.
  • Reuse the parser/serializer boundary rules for list looseness. Same-marker plain/task runs remain one logical list; different markers and nested levels stay independent. Task conversion inherits existing spacing, and menu toggles cover the whole logical list.

The list consistency rule also covers the conversion, menu, and paste symptoms in #831, #823, and #706, and relates to mixed plain/task lists in #5257. It builds on #5854. The transaction contract is documented in packages/muya/src/editor/transactions/README.md.

Type of change

  • Bug fix (non-breaking, fixes an issue)

Test plan

  • 26 list regressions covering all list kinds, mixed runs, nesting, paste, conversion, menus, HTML boundaries, empty final paragraphs, batching, and undo/redo.
  • 25 transaction regressions covering mixed Block/API edits, nested scopes, cancellation, rollback (including locked documents), rebuild boundaries, subsequent editing after option/locale changes, flush deferral, committed notifications, replacement history, literal state application, and replay policies.
  • Existing history, source replacement, snapshot ownership, and stale-caret regressions retained; legacy history without a saved selection is exercised explicitly.
  • Muya unit suite: 2,982 passed.
  • CommonMark/GFM fixture suite: 1,347 passed against the existing expected-failure baseline.
  • Post-revert Chromium validation: 13 targeted list/transaction cases passed (2 workers). The restored source tree is identical to f575b45, which previously passed 561 full-suite cases with 3 existing skips.
  • Muya and desktop builds; Muya/root ESLint; Muya/desktop typechecks and declaration emit; circular-dependency check.
  • Browser validation on macOS using local Chromium automation.

Notes for reviewers

The candidate/reference-cache performance optimization from ffb2f01 has been reverted. The source tree is restored to the correctness-fixed f575b45 version; the batch-edit performance finding remains unresolved.

Most changes to existing tests migrate deferred flushing from the internal state store to the transaction coordinator. The public muya.flush() remains available to hosts. No compatibility shim leaves editing responsibilities in JSONState.

Regression tests cover reference-link rendering against candidate state, API source and user-only history, checkbox-only normalization and projection, standalone configuration/rebuild boundaries, and rollback after enabling read-only mode. The boundary/recovery checks were reproduced as failures before their fixes. Non-blocking menu/list-run refactors remain outside this PR.

Automatic list completion only promotes tight lists when required; explicit menu actions can tighten every run together when the structure permits it. Exact preservation of original blank lines, including the distinct-marker gaps in #983 and broader source-fidelity concerns in #2189, remains separate work. Existing conformance expected failures are unchanged; this does not claim full CommonMark/GFM compliance.


By submitting this pull request, I confirm that my contribution is made under the terms of the MIT license.

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.

🟢 Approval recommended

No unresolved review issues remain, and the supplied assessments unanimously support approval.

No open issues 🎉

What changed in this PR

This pull request keeps logical list looseness consistent across editing, serialization, live rendering, conversions, paste, and undo/redo operations.

Changes:

  • Adds transaction-boundary list-looseness normalization.
  • Synchronizes list metadata, history operations, and mu-tight-list DOM classes.
  • Preserves spacing across mixed lists, conversions, nesting, menu actions, and batch edits.
  • Adds comprehensive unit and Chromium E2E regression coverage.
File Description
packages/​muya/​src/​state/​types.ts Adds list-marker identification for grouping compatible logical lists.
packages/​muya/​src/​state/​listLooseness.ts Detects affected lists and generates derived looseness metadata operations.
packages/​muya/​src/​state/​index.ts Applies normalization at transaction boundaries and includes it in emitted operations and history.
packages/​muya/​src/​muya.ts Toggles all adjacent compatible list runs through the menu.
packages/​muya/​src/​editor/​index.ts Applies list metadata and DOM-class updates during incremental operations.
packages/​muya/​src/​block/​gfm/​taskList/​index.ts Uses the shared list implementation for task-list looseness updates.
packages/​muya/​src/​block/​commonMark/​orderList/​index.ts Uses the shared list implementation for ordered-list looseness updates.
packages/​muya/​src/​block/​commonMark/​bulletList/​index.ts Uses the shared list implementation for bullet-list looseness updates.
packages/​muya/​src/​block/​base/​list.ts Centralizes list looseness state and CSS-class synchronization.
packages/​muya/​src/​block/​base/​format.ts Inherits existing list spacing when converting items to task lists.
packages/​muya/​src/​block/​base/​__tests__/​convertToOrderedTaskList.spec.ts Updates ordered-task conversion expectations for preserved tightness.
packages/​muya/​src/​__tests__/​listLooseness.spec.ts Adds broad regression coverage for edits, conversions, paste, nesting, menu actions, and history.
packages/​muya/​e2e/​tests/​editing/​list-looseness-5297.spec.ts Verifies live DOM spacing, keyboard edits, undo/redo, and reopen behavior.

Review effort: Lite

@Jocs Jocs changed the title fix(muya): keep logical list looseness consistent across edits fix(muya): keep list spacing consistent through edit transactions Oct 23, 2026

@Jocs Jocs left a comment •

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.

Review of commit daf0ee3f8df5282cf133d5fd21468367eda53030.

I recommend holding the merge until the four reproduced P2 issues in the inline comments are addressed: reference links render against stale state inside transactions; setContent() bypasses the transaction boundary and breaks rollback; scoped API operations lose their source; and checkbox updates serialize and parse an entire list.

The architectural direction is sound: moving batching, editing rules, and notifications out of JSONState; sharing the Block walker and recovery path; and attaching history suppression to individual events to support reentrant edits. The remaining gap is the read contract between candidate and committed state. Writes participate in the transaction, while derived modules such as InlineRenderer still read the committed document. Matching JSON and serialized Block state does not by itself establish that the rendered DOM is correct.

Non-blocking suggestions for reuse and maintainability:

  • Extract the calculation of adjacent logical list runs with the same marker for use by both the editing rule and _toggleLooseList(); they currently maintain separate scans.
  • Menu actions that toggle loose/tight spacing still rebuild the entire group of Blocks. Consider an operation-recording list-spacing interface that accepts a source and reuses ListBlock.setLoose(), reducing rebuilds and selection restoration.
  • Make commit metadata such as source part of the transaction context, with explicit policy-combination rules for nested scopes and mixed Block/API operations, so introducing a scope does not silently change call semantics.

Validation:

  • Muya unit tests run against this commit in a separate worktree: 2,968 passed.
  • CommonMark/GFM fixtures: 1,347 passed.
  • Seven additional boundary checks: six failed and one unscoped control passed, covering the four issues in the inline comments.
  • Performance numbers are medians of five rule-function runs in happy-dom/Vitest. They exclude Block construction, DOM updates, and end-to-end interaction time.
  • For browser E2E coverage, I checked the passing GitHub CI results; I did not rerun the full browser suite during this review.

Comment thread packages/muya/src/editor/index.ts Resolved

@Jocs Jocs left a comment

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.

Follow-up review of 5583508157a63feac421e0028baa43c54a9a5f7d, including the changes since daf0ee3f and the surrounding transaction lifecycle.

The four P2 findings from my previous review are fixed in their reproduced scenarios: scoped reference-link rendering, the standalone setContent boundary, API source/user-only history, and checkbox-only list normalization. The shared checkbox projection also keeps Block metadata and checkbox DOM consistent through undo/redo.

I still recommend holding the merge for the two remaining P2 transaction-boundary issues in the inline comments:

  • Render-only whole-document rebuilds can discard provisional Block changes while the pending operation still commits to JSONState.
  • Rollback cannot rebuild the view after a command enables read-only mode, leaving committed JSONState and the displayed document inconsistent.

Both were reproduced in happy-dom unit checks and in Chromium against this exact commit. These are remaining gaps in the transaction lifecycle; they are not a claim that the four earlier fixes failed.

Validation:

  • Existing Muya unit suite: 2,977 passed.
  • CommonMark/GFM fixture suite: 1,347 passed.
  • Seven checks for the previous findings now pass, with the rollback check updated to expect the new standalone-boundary rejection.
  • Targeted Chromium run: all eight existing list/transaction regression cases passed; the two additional browser checks for the findings below failed with the documented JSON/DOM differences.
  • Five additional unit checks: three failed and two passed. Two failures cover scoped/unscoped render-only rebuilds, and one covers rollback after enabling read-only mode.
  • The earlier 10,000-item checkbox rule benchmark no longer enters export/import and measured below 0.02 ms locally; this measures only the rule function.
  • All current GitHub CI checks pass. I reran the targeted browser cases locally, not the full browser suite.

The non-blocking suggestions about sharing logical-list range calculation and avoiding menu-driven Block rebuilds remain applicable. The more immediate architectural need is a consistent policy for every whole-document rebuild and a recovery path whose execution authority does not depend on the current user-editability flag.

Comment thread packages/muya/src/muya.ts Resolved
Comment thread packages/muya/src/editor/index.ts Resolved

@Jocs Jocs left a comment

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.

Overall and performance follow-up on f575b4588b663946acf06f496b8da71b1bbc7cac, compared with the PR base b7988bd1 and the previous reviewed revision 55835081.

The six previously reported correctness issues pass their targeted regressions. Local validation of this revision: 2,982 unit tests, 1,347 CommonMark/GFM fixture tests, and 13 targeted Chromium tests passed. Current GitHub CI also passes.

There is one remaining P2 performance finding in the inline comment: candidate-state invalidation makes batch editing repeatedly replay pending operations and rescan the entire document's reference definitions. I recommend addressing this before merging.

Measurement conditions: Apple M4 Pro, Chrome 155.0.8059.86, 1280×900, no CPU throttling, separate worktrees sharing the same installed dependencies, Vite development builds. Each version was warmed up and then alternated for seven rounds; values below are medians. Times include the synchronous command, explicit flush, and a forced layout read. Initialization, module loading, asynchronous paint, IPC, and file persistence are excluded. These are browser editor-engine measurements, not packaged Electron end-to-end latency.

Operation Document size Base ms Head ms Head/base
One text Block edit 5,000 paragraphs 1.1 1.1 1.00x
Select all and bold 500 paragraphs 240.1 321.6 1.34x
Select all and bold 1,000 paragraphs 730.0 1,050.9 1.44x
Update and render each Block 1,000 paragraphs 257.8 564.6 2.19x
Replace all matching text 2,000 paragraphs 1,007.9 1,049.7 1.04x
One API text edit 5,000 paragraphs 1.5 1.5 1.00x
Ordinary list Enter 5,000 items 5.3 5.5 1.04x
Toggle a checkbox in a nested task list 5,000 items 0.8 1.0 1.25x
Whole-document replacement 2,000 paragraphs 705.2 712.0 1.01x

Submillisecond differences should not be interpreted from their ratios alone. Adding a second paragraph to a 5,000-item list measured 3.1 -> 26.3 ms, but that comparison includes a behavior change: the base incorrectly keeps the list tight, while the head promotes it to loose and relayouts the list. It is a correctness cost rather than an identical-output benchmark.

The final correctness fix itself does not explain the batch regression: in a separate alternating comparison, 1,000-paragraph bold measured 1,096.1 ms on 55835081 and 1,103.5 ms on f575b458; batch text updates measured 571.0 and 567.6 ms respectively.

A separate, non-blocking notification observation: a 20-character zero-delay keyboard burst in a 5,000-paragraph document with a representative snapshot-reading listener produced approximately 9 -> 20 json-change notifications. Summed input-handler plus deferred-commit work measured 43.7 -> 60.6 ms. At a 30 ms inter-character delay, both versions emitted 20 notifications and measured 65.5 -> 70.0 ms. The listener reads getMarkdown/getHistory/getTOC/getState; it does not include the desktop's word count, Pinia, synthetic history, IPC, or saving. This metric excludes keydown/keyup work and is not wall-clock typing latency. Consider coalescing expensive host-side derived updates per frame while preserving transaction/history semantics.

The complete local matrix covers 21 cases, with raw samples, diagnostic counters, a five-round attribution experiment, and reproducible harness scripts retained outside the checkout.

Comment on lines 82 to 85
collectReferenceDefinitions(): Labels {
const { jsonState } = this.muya.editor;
if (this._labelsRevision === jsonState.revision)
const state = this.muya.editor.transactions.candidateState;
if (this._labelsState === state)
return this.labels;

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.

[P2] Avoid rebuilding the candidate and rescanning every definition after each Block mutation

enqueue() invalidates _candidate on every edit. Each subsequent Block render reaches this getter, which previews the entire growing pending operation against committed state. Its new root identity then invalidates _labelsState, causing a full-document reference-definition scan. This happens even in a document with no reference definitions, so a multi-Block command pays work proportional to edited Blocks times document size, plus repeated cloning/replay of the pending operation.

Reproduced with ordinary paragraphs, selecting from the first paragraph's offset 0 through the last paragraph's text length, then timing muya.format('strong'); muya.flush(); void muya.domNode.offsetHeight. Uninstrumented seven-round medians on the same machine:

Paragraphs Base ms Head ms
100 26.4 30.0
500 240.1 321.6
1,000 730.0 1,050.9

A separate diagnostic run of the 1,000-paragraph command counted 1,999 getLabelInfo calls on the base versus 1,001,999 on the head, and 1,002 JSONState.preview calls on the head. These counts include per-render label checks; the extra million visits come from whole-document scans. Diagnostic timings were excluded from the table.

For attribution only, disabling reference collection in this reference-free fixture returned head formatting from 1,058.1 ms to 739.4 ms over five rounds, close to the base's 730.8 ms. This is not a proposed fix for documents containing references.

Please decouple definition-index invalidation from arbitrary candidate-root identity changes, and avoid replaying the entire accumulated operation for every render. Simply wrapping formatting in transact does not prevent enqueue from invalidating this cache on each mutation. Preserve the scoped-reference, definition-edit, and rollback regressions while adding a bounded-work check for batch formatting.

@Jocs
Jocs merged commit 3fcb5ce into develop Oct 24, 2026
8 checks passed
Jocs added a commit that referenced this pull request Oct 24, 2026
Refs #2189. Based on the merged edit-transaction refactor #5872.

## Result

Opening and saving headings currently normalizes source spacing and delimiters. Preserve ATX and Setext heading forms by default: editing `##   title  ###  ` emits `##   changed  ###  `.

This PR is limited to headings. Earlier code-block and other syntax-preservation changes are withdrawn.

## Design

- ATX `text` owns the complete editable source line, including indentation, separators, closing hashes and trailing whitespace. `meta.level` retains its semantic role; no ATX syntax/body copy.
- Setext `text` owns the original body lines and prefixes. Move the complete underline line from `meta.underline` into `syntax.underline`; no prefixes array or legacy-state migration layer.
- Shared heading helpers handle level changes, paragraph conversion, cursor offsets and structural edits. All structural paste paths preserve closing syntax on the heading and append only the body tail to the final pasted block.
- API commands and the actual front-menu Turn Into path share selection mapping. Menu mousedown retains the native selection so the conversion transaction records the original history endpoints. Caret/range positions survive level changes, paragraph conversion, undo/redo and subsequent typing.
- The inline lexer recognizes closing hashes only when its top-level tokens start with an ATX header. Outline output consumes these tokens directly, without rewriting Setext tokens after parsing.
- Carry Setext syntax through Blocks, cloning, replacement, JSON1 operations and history. Independent body and underline operations retain OT convergence.

All changes are inside `packages/muya`. No source buffer, persistent source-offset map, syntax-repair transaction rule or opt-in preservation flag. Block gaps, file-boundary blank lines and EOL bytes remain outside this PR's fidelity guarantee; container marker spelling is unchanged.

## Validation

Latest follow-up: `9c98b814`.

- Muya unit: 3,041 passed.
- CommonMark/GFM fixtures: 1,347 passed against the existing expected-failure baseline, with no new failures. Existing engine conformance limits remain.
- Final frozen-revision Chromium: 591 passed, 3 existing skips.
- The front-menu group passes 14 real-click cases, including 8 new regressions for caret/range conversion, undo/redo, typing, paragraph-to-heading conversion and an unrelated menu target.
- Muya and root lint/typecheck, circular dependency check and `git diff --check`: passed, existing warnings only. GitHub checks are running for the latest revision.

A local full run reused a Vite server that was exiting and failed with connection-refused errors. A fresh, independently owned test server passed the full suite without changing repository test configuration, timeouts or assertions.

`9c98b814` fixes the four subsequent review regressions: keep a separate list-marker line when the first heading has indentation; share body-bounded formatting across single/multiple blocks; shift non-ATX source selections by the actual inserted prefix; stop block-prefix parsing before interpreting heading body text as a reference definition. Twelve unit and ten browser regressions cover the reported examples and their adjacent cases. Final local validation: unit 3,041, spec 1,347, Chromium 591 passed / 3 existing skips; lint/types/circular checks passed. Fresh CI checks are running for this revision.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug] Adding a paragraph to a list item keeps the list tight in the editor, but it reopens loose

2 participants