Skip to content

fix(markdown-preview): paint Find matches without mutating react DOM (crash 237acef1) - #8678

Merged
nwparker merged 2 commits into
mainfrom
nwparker/fix-markdown-preview-search-crash
Jul 14, 2026
Merged

nwparker merged 2 commits into
mainfrom
nwparker/fix-markdown-preview-search-crash

Conversation

@nwparker

@nwparker nwparker commented Jul 14, 2026 •

Copy link
Copy Markdown
Contributor

What

Fixes a renderer crash — NotFoundError: Failed to execute 'insertBefore' on 'Node': The node before which the new node is to be inserted is not a child of this node — in the markdown preview.

Crash report 237acef1-e50c-4c78-bfea-623aa211b7ea (macOS, prod build, terminal.workbench boundary):

NotFoundError: Failed to execute 'insertBefore' on 'Node': ...
    at insertOrAppendPlacementNode
    at commitReconciliationEffects
    at commitMutationEffectsOnFiber
    ...
component stack: p → Markdown → MarkdownPreview → EditorContent → ...

Root cause

Find-in-preview highlighting painted matches by mutating react-markdown's own DOM:

  • applyMarkdownPreviewSearchHighlights split each matching Text node and textNode.replaceWith(fragment)'d in <mark> elements.
  • clearMarkdownPreviewSearchHighlights unwrapped them and called root.normalize(), merging adjacent text nodes.

Both rewrite the child list of nodes React owns. React keeps fiber pointers to the original text nodes, so when streamed/external file content re-renders the paragraph (extremely common in Orca — AI writes, external edits), React's commit phase runs insertBefore/removeChild against a node that is no longer a child of its parent → the crash. Trigger conditions from the report: the preview Find bar open while content was being rewritten.

The fix

Paint matches with the CSS Custom Highlight API — CSS.highlights.set(name, new Highlight(...ranges)) over Ranges computed from the text nodes. This highlights the exact same character ranges without mutating a single DOM node, so React's tree is never disturbed. Match offsets come from the existing findTextMatchRanges (unchanged), which already returns original-text offsets that map straight onto each Text node.

The API is reached through a getHighlightApi() feature-detector, so it degrades to a no-op where the API is absent (older Chromium, jsdom/happy-dom in tests) — match count and navigation still work off the returned Ranges; only the visual paint is skipped. The <mark> CSS became ::highlight(...) rules.

Also added translate="no" to the preview body so browser/OS page-translation (which swaps text nodes behind React's back) can't trigger the same class of crash.

ELI5

To highlight your search matches, the app used to cut up the page's text and staple little yellow <mark> tags into it. But React had already memorized where every piece of text was. When new content streamed in, React reached for a piece of text that the highlighter had quietly moved — and fell over. The fix paints the yellow highlight on top of the text using a browser feature made exactly for this, without ever cutting the text up. React's memory stays correct, so nothing falls over.

Fix evidence (undeniable)

New happy-dom regression test markdown-preview-search-crash.test.tsx renders a real react-owned <p> and drives the real search functions:

  • Before the fix — applying highlights injects a <mark> (body.querySelector('mark') is non-null → the "no mutation" assertion fails), and re-rendering the paragraph while highlights are active throws the NotFoundError.
  • After the fix — no <mark> is injected, body.textContent is byte-for-byte intact, and a streamed re-render is clean.

129 test files / 839 tests in src/renderer/src/components/editor/ pass (incl. the existing markdown-preview-search.test.ts). Typecheck (web) exit 0. oxlint + oxfmt clean.

Trade-offs / behavior changes

  • Highlight visual: colors (yellow match, orange active) are preserved; the old 2px border-radius/padding is dropped because ::highlight() only styles color/background. Cosmetic.
  • Accessibility: the transient search highlight is no longer a <mark> element in the a11y tree. Match count is still surfaced in the UI; this only affects the highlight decoration, not navigation.
  • Multiple simultaneous Find bars: CSS.highlights is a document-global registry. Highlights are scoped per-preview via a module-level union registry (each preview's ranges are tracked by its own token and the union is painted), so split/floating previews with Find open don't clobber each other — parity with the old per-<mark> behavior.
  • Active highlight on a same-count stream: if streamed content changes while the match count and active index stay identical, the orange active-match highlight briefly drops until the next Find navigation. Cosmetic, narrow, and identical to the old code's behavior (fresh <mark>s lost data-active the same way).
  • No change to normal markdown rendering, and no DOM mutation of react-owned content at all.

Adversarial review

2 loops → clean.

  • Round 1 (crash-elimination + UX-regression lenses) found two real defects, both fixed:
    1. new Highlight(...ranges) spread the entire match array as constructor args → RangeError: Maximum call stack size exceeded at ~100k+ matches (large streamed doc + short common query — the same regime as the bug being fixed). Fixed: build the Highlight incrementally with .add(); no range-spread anywhere on a match-scaling path. Regression test with an arg-rejecting stub Highlight.
    2. CSS.highlights is document-global → two previews with Find open clobbered each other. Fixed: per-instance union registry keyed by a stable per-preview token. Regression test proves A+B paint the union and closing one keeps the other.
  • Round 2 (verification of both fixes + the new union code) — clean: no range-spread survives, the union is correct, clearing one instance leaves others painted, no memory leak (effect cleanup always deletes the instance on unmount/close), API-absent path still returns Ranges so count/navigation work. Two low/cosmetic observations only (active highlight may drop on a same-count stream; setActive re-paints the match set on navigation — both pre-existing-equivalent, neither a crash or regression).

Made with Orca 🐋

Search highlighting injected <mark> by splitting react-markdown's own text
nodes (and normalize()-merging them on clear). react kept stale child pointers,
so the next streamed-content commit threw NotFoundError (crash 237acef1:
insertBefore ... not a child of this node) when Find was open during a rewrite.

Paint match Ranges with the CSS Custom Highlight API instead — zero DOM
mutation of the subtree react owns. Also mark the preview body translate="no"
so browser/OS page-translation can't trigger the same class of crash.

Adds a happy-dom regression test that reproduces the crash: before, applying
highlights injects a <mark> and a re-render throws; after, the DOM react owns is
untouched and streamed re-renders are clean.

Co-authored-by: Orca <[email protected]>
@coderabbitai

coderabbitai Bot commented Jul 14, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

Markdown preview search highlighting was migrated from injected <mark> elements to instance-scoped CSS Custom Highlights backed by Range objects. Preview search effects now apply and clean up highlights using stable instance tokens, while multiple previews share aggregated registry entries. CSS selectors style regular and active matches. The markdown container disables translation, and regression tests cover React text preservation, highlight API behavior, and multi-instance cleanup.

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description is detailed, but it omits required template sections like Screenshots, AI Review Report, Security Audit, and Notes. Add the missing template sections and include explicit testing, cross-platform review, security audit, screenshots or a clear no-visual-change note, and notes.
Docstring Coverage ⚠️ Warning Docstring coverage is 11.11% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately summarizes the main change: rendering Find matches without mutating React-owned markdown DOM.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot 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.

Actionable comments posted: 4


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 5e34720d-e32d-45be-9cf8-df5767e3496a

📥 Commits

Reviewing files that changed from the base of the PR and between 8ac6d79 and 5a7f2ce.

📒 Files selected for processing (4)
  • src/renderer/src/assets/markdown-preview.css
  • src/renderer/src/components/editor/MarkdownPreview.tsx
  • src/renderer/src/components/editor/markdown-preview-search-crash.test.tsx
  • src/renderer/src/components/editor/markdown-preview-search.ts

- Use --markdown-search-match(-active) theme tokens instead of raw hex.
- Split match vs active highlight painting so Next/Prev navigation repaints
  only the active range, not the full (100k-range) match set.
- Reapply the active highlight after a re-apply via a searchRevision effect dep,
  so a same-count streamed rerender doesn't drop the active highlight.
- Strengthen the streamed-rerender test (keep highlights active across the
  commit) and add navigation-only-repaints + same-count active regression tests.

Co-authored-by: Orca <[email protected]>
@nwparker

Copy link
Copy Markdown
Contributor Author

Old vs new Find-highlight styling

Markdown Find highlight — before (mark DOM injection) vs after (CSS Custom Highlight API), light + dark

Before = the old <mark> injection · After = the new CSS Custom Highlight API (this PR). Match/active colors are identical (yellow #facc15 / orange #fb923c, now via the --markdown-search-match(-active) tokens) in both light and dark. The only visual delta is the highlight corners: the old <mark> had a 2px border-radius; ::highlight() only styles color/background, so highlights are now square. Same-position, same-color, no DOM mutation.


CodeRabbit review — all 4 comments addressed (commit 37dbcbc)

  1. Theme tokens — replaced the raw hex in markdown-preview.css with new --markdown-search-match / --markdown-search-match-active tokens in main.css (light + dark).
  2. Perf: navigation — split match vs active painting; setActiveMarkdownPreviewSearchMatch now repaints only ACTIVE_SEARCH_HIGHLIGHT_NAME, so Next/Prev no longer rebuilds the (up to 100k-range) full match highlight.
  3. Correctness: active highlight on same-count rerender — a searchRevision counter bumps on every re-apply and is a dep of the active-paint effect, so a streamed rerender with the same match count/index re-paints the active highlight instead of dropping it. Added a same-count regression test.
  4. Test strength — the streamed-rerender test now keeps highlights registered across the commit (removed the premature clear); added navigation-only-repaints coverage.

@coderabbitai coderabbitai Bot 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.

🧹 Nitpick comments (1)
src/renderer/src/assets/main.css (1)

297-298: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Consider adjusting the dark mode colors for optimal contrast.

The dark mode colors for --markdown-search-match and --markdown-search-match-active are identical to their light mode counterparts (#facc15 and #fb923c). Consider if these shades provide the intended visual comfort against the dark background (#1e1e1e), similar to how --annotation-highlight was slightly adjusted between modes.


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: ff252691-113d-4eb6-b44e-6c9b94afe1fe

📥 Commits

Reviewing files that changed from the base of the PR and between 5a7f2ce and 37dbcbc.

📒 Files selected for processing (5)
  • src/renderer/src/assets/main.css
  • src/renderer/src/assets/markdown-preview.css
  • src/renderer/src/components/editor/MarkdownPreview.tsx
  • src/renderer/src/components/editor/markdown-preview-search-crash.test.tsx
  • src/renderer/src/components/editor/markdown-preview-search.ts
🚧 Files skipped from review as they are similar to previous changes (3)
  • src/renderer/src/components/editor/markdown-preview-search.ts
  • src/renderer/src/assets/markdown-preview.css
  • src/renderer/src/components/editor/MarkdownPreview.tsx

@nwparker
nwparker merged commit a2b5431 into main Jul 14, 2026
1 check passed
@nwparker
nwparker deleted the nwparker/fix-markdown-preview-search-crash branch July 14, 2026 06:34
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
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