Leonardo Cavalcante
Leonardo Cavalcante

Reputation: 1303

retrieve block and cursor position on editor.js after lose focus

I need help with editor.js

Imagine the following scenario, on my page I have the editor.js on the right and a bunch of buttons on the right side of the screen.

The buttons are a collection of phrases, and when click on it, the phrase must be inserted in the editor.js

However, it must be inserted where the cursor was before losing focus, considering it to be anywhere in the editor.js, Example, can be in the first, second or last block, and within a specific block, the cursor can be in the beginning, middle or end of the sentence.

How can I retrieve the block and cursor position to insert the new phrase?

Thanks in advance

Upvotes: 0

Views: 3535

Answers (2)

Azibodusi Duke Osain
Azibodusi Duke Osain

Reputation: 11

I needed a similar functionality so i did the following to achieve it, using reactjs.

created ref that will hold the current index const currentBlockIndexRef = useRef('')

How to get the current index.

To get the current index, the api is used. When you click the editor where the user wants to add content, the Onchange(api) can be used which will contain the current block index corresponding to where the user wants to add content. As shown below.

 const editor = new EditorJS({
     holder: editorId,
     logLevel: "ERROR",
     data: initData,
     onReady: () => {
       ejInstance.current = editor;
     },
     onChange: function(api, block) {
           console.log('api', api.blocks.getCurrentBlockIndex())
           currentBlockIndexRef.current= api.blocks.getCurrentBlockIndex() // update ref with the current index
         editor.save().then((data) => {
 
          setEditorData({ ...editorData,data,});
         })
       
     },
     autofocus: true,
     readOnly: false,
     tools: editorTools
   });
   editorJs = editor
 };
``` 

Then you can insert the block at the index 

 editorJs.blocks.insert('image', {...data.data},'',currentBlockIndexRef.current) // update the block 

Upvotes: 0

nC Ann
nC Ann

Reputation: 31

You can try to use the below to set the cursor back to the previous position. However, this doesn't work correctly if you have nested elements in your block.

editor.caret.setToBlock(/* current block index */, null, /* last cursor position */)

To get last cursor position:

let selection = document.getSelection();
let cursorPosition = selection.anchorOffset;

To get current block index:

let currentBlockIndex = editor.blocks.getCurrentBlockIndex()

where editor is your created editor.js instance.

Reference: https://editorjs.io/caret#settoblock

Upvotes: 3

Related Questions