Skip to content

Commit

Permalink
fix: cursor positioning
Browse files Browse the repository at this point in the history
  • Loading branch information
BartoszGrajdek committed Oct 28, 2024
1 parent e54929e commit 6379bb5
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 3 deletions.
10 changes: 9 additions & 1 deletion src/web/utils/blockUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -128,4 +128,12 @@ function extendBlockStructure(
return targetNode;
}

export {addStyleToBlock, extendBlockStructure, isBlockMarkdownType, getFirstBlockMarkdownRange};
function getTopParentTreeNode(node: TreeNode) {
let currentParentNode = node.parentNode;
while (currentParentNode && ['text', 'br', 'line', 'syntax'].includes(currentParentNode.parentNode?.type || '')) {
currentParentNode = currentParentNode?.parentNode || null;
}
return currentParentNode;
}

export {addStyleToBlock, extendBlockStructure, isBlockMarkdownType, getFirstBlockMarkdownRange, getTopParentTreeNode};
12 changes: 10 additions & 2 deletions src/web/utils/cursorUtils.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import type {MarkdownTextInputElement} from '../../MarkdownTextInput.web';
import {getTopParentTreeNode} from './blockUtils';
import {findHTMLElementInTree, getTreeNodeByIndex} from './treeUtils';
import type {TreeNode} from './treeUtils';

Expand All @@ -17,8 +18,15 @@ function setCursorPosition(target: MarkdownTextInputElement, startIndex: number,
const range = document.createRange();
range.selectNodeContents(target);

const startTreeNode = getTreeNodeByIndex(target.tree, start);
const endTreeNode = end && startTreeNode && (end < startTreeNode.start || end >= startTreeNode.start + startTreeNode.length) ? getTreeNodeByIndex(target.tree, end) : startTreeNode;
let startTreeNode = getTreeNodeByIndex(target.tree, start);
let endTreeNode = end && startTreeNode && (end < startTreeNode.start || end >= startTreeNode.start + startTreeNode.length) ? getTreeNodeByIndex(target.tree, end) : startTreeNode;

const parentLine = startTreeNode?.type === 'br' && getTopParentTreeNode(startTreeNode);
if (parentLine && parentLine?.childNodes?.some((e) => e.type === 'pre')) {
startTreeNode = getTreeNodeByIndex(target.tree, start - 1);
endTreeNode = startTreeNode;
}

if (!startTreeNode || !endTreeNode) {
console.error('Invalid start or end tree node');
return;
Expand Down

0 comments on commit 6379bb5

Please sign in to comment.