The problem with the code above is that I can’t get the cursor (caret) position within the “contenteditable” div—the text gets added at the end of the element tree.
Hello @unlustucru, I think you should manipulate the Rich Text’s value to achieve this. Let’s say that you want to append a “hello world”, you’d go and do the following:
But for some reason I’m not able to find the input element of this component. It seems like WeWeb uses a library for this, called TipTap, I’m afraid that it won’t be that simple to do.
@Broberto The input is a contenteditable div (classes .tiptap and.ProseMirror). I’ve tried with JS but unsucessfully so far. The first problem was to preserve the text caret position when the button was clicked. I managed that, but the string doesnt get added at the right spot for some reason; my JS skills are limited.
That’s why I posted on here, because since other functions of the text editor can obviously successfully detect the caret position, i thought Weweb could help.
I think I got it thanks to this. I’ll get back to you in a few.
You can get the position of the cursor like this:
const doc = wwLib.getFrontDocument();
console.log(doc.getSelection()) // This gets you the selection
console.log(doc.getSelection().anchorOffset) // This gets you the position of the cursor within the <p> tag
The only issue is that this renders HTML, so the other tags make it hard to insert a string at a certain index, because the tags actually increase the length of the string.
If you then save it as a variable, you can use it further.
function insertTextIntoRichTextInput(text) {
const richTextInput = document.querySelector('[contenteditable="true"]');
if (!richTextInput) {
alert('Rich Text Input element not found');
return;
}
// Insert the text at the cursor position or at the end if no selection
const selection = window.getSelection();
if (selection.rangeCount > 0) {
const range = selection.getRangeAt(0);
range.deleteContents();
range.insertNode(document.createTextNode(text));
} else {
richTextInput.appendChild(document.createTextNode(text));
}
// Trigger an input event to ensure WeWeb recognizes the change
richTextInput.dispatchEvent(new Event('input', { bubbles: true }));
alert('Text inserted successfully');
}
insertTextIntoRichTextInput('Hello World');