Skip to content

Commit 3260362

Browse files
committed
fix(mdviewer): prevent cursor sync highlight flash during CM typing
Track the last highlighted source line and re-apply the highlight after content re-renders (file:rendered event) so typing in CM doesn't cause the viewer highlight to flash off and on. Clear tracked line when viewer gets focus.
1 parent b47d269 commit 3260362

1 file changed

Lines changed: 32 additions & 0 deletions

File tree

src-mdviewer/src/bridge.js

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -842,14 +842,46 @@ function handleScrollToLine(data) {
842842
const prev = viewer.querySelector(".cursor-sync-highlight");
843843
if (prev) { prev.classList.remove("cursor-sync-highlight"); }
844844
bestEl.classList.add("cursor-sync-highlight");
845+
_lastHighlightSourceLine = bestLine;
845846
}
846847

848+
// Track last highlighted source line so we can re-apply after re-renders
849+
let _lastHighlightSourceLine = null;
850+
851+
function _reapplyCursorSyncHighlight() {
852+
if (_lastHighlightSourceLine == null) return;
853+
const viewer = document.getElementById("viewer-content");
854+
if (!viewer) return;
855+
// Don't re-apply if viewer has focus (user is editing in viewer)
856+
if (viewer.contains(document.activeElement)) return;
857+
const elements = viewer.querySelectorAll("[data-source-line]");
858+
let bestEl = null;
859+
let bestLine = -1;
860+
for (const el of elements) {
861+
const srcLine = parseInt(el.getAttribute("data-source-line"), 10);
862+
if (srcLine <= _lastHighlightSourceLine && srcLine > bestLine) {
863+
bestLine = srcLine;
864+
bestEl = el;
865+
}
866+
}
867+
if (bestEl) {
868+
bestEl.classList.add("cursor-sync-highlight");
869+
}
870+
}
871+
872+
// Re-apply cursor sync highlight after content re-renders (e.g. typing in CM)
873+
on("file:rendered", () => {
874+
// Small delay to let morphdom finish updating the DOM
875+
requestAnimationFrame(_reapplyCursorSyncHighlight);
876+
});
877+
847878
// Clear viewer highlight when viewer gets focus (user is editing in viewer)
848879
document.addEventListener("focusin", (e) => {
849880
const viewer = document.getElementById("viewer-content");
850881
if (viewer && viewer.contains(e.target)) {
851882
const prev = viewer.querySelector(".cursor-sync-highlight");
852883
if (prev) { prev.classList.remove("cursor-sync-highlight"); }
884+
_lastHighlightSourceLine = null;
853885
}
854886
});
855887

0 commit comments

Comments
 (0)