Skip to content

Commit 46a8b68

Browse files
committed
fix(mdviewer): fix End/Home key jumping to end of file near images
Contenteditable jumps to container end/start instead of block end/start when cursor is near an <img>. Intercept End/Home (and Cmd+Right/Left on Mac) to manually position cursor at block boundary.
1 parent 09e5dcf commit 46a8b68

1 file changed

Lines changed: 28 additions & 0 deletions

File tree

src-mdviewer/src/components/editor.js

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1835,6 +1835,34 @@ function enterEditMode(content) {
18351835
}
18361836
}
18371837

1838+
// Fix End/Home key near images — contenteditable jumps to end/start of
1839+
// container instead of end/start of current block when cursor is near <img>.
1840+
// On Mac, Cmd+Right/Left is the equivalent of End/Home.
1841+
const isEndKey = e.key === "End" || (isMac && e.metaKey && e.key === "ArrowRight");
1842+
const isHomeKey = e.key === "Home" || (isMac && e.metaKey && e.key === "ArrowLeft");
1843+
if ((isEndKey || isHomeKey) && !(e.key === "End" && mod) && !(e.key === "Home" && mod)) {
1844+
const sel = window.getSelection();
1845+
if (sel && sel.rangeCount) {
1846+
let node = sel.anchorNode;
1847+
if (node?.nodeType === Node.TEXT_NODE) node = node.parentElement;
1848+
const block = node?.closest("p, h1, h2, h3, h4, h5, h6, li, blockquote, td, th");
1849+
if (block && block.querySelector("img")) {
1850+
e.preventDefault();
1851+
const range = document.createRange();
1852+
if (isEndKey) {
1853+
range.selectNodeContents(block);
1854+
range.collapse(false);
1855+
} else {
1856+
range.selectNodeContents(block);
1857+
range.collapse(true);
1858+
}
1859+
sel.removeAllRanges();
1860+
sel.addRange(range);
1861+
return;
1862+
}
1863+
}
1864+
}
1865+
18381866
// ArrowDown at end of code block → exit to paragraph below
18391867
if (e.key === "ArrowDown" && !mod) {
18401868
const sel = window.getSelection();

0 commit comments

Comments
 (0)