Skip to content

Commit

Permalink
Merge pull request #26 from editor-js/fix-focus-start
Browse files Browse the repository at this point in the history
fix(caret): fix focus at start when first child is empty
  • Loading branch information
neSpecc authored Oct 9, 2024
2 parents 2927c2e + 6616aed commit 2ba780f
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 4 deletions.
2 changes: 1 addition & 1 deletion packages/caret/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
"description": "Utils useful for work with caret for Editor.js tools development",
"repository": "https://github.com/editor-js/utils/tree/main/packages/caret",
"link": "https://github.com/editor-js/utils/tree/main/packages/caret",
"version": "1.0.1",
"version": "1.0.2",
"main": "dist/index.js",
"license": "MIT",
"scripts": {
Expand Down
11 changes: 8 additions & 3 deletions packages/caret/src/focus/focus.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,11 +23,16 @@ export function focus(element: HTMLElement, atStart: boolean = true): void {
/**
* Helper function to create a new text node and set the caret
* @param parent - parent element to append the text node
* @param prepend - should the text node be prepended or appended
*/
const createAndFocusTextNode = (parent: HTMLElement): void => {
const createAndFocusTextNode = (parent: HTMLElement | ChildNode, prepend = false): void => {
const textNode = document.createTextNode('');

parent.appendChild(textNode);
if (prepend) {
parent.insertBefore(textNode, parent.firstChild);
} else {
parent.appendChild(textNode);
}
range.setStart(textNode, 0);
range.setEnd(textNode, 0);
};
Expand Down Expand Up @@ -67,7 +72,7 @@ export function focus(element: HTMLElement, atStart: boolean = true): void {
/**
* If no text node is found, create one and set focus
*/
createAndFocusTextNode(element);
createAndFocusTextNode(element, atStart);
}
} else {
/**
Expand Down

0 comments on commit 2ba780f

Please sign in to comment.