Skip to content

Commit

Permalink
Add selection removing on blur
Browse files Browse the repository at this point in the history
  • Loading branch information
Skalakid committed Mar 1, 2024
1 parent 0ee944c commit b625b61
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 13 deletions.
1 change: 1 addition & 0 deletions src/MarkdownTextInput.web.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -422,6 +422,7 @@ const MarkdownTextInput = React.forwardRef<TextInput, MarkdownTextInputProps>(
const handleBlur: FocusEventHandler<HTMLDivElement> = useCallback(
(event) => {
const e = event as unknown as NativeSyntheticEvent<TextInputFocusEventData>;
CursorUtils.removeSelection();
currentlyFocusedField.current = null;
if (onBlur) {
setEventProps(e);
Expand Down
35 changes: 22 additions & 13 deletions src/web/cursorUtils.ts
Original file line number Diff line number Diff line change
@@ -1,20 +1,22 @@
function findTextNodes(textNodes: Text[], node: ChildNode) {
if (node.nodeType === 3) {
textNodes.push(node as Text);
} else {
for (let i = 0, len = node.childNodes.length; i < len; ++i) {
const childNode = node.childNodes[i];
if (childNode) {
findTextNodes(textNodes, childNode);
}
}
}
}

function setCursorPosition(target: HTMLElement, start: number, end: number | null = null) {
const range = document.createRange();
range.selectNodeContents(target);

const textNodes: Text[] = [];
(function findTextNodes(node: ChildNode) {
if (node.nodeType === 3) {
textNodes.push(node as Text);
} else {
for (let i = 0, len = node.childNodes.length; i < len; ++i) {
const childNode = node.childNodes[i];
if (childNode) {
findTextNodes(childNode);
}
}
}
})(target);
findTextNodes(textNodes, target);

let charCount = 0;
let startNode: Text | null = null;
Expand Down Expand Up @@ -80,4 +82,11 @@ function getCurrentCursorPosition(target: HTMLElement) {
return {start: -1, end: -1};
}

export {getCurrentCursorPosition, moveCursorToEnd, setCursorPosition};
function removeSelection() {
const sel = window.getSelection();
if (sel) {
sel.removeAllRanges();
}
}

export {getCurrentCursorPosition, moveCursorToEnd, setCursorPosition, removeSelection};

0 comments on commit b625b61

Please sign in to comment.