Skip to content

Commit

Permalink
Change get selection function
Browse files Browse the repository at this point in the history
  • Loading branch information
Skalakid committed Mar 1, 2024
1 parent a264ab2 commit d82147b
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 27 deletions.
11 changes: 6 additions & 5 deletions src/MarkdownTextInput.web.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -307,11 +307,12 @@ const MarkdownTextInput = React.forwardRef<TextInput, MarkdownTextInputProps>(
const currentSelection = CursorUtils.getCurrentCursorPosition(divRef.current);

if (contentSelection.current.start !== currentSelection.start || contentSelection.current.end !== currentSelection.end) {
const markdownHTMLInput = divRef.current as HTMLInputElement;
markdownHTMLInput.selectionStart = currentSelection.start;
markdownHTMLInput.selectionEnd = currentSelection.end;
contentSelection.current = currentSelection;

if (contentSelection.current.start >= 0 && contentSelection.current.end >= 0) {
const markdownHTMLInput = divRef.current as HTMLInputElement;
markdownHTMLInput.selectionStart = currentSelection.start;
markdownHTMLInput.selectionEnd = currentSelection.end;
contentSelection.current = currentSelection;
}
if (e) {
handleSelectionChange(e);
}
Expand Down
35 changes: 13 additions & 22 deletions src/web/cursorUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,31 +62,22 @@ function moveCursorToEnd(target: HTMLElement) {
}
}

function getIndexedPosition(target: HTMLElement, range: Range, isStart: boolean) {
const marker = document.createTextNode('\0');
const rangeClone = range.cloneRange();

rangeClone.collapse(isStart);

rangeClone.insertNode(marker);
const position = target.innerText.indexOf('\0');
if (marker.parentNode) {
marker.parentNode.removeChild(marker);
}
function getCurrentCursorPosition(target: HTMLElement) {
const sel = window.getSelection();

return position;
}
if (sel && sel.rangeCount > 0) {
const range = sel.getRangeAt(0);
const preSelectionRange = range.cloneRange();
preSelectionRange.selectNodeContents(target);
preSelectionRange.setEnd(range.startContainer, range.startOffset);
const start = preSelectionRange.toString().length;

function getCurrentCursorPosition(target: HTMLElement) {
const selection = document.getSelection();
if (!selection || selection.rangeCount === 0) {
return {start: target.innerText.length, end: target.innerText.length};
return {
start,
end: start + range.toString().length,
};
}

const range = selection.getRangeAt(0);
const start = getIndexedPosition(target, range, true);
const end = getIndexedPosition(target, range, false);
return {start, end};
return {start: -1, end: -1};
}

export {getCurrentCursorPosition, moveCursorToEnd, setCursorPosition};

0 comments on commit d82147b

Please sign in to comment.