Currently, I am developing a straightforward syntax highlighter that transforms text into DOM elements with specified classes.
For example, consider the following:
<div contenteditable="true">
Some text. | And some other text.
</div>
Assume that the cursor is positioned at the | pipe.
If a user were to type foo
:
<div contenteditable="true">
Some text. foo| And some other text.
</div>
After replacing the text and adjusting the selection, the result would be:
<div contenteditable="true">
Some text. <span class="highlight-foo">foo</span>| And some other text.
</div>
However, a problem arises when trying to type within the newly inserted element:
<div contenteditable="true">
Some text. <span class="highlight-foo">foobar|</span> And some other text.
</div>
It is not desired for the user input to be within the span element, as shown in the above example.
Despite attempting various solutions, such as adjusting the selection after the element insertion, the issue persist:
<div contenteditable="true">
Some text. <span class="highlight-foo">foo</span>bar| And some other text.
</div>
Below is the Javascript code responsible for highlighting and replacing:
...
// Chunk variable holds 'foo' in the given example
// Select it
range.setStart(range.startContainer, range.startOffset - chunk.length);
// Add it to the range
sel.addRange(range);
// Replace it, then set the range to the textNode after the span
// Ideally, the selection should be outside the span element
range.setStart(sel.anchorNode.parentNode.nextSibling, 0);
// Even though the range is set correctly above, adding it back to the selection does not resolve the issue
sel.removeAllRanges();
sel.addRange(range);
// The selection remains within the span element
Seeking a solution to this issue has been challenging, as existing resources do not address this specific problem. Any suggestions on how to overcome this?