editor.js icon indicating copy to clipboard operation
editor.js copied to clipboard

Insert Text, without selection - not block

Open kogutu opened this issue 11 months ago • 1 comments

Hello everyone, Please tell me is it possible to insert text by click by button - ex. {{text}} to current cursor position without selection text or add new block - I try create possibilty to insert template text from database to speed up fill text.

kogutu avatar Feb 12 '25 11:02 kogutu

to add text at cursor you can use code like this:

   const selection = window.getSelection(); //get cursor position from browser api (offset and target element)
    if (!selection || !selection.anchorNode) return;
    const element = selection.anchorNode.parentElement //anchor is textNode
    if (element == null) return;
    const block = editor.blocks.getBlockByElement(element)
    if (block == undefined) return; //check block is in editor
    const offset = selection.anchorOffset; //get cursor offset in element and store it to use after text insert
    const originalText = selection.anchorNode.textContent;
    if (originalText) {
      selection.anchorNode.textContent = originalText.slice(0, offset) + text + originalText.slice(offset); //add text at cursor position and set to node
    } else {
      selection.anchorNode.textContent = text;
    }
    block.dispatchChange();
    editor.caret.setToBlock(block, 'default', offset+text.length); //set cursor at end of inserted text and focus element

In the table or other elements with complicated structure set cursor in element is not working, but text is inserted in selected position.

4ib3r avatar Mar 29 '25 10:03 4ib3r