Skip to content

Commit 5f67ec9

Browse files
committed
fix(mdviewer): re-render from CM content on edit→reader switch for cursor sync
When switching from edit to reader mode, MarkdownSync now sends the current CM document text back to the iframe. The iframe re-parses it to produce fresh data-source-line attributes so cursor sync works on newly edited elements.
1 parent 181e23d commit 5f67ec9

2 files changed

Lines changed: 23 additions & 3 deletions

File tree

src-mdviewer/src/bridge.js

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -290,6 +290,8 @@ export function initBridge() {
290290
on("bridge:contentChanged", ({ markdown }) => {
291291
if (_suppressContentChange) return;
292292
_syncId++;
293+
// Keep state.currentContent in sync so edit→reader re-render has latest content
294+
setState({ currentContent: markdown });
293295
// Update the cache entry's mdSrc so it stays in sync
294296
const activePath = docCache.getActiveFilePath();
295297
if (activePath) {
@@ -594,8 +596,16 @@ function handleSetTheme(data) {
594596
}
595597

596598
function handleSetEditMode(data) {
597-
const { editMode } = data;
599+
const { editMode, markdown } = data;
598600
setState({ editMode });
601+
602+
// When switching to reader, re-render from CM's current markdown
603+
// so all elements get fresh data-source-line attributes for cursor sync.
604+
if (!editMode && markdown) {
605+
const parseResult = parseMarkdownToHTML(markdown);
606+
setState({ currentContent: markdown, parseResult });
607+
emit("file:rendered", parseResult);
608+
}
599609
}
600610

601611

src/extensionsIntegrated/Phoenix-live-preview/MarkdownSync.js

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -107,7 +107,11 @@ define(function (require, exports, module) {
107107
_handleRedo();
108108
break;
109109
case "mdviewrEditModeChanged":
110-
// Could be used to sync edit mode UI state in Phoenix if needed
110+
// When switching to reader, send CM content back so the iframe
111+
// can re-render with accurate data-source-line for cursor sync.
112+
if (!data.editMode && _doc) {
113+
setEditMode(false);
114+
}
111115
break;
112116
case "mdviewrRequestEditMode":
113117
if (_onEditModeRequest) {
@@ -707,7 +711,13 @@ define(function (require, exports, module) {
707711
}
708712
const iframeWindow = _getIframeWindow();
709713
if (iframeWindow) {
710-
iframeWindow.postMessage({ type: "MDVIEWR_SET_EDIT_MODE", editMode: editMode }, "*");
714+
const msg = { type: "MDVIEWR_SET_EDIT_MODE", editMode: editMode };
715+
// When switching to reader, include current CM content so the iframe
716+
// can re-render with accurate data-source-line attributes for cursor sync.
717+
if (!editMode && _doc) {
718+
msg.markdown = _doc.getText();
719+
}
720+
iframeWindow.postMessage(msg, "*");
711721
}
712722
}
713723

0 commit comments

Comments
 (0)