Skip to content

Commit

Permalink
Fix cursor position issue after introducing block separators
Browse files Browse the repository at this point in the history
  • Loading branch information
Skalakid committed Oct 11, 2024
1 parent 03811f0 commit 1b1e801
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 2 deletions.
14 changes: 13 additions & 1 deletion src/web/utils/cursorUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,18 @@ function moveCursorToEnd(target: HTMLElement) {
}
}

function getNodeOffset(targetNode: TreeNode, rangeContainer: Node, rangeOffset: number) {
let index = targetNode.start;
if (rangeContainer.nodeType !== Node.TEXT_NODE) {
targetNode.childNodes.forEach((node) => {
index += node.element.value.length;
});
} else {
index += rangeOffset;
}
return index;
}

function getCurrentCursorPosition(target: MarkdownTextInputElement) {
function getHTMLElement(node: Node) {
let element = node as HTMLElement | Text;
Expand Down Expand Up @@ -117,7 +129,7 @@ function getCurrentCursorPosition(target: MarkdownTextInputElement) {
if (endTreeNode?.parentNode === null) {
end = target.value.length;
} else {
end = endTreeNode.start + range.endOffset;
end = getNodeOffset(endTreeNode, range.endContainer, range.endOffset);
}
}
return {start, end};
Expand Down
4 changes: 3 additions & 1 deletion src/web/utils/parserUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -205,7 +205,9 @@ function parseRangesToHTMLNodes(
// wrap all elements before the first block type markdown range with a span element
const blockRange = getFirstBlockMarkdownRange([range, ...lineMarkdownRanges]);
if (!wasBlockGenerated && blockRange) {
currentParentNode = addBlockWrapper(currentParentNode, line.text.substring(lastRangeEndIndex - line.start, blockRange.start + blockRange.length - line.start).length, markdownStyle);
const blockText = line.text.substring(lastRangeEndIndex - line.start, blockRange.start + blockRange.length - line.start);
currentParentNode = addBlockWrapper(currentParentNode, blockText.length, markdownStyle);
currentParentNode.element.value = blockText;
wasBlockGenerated = true;
}
// add text before the markdown range
Expand Down
2 changes: 2 additions & 0 deletions src/web/utils/treeUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,9 @@ function updateTreeElementRefs(treeRoot: TreeNode, element: HTMLMarkdownElement)

const currentElement = dataIDToElementMap[node.orderIndex];
if (currentElement) {
const nodeValue = node.element.value;
node.element = currentElement;
node.element.value = nodeValue;
}
}

Expand Down

0 comments on commit 1b1e801

Please sign in to comment.