Skip to content

Commit 6f5efd7

Browse files
committed
fix(mdviewer): preserve scroll position when closing image edit dialog
Place cursor near the image on dialog close so selection handlers don't scroll to top. Use requestAnimationFrame to restore scroll position after any async handlers that fire from the focus/selection change.
1 parent 2670765 commit 6f5efd7

1 file changed

Lines changed: 22 additions & 1 deletion

File tree

src-mdviewer/src/components/image-popover.js

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -223,9 +223,30 @@ function showEditDialog(imgEl, currentSrc, currentAlt) {
223223
urlInput.select();
224224

225225
function close() {
226+
const appViewer = document.getElementById("app-viewer");
227+
const scrollTop = appViewer ? appViewer.scrollTop : 0;
226228
backdrop.remove();
227-
if (contentEl) {
229+
// Place cursor near the image so focus doesn't reset to top
230+
if (imgEl && imgEl.parentNode && contentEl) {
231+
const block = imgEl.closest("p, div, li") || imgEl.parentNode;
232+
const range = document.createRange();
233+
if (block.nextSibling) {
234+
range.setStartBefore(block.nextSibling);
235+
} else {
236+
range.selectNodeContents(block);
237+
range.collapse(false);
238+
}
239+
const sel = window.getSelection();
240+
sel.removeAllRanges();
241+
sel.addRange(range);
228242
contentEl.focus({ preventScroll: true });
243+
} else if (contentEl) {
244+
contentEl.focus({ preventScroll: true });
245+
}
246+
// Restore scroll in case async handlers shifted it
247+
if (appViewer) {
248+
appViewer.scrollTop = scrollTop;
249+
requestAnimationFrame(() => { appViewer.scrollTop = scrollTop; });
229250
}
230251
}
231252

0 commit comments

Comments
 (0)