From fdb8f6e93f7ab3a220cc5799276543e251ba72b2 Mon Sep 17 00:00:00 2001 From: Peter Savchenko Date: Wed, 9 Oct 2024 22:07:44 +0300 Subject: [PATCH 1/2] fix(caret): fix focus at start when first child is empty --- packages/caret/package.json | 2 +- packages/caret/src/focus/focus.ts | 11 ++++++++--- 2 files changed, 9 insertions(+), 4 deletions(-) diff --git a/packages/caret/package.json b/packages/caret/package.json index 5f9edc3..3bd7cfb 100644 --- a/packages/caret/package.json +++ b/packages/caret/package.json @@ -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": { diff --git a/packages/caret/src/focus/focus.ts b/packages/caret/src/focus/focus.ts index 01783a1..5863e3d 100644 --- a/packages/caret/src/focus/focus.ts +++ b/packages/caret/src/focus/focus.ts @@ -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 */ - 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); }; @@ -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 { /** From 6616aedca43564bd081d2cba74fd20fbbc4986c1 Mon Sep 17 00:00:00 2001 From: Peter Savchenko Date: Wed, 9 Oct 2024 22:09:11 +0300 Subject: [PATCH 2/2] Update focus.ts --- packages/caret/src/focus/focus.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/caret/src/focus/focus.ts b/packages/caret/src/focus/focus.ts index 5863e3d..cd0738f 100644 --- a/packages/caret/src/focus/focus.ts +++ b/packages/caret/src/focus/focus.ts @@ -23,7 +23,7 @@ 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 + * @param prepend - should the text node be prepended or appended */ const createAndFocusTextNode = (parent: HTMLElement | ChildNode, prepend = false): void => { const textNode = document.createTextNode('');