Contenteditable: Some problems with creating and focusing span

I’ve been trying to solve this issue for a few days now but I don’t have any idea how I can fix it. I hope you can help me or give me some tips which lead me to the point to fix the issues.

I’m developing a feature in my app where it is possible to execute specific function on each sentence. Each sentence is assigned to a span element.

The browser’s default functionality destroys the entire functionality of the feature so I’m trying to add a custom functionality what happens if the user presses enter at the end of a sentence. My goal is to add a new line break with a new span each time when the cursor is at the end of the sentence and the user presses enter. The cursor should follow automatically the line breaks (go into the next row) and should focus the created span element that the input is assigned to the span.

I’ve tried to do it with the Selection-API and some things are working but not everything.

The things that aren’t working are:

  • move the cursor automatically into the next line
  • to focus the created span that the input is assigned to it and not inserted between the span elements (such as on the picture)

enter image description here

  • to add the line break and span at the end of a sentence outside the focused span (it doesn’t work, because I append the newly created spans as a child to the contentediable container.

In the contenteditable container should only be span elements on 1 layer without any deeper structure/layers.

How can I solve these isses?

This is my code:

public addOwnBehaviorToContentEditable(event: KeyboardEvent) {
    if (event.key !== 'Enter') return;

    event.preventDefault();

    let contenteditable = event.target as HTMLElement;
    let selection = this._document.getSelection();

    if (selection.rangeCount > 0) {
      let range = selection.getRangeAt(0);
      // Get the common ancestor container of the start and end nodes of the range
      let container = range.commonAncestorContainer;
      // Is the user in the last span element and at the end of the range (sentence) a new <br> and <span> element is created

      if (range.endOffset === container.textContent.length) {
        contenteditable.appendChild(this._document.createElement('br'));
        let span = this._document.createElement('span');
        span.textContent = '';

        this.assignPropertiesToSpan(span);
        contenteditable.appendChild(span);

        span.focus();

        let newRange = this._document.createRange();
        newRange.setStart(span, 0);
        

        selection.removeAllRanges();
        selection.addRange(newRange);
      } else {
        range.insertNode(document.createElement('br'));
      }
    }
  }