Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(caret): Improve getCaretNodeAndOffset to handle non-editable element #2853

Open
wants to merge 1 commit into
base: next
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 42 additions & 0 deletions src/components/utils/caret.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,32 @@
import $, { isCollapsedWhitespaces } from '../dom';

/**
* New: Helper function to find the first editable text node
* This function recursively searches for an editable text node
*
* @param node Node
*/
function findFirstEditableTextNode(node: Node): Text | null {
if (node.nodeType === Node.TEXT_NODE) {
return node as Text;
}
if (node.nodeType === Node.ELEMENT_NODE) {
const element = node as HTMLElement;

if (element.contentEditable !== 'false') {
for (const child of Array.from(element.childNodes)) {
const textNode = findFirstEditableTextNode(child);

if (textNode) {
return textNode;
}
}
}
}

return null;
}

/**
* Returns TextNode containing a caret and a caret offset in it
* Returns null if there is no caret set
Expand Down Expand Up @@ -45,6 +72,21 @@ export function getCaretNodeAndOffset(): [ Node | null, number ] {
}
}

/**
* Handle case when focusNode is not a text node
* Find the first editable text node within the current node
*/
if (focusNode.nodeType !== Node.TEXT_NODE) {
const textNode = findFirstEditableTextNode(focusNode);
if (textNode) {
focusNode = textNode;
focusOffset = 0;
} else {
// If no editable text node found, return null
return [null, 0];
}
}
Comment on lines +79 to +88
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

please, write tests for both cases


return [focusNode, focusOffset];
}

Expand Down