Skip to content

fix(penpal): stabilize MarkdownViewer components to preserve mermaid SVGs#543

Merged
loganj merged 1 commit intomainfrom
fix-mermaid-diagram-highlighti
Mar 30, 2026
Merged

fix(penpal): stabilize MarkdownViewer components to preserve mermaid SVGs#543
loganj merged 1 commit intomainfrom
fix-mermaid-diagram-highlighti

Conversation

@loganj
Copy link
Copy Markdown
Collaborator

@loganj loganj commented Mar 30, 2026

Summary

Commit bb7b31b changed the components useMemo in MarkdownViewer from useMemo(…, []) to useMemo(…, [highlights]) so the code component could read highlights for code block highlighting. That was the logically correct change for code highlights to work, but it had a side effect: components got new function references whenever highlights changed. React-Markdown treats component functions as element types, so changed references triggered unmount/remount of all custom components — destroying externally-rendered mermaid SVGs and their highlight overlays.

The bug wasn't caught because all existing MarkdownViewer tests rendered once and checked output. None exercised React's reconciliation across re-renders. A single-render test can never catch this class of bug because the first render is always correct — the destruction happens when React sees new component function references on a subsequent render and unmounts/remounts.

Fix: Store highlights in a ref (highlightsRef) and read from it in the code component, allowing useMemo to use [] for stable function references. React reconciles in place, preserving mermaid SVGs.

Testing gap closed: Added a test that uses rerender() and checks DOM element reference identity (toBe) on the mermaid container. If anyone changes the useMemo deps back to [highlights] (or adds any dependency that causes component function recreation), this test fails immediately — the mermaid container would be a different DOM node after re-render.

🤖 Generated with Claude Code

…SVGs

The components useMemo in MarkdownViewer depended on [highlights], causing
new function references on every highlight change. React-Markdown treats
component functions as element types, so changed references triggered
unmount/remount of all custom components — destroying externally-rendered
mermaid SVGs and their highlight overlays.

Fix: store highlights in a ref and read from it in the code component,
allowing useMemo to use [] (no deps) for stable function references.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
@loganj loganj merged commit 44be13a into main Mar 30, 2026
4 checks passed
@loganj loganj deleted the fix-mermaid-diagram-highlighti branch March 30, 2026 01:58
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