Skip to content

Insert Text, without selection - not block #2912

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

Open
kogutu opened this issue Feb 12, 2025 · 1 comment
Open

Insert Text, without selection - not block #2912

kogutu opened this issue Feb 12, 2025 · 1 comment

Comments

@kogutu
Copy link

kogutu commented Feb 12, 2025

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.

@4ib3r
Copy link

4ib3r commented Mar 29, 2025

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants