Skip to content

🐛 fix: keep per-line insertion linear and bound undo memory - #243

Open
lobehub-coder wants to merge 5 commits into
masterfrom
fix/per-line-insert-perf
Open

lobehub-coder wants to merge 5 commits into
masterfrom
fix/per-line-insert-perf

Conversation

@lobehub-coder

@lobehub-coder lobehub-coder commented Nov 17, 2026 •

Copy link
Copy Markdown

💻 变更类型 | Change Type

  • ✨ feat
  • 🐛 fix
  • ♻️ refactor
  • 💄 style
  • 🔨 chore
  • 📝 docs

🔀 变更说明 | Description of Change

Fixes the quadratic slowdown (and the memory growth behind the crash) when text reaches the editor one line at a time instead of through paste.

Reproduction / trigger. In Chrome, trusted per-line input — Input.insertText(line) followed by Enter, as automation tools, extensions and some input methods do — fires one beforeinput insertText and one keydown Enter per line. That makes 2 committed updates per line, never a paste event, so the markdown paste path's single batch insert is not used. Other paths checked:

  • document.execCommand('insertText', …): no beforeinput. Lexical reconciles the DOM mutation and drops all but the first line (a separate data-loss issue, not this one).
  • A multi-line Input.insertText: one update, inserted as line breaks.
  • Synthetic beforeinput events in a synchronous loop: Lexical batches them into one commit.

Every per-line update then paid for work proportional to the whole document:

Hot spot (Chrome profile, 2,000-paragraph doc) Share of CPU Fix
$normalizeNodeIds RootNode transform: walks the whole tree twice per update 35% Check only the nodes the update created or wrote (_cloneNotNeeded) against an id index of the last normalized committed state. Any duplicate, setEditorState, skipTransforms update, policy change, or write the transform did not see falls back to the existing full pass, so repair semantics are unchanged.
Heading slugs / TOC refreshed on every content update (Lexical flags the root as intentionally dirty on every transform pass, so root === true was always true) 2.2% One shared exact check: dirty nodes that are (or sit in) a heading, plus subtrees of nodes that were inserted, removed or moved.
litexml DiffNode / table-row-diff / table-cell-diff listeners: $nodesOfType per update (plus useHasDiffNode scanning the node map) 2.1% Check only dirty nodes (ancestors of a change are dirty too); full scan only on load/undo (setEditorState marks just the root, history restores carry HISTORIC_TAG).
Markdown shortcut listener: nested editor.update() on every collapsed-selection change, cloning the editor state even when no transformer can apply per keystroke Same precheck the transformer runners bail out on, in a read first.

Crash. The undo stack keeps a full EditorState (one node-map entry per node) per entry, and per-line input pushes 2 entries per line. Heap measured after GC: 52 MB → 500 MB at 2,000 lines, growing with lines × document size; at 1,500 lines, clearing the history drops the heap from 322 MB to 56 MB. registerHistoryMemoryLimit drops the oldest entries once the stack would retain more than 1M node-map entries at the current document size, and always keeps ≥ 100 undo steps. Small documents are unaffected (1,000 nodes → 1,000 steps).

Not changed. Paste and its markdown auto-conversion (PASTE_COMMAND → INSERT_MARKDOWN_COMMAND), litexml diff semantics, and node-ID repair rules (previous owner keeps the ID, copies and splits get fresh ones). No debounce/throttle anywhere: every update is still processed when it happens.

📝 补充信息 | Additional Information

Measurements. Chrome 1248 headless renders the real Editor with LobeHub's page-editor plugin set. Each line is a trusted insertText + Enter of 61 characters. "Plain Lexical" is a bare rich-text editor with no LobeHub plugins, the floor.

Lines inserted from an empty doc master this PR plain Lexical heap master heap this PR updates (both)
500 3.60 s 2.79 s 2.17 s 82.6 MB 73.2 MB 1001
1000 11.70 s 7.91 s 7.87 s 166.7 MB 85.7 MB 2001
1500 24.96 s 15.61 s 15.15 s 322.6 MB 92.5 MB 3001
2000 (126k chars) 44.37 s 26.16 s 25.57 s 499.8 MB 89.0 MB 4001
Per-line cost after K existing paragraphs master this PR plain Lexical
K = 0 4.75 ms 4.29 ms 3.87 ms
K = 1,000 15.33 ms 9.96 ms 9.10 ms
K = 2,000 25.09 ms 16.57 ms 13.61 ms
Editor-owned work (jsdom, tests/per-line-insert-performance.test.ts) master this PR
Listener + transform + command time, 300 → 1,200 lines 297 → 4,664 ms (15.7×, fails) 36 → 156 ms (4.3×)
Identity checks for one appended line (500-paragraph doc) 2,008 7

The update count is exactly 2 per line in every build, and the editor's own work now scales linearly. Total wall time in Chrome still grows faster than linear (2× lines ≈ 3.3× time), at the same rate as plain Lexical: what's left is Chrome's forced layout / selection sync in setBaseAndExtent and Lexical's state clone and root reconcile. The CPU profile at K=2,000 has no editor plugin frames left; on master, $normalizeNodeIds was 35.7%. In headless Chrome, master did not crash at 2,000 lines, so heap growth is the evidence for the crash fix.

Paste: a real Ctrl+V of mixed markdown fires PASTE_COMMAND once, then INSERT_MARKDOWN_COMMAND once, and renders the same structure on master and this PR (headings, bold, link, lists, quote, code block, table). One undo returns to the raw text on both. The existing paste/markdown suites pass 42/42 on both.

Acceptance (evidence, recordings, raw data): https://lobehub.com/acceptance/8155085c-44d4-4329-aa89-16b2a3ba099e

Tests: vitest run 140 files / 974 tests pass; type-check clean. Each new test was also run against master's src/: the perf, node-visit and nested-update tests fail there; the fallback, heading-shortcut and normalization tests pass on both, as guards for unchanged behavior.

A follow-up is needed in the LobeHub app. The page editor's own update listener (src/features/EditorCanvas/InternalEditor.tsx) exports getDocument('json') and deep-compares it on every content update. handleContentChange then exports markdown and JSON again. That is O(document) per line on the app side, which this PR cannot remove.

…each update

Each per-line insert (insertText + Enter, one commit each) ran a RootNode
transform that walked the whole document twice to normalize node IDs, and
the heading service / TOC refreshed slugs on every content update because
Lexical flags the root as intentionally dirty on every transform pass.

- Node IDs: once a committed state is known to be normalized, check only the
  nodes the update created or wrote against an id index; fall back to the
  existing full pass for setEditorState, skipTransforms updates, policy
  changes and any duplicate, so repair semantics are unchanged.
- Headings: share one exact change check that ignores the root flag and only
  walks subtrees of nodes that were inserted, removed or moved.
The DiffNode, table-row-diff and table-cell-diff update listeners (and useHasDiffNode) scanned every node of the document on each update via $nodesOfType / the node map. A change can only produce a node needing normalization through a node the update touched, and Lexical marks every ancestor of a change dirty too, so check the dirty nodes and scan everything only on load/undo (setEditorState marks just the root, history restores carry HISTORIC_TAG). Diff semantics are unchanged.
…igger a shortcut

The shortcut listener opened a nested editor.update() on every collapsed-selection change, cloning the whole editor state even when no transformer could apply. Check the same preconditions the transformer runners bail out on in a read first.
Each undo entry holds a full EditorState. Inserting a document line by line pushes about two entries per line, so retained memory grew with lines x document size (~450 MB at 2,000 lines) until the tab crashed. Drop the oldest entries once the stack would keep more than 1M node-map entries at the current document size, always keeping at least 100 steps.
Insert N lines the way a browser does when it bypasses paste (one committed text insert plus one Enter per line) and assert exactly 2N updates and that the editor's own callbacks scale linearly (4x lines -> < 7x time; master is ~16x). Also cover incremental node-ID checks, their fallbacks, and heading-change detection.
@lobe-tsukumo

lobe-tsukumo Bot commented Nov 17, 2026

Copy link
Copy Markdown

👍 @lobehub-coder

Thank you for raising your pull request and contributing to our Community.
Please make sure you have followed our contributing guidelines. We will review it as soon as possible.
If you encounter any problems, please feel free to connect with us.

非常感谢您提出拉取请求并为我们的社区做出贡献,请确保您已经遵循了我们的贡献指南,我们会尽快审查它。
如果您遇到任何问题,请随时与我们联系。

@vercel

vercel Bot commented Nov 17, 2026 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated
lobe-editor Ready Ready Preview Nov 17, 2026 4:39pm UTC

Request Review

@pkg-pr-new

pkg-pr-new Bot commented Nov 17, 2026

Copy link
Copy Markdown

Open in StackBlitz

npm i https://pkg.pr.new/@lobehub/editor@243

commit: 0853c52

@lobehub

lobehub Bot commented Nov 17, 2026

Copy link
Copy Markdown

LobeHub is tracking this pull request. Merging accepts the delivery; failing checks and review feedback reach the agent that opened it. Learn more ↗︎

Acceptance Status Conversation Notifications Updated (UTC)
8155085c ⚪ Planned — — Nov 17, 2026 1:19pm

This branch was successfully deployed

1 active deployment
Preview — 0853c52f Deployed Nov 17, 2026 by vercel[bot]
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.

1 participant