Skip to content

Mermaid diagram disappears after blurring from edit mode - #953

Merged
malibio merged 2 commits into
mainfrom
fix/issue-938-mermaid-rerender-on-blur
Mar 17, 2026
Merged

malibio merged 2 commits into
mainfrom
fix/issue-938-mermaid-rerender-on-blur

Conversation

@malibio

@malibio malibio commented Mar 14, 2026

Copy link
Copy Markdown
Collaborator

Closes #938

Root cause: mermaid.render() uses the element ID to create a temporary DOM
element during rendering. When blur triggers rapid re-renders (the $effect
fires multiple times as isEditing changes propagate across all mermaid nodes),
two concurrent render calls for the same node share the same element ID
(mermaid-{nodeId}). The first render's result gets discarded as stale by the
sequence guard, and the second render fails because the ID already exists in
the DOM — causing mermaid to throw and return null, clearing the diagram.

Fix: use a unique render ID per call (mermaid-{nodeId}-{timestamp}) so
concurrent renders never collide. The temp element is cleaned up after each
successful render.

Co-Authored-By: Claude <[email protected]>
@malibio

malibio commented Mar 16, 2026

Copy link
Copy Markdown
Collaborator Author

Code Review Summary

This PR addresses a real, reproducible bug: mermaid diagrams disappearing after blur from edit mode. The change is a single-file, 7-line diff to packages/desktop-app/src/lib/services/mermaid-render.ts.

Background context: The underlying stale-result guard fix was already landed on main in commit ddd3843c (#942), which addressed the svelte $effect logic in code-block-node.svelte. This PR adds a complementary, lower-level fix inside the renderMermaid service function itself, targeting the actual DOM ID collision that caused the second render to throw.

Verdict: This is a net improvement. The root cause identified in the commit message is accurate and the fix is correct. Approved with one improvement and one nit noted below.


Findings

Suggested Improvements

packages/desktop-app/src/lib/services/mermaid-render.ts, line 126 — DOM cleanup only runs on the happy path

The document.getElementById(renderId)?.remove() call executes after mermaid.render() resolves successfully, but if mermaid.render() throws (e.g. invalid syntax), execution jumps to the catch block and the temp element is never cleaned up. Over multiple failed render attempts this will accumulate orphaned DOM nodes with IDs like mermaid-{id}-{timestamp}.

The cleanup should be placed in a finally-equivalent pattern or in a try/finally:

const renderId = `mermaid-${id}-${Date.now()}`;
try {
  const { svg } = await mermaid.render(renderId, definition);
  return sanitizeSvg(svg);
} finally {
  document.getElementById(renderId)?.remove();
}

This is a correctness issue in the error path. With the current structure you'd need to restructure the existing try/catch slightly, but the intent is clear. Recommend fixing before merge.

Nitpicks

packages/desktop-app/src/lib/services/mermaid-render.ts, line 124 — Date.now() uniqueness is probabilistic, not guaranteed

Date.now() returns millisecond precision. Two concurrent renders dispatched in the same millisecond (plausible in a microtask burst) will produce the same renderId and still collide. A monotonic counter (e.g. a module-level let renderCounter = 0 incremented per call) is strictly unique within the module's lifetime and avoids the residual race. Low probability in practice, but trivially solved.


Acceptance Criteria Check

  • Mermaid diagram re-renders correctly after blur — addressed by the ID collision fix
  • Diagram remains visible during async re-render — preserved by the stale-guard logic in code-block-node.svelte (landed in Mermaid diagram disappears after blurring from edit mode #942)
  • Error state displays correctly on invalid syntax — unchanged behavior, still covered by the null-check path
  • Stale-result protection not regressed — sequence guard in the component is unmodified
  • The PR description does not mention test results — recommend confirming bun run test:all was run cleanly before merge

The improvement around the finally cleanup is worth addressing. The Date.now() nit is low-risk in practice but is a one-line fix.

Use try/finally for temp element cleanup so it always runs even when
mermaid.render() throws. Also replace Date.now() with a module-level
monotonic counter to guarantee unique render IDs with no ms-precision
collision risk.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
@malibio

malibio commented Mar 17, 2026

Copy link
Copy Markdown
Collaborator Author

Addressed both review comments in commit 27111ef:

🟡 DOM temp element leak on render failure — Wrapped mermaid.render() in a try/finally block so document.getElementById(renderId)?.remove() always executes, even when the render throws. The outer try/catch still handles errors and returns null as before.

🟢 Monotonic counter instead of Date.now() — Added a module-level renderCounter variable. Render IDs now use mermaid-${id}-${++renderCounter}, which is strictly unique and avoids any ms-precision collision risk.

@malibio
malibio merged commit 167e4df into main Mar 17, 2026
@malibio
malibio deleted the fix/issue-938-mermaid-rerender-on-blur branch March 17, 2026 10:54
malibio added a commit that referenced this pull request Jun 22, 2026
* Fix mermaid diagram disappearing after blur from edit mode (closes #938)

Root cause: mermaid.render() uses the element ID to create a temporary DOM
element during rendering. When blur triggers rapid re-renders (the $effect
fires multiple times as isEditing changes propagate across all mermaid nodes),
two concurrent render calls for the same node share the same element ID
(mermaid-{nodeId}). The first render's result gets discarded as stale by the
sequence guard, and the second render fails because the ID already exists in
the DOM — causing mermaid to throw and return null, clearing the diagram.

Fix: use a unique render ID per call (mermaid-{nodeId}-{timestamp}) so
concurrent renders never collide. The temp element is cleaned up after each
successful render.

Co-Authored-By: Claude <[email protected]>

* Fix DOM temp element leak on Mermaid render failure

Use try/finally for temp element cleanup so it always runs even when
mermaid.render() throws. Also replace Date.now() with a module-level
monotonic counter to guarantee unique render IDs with no ms-precision
collision risk.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>

---------

Co-authored-by: Claude <[email protected]>
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.

Mermaid diagram disappears after blurring from edit mode

1 participant