Playing with ranges

Range sample

by Paul Sijpkes

HTML

<textarea style='width: 400px; height: 100px' placeholder='serialised content here' id='inputMe'>{"id":"m_0","index":1,"start":23,"end":148,"startXpath":"/*[name()='HTML' and namespace-uri()='http://www.w3.org/1999/xhtml']/*[name()='BODY' and namespace-uri()='http://www.w3.org/1999/xhtml'][1]/*[name()='DIV' and namespace-uri()='http://www.w3.org/1999/xhtml'][1]","endXPath":"/*[name()='HTML' and namespace-uri()='http://www.w3.org/1999/xhtml']/*[name()='BODY' and namespace-uri()='http://www.w3.org/1999/xhtml'][1]/*[name()='DIV' and namespace-uri()='http://www.w3.org/1999/xhtml'][1]"}
  
 
</textarea>
<button id='process'>
Process
</button>

JavaScript

function getXPathForElement(el, xml) {
  var xpath = '';
  var pos, tempitem2;

  while (el !== xml.documentElement) {
    pos = 0;
    tempitem2 = el;
    while (tempitem2) {
      if (tempitem2.nodeType === 1 && tempitem2.nodeName === el.nodeName) { // If it is ELEMENT_NODE of the same name
        pos += 1;
      }
      tempitem2 = tempitem2.previousSibling;
    }

    xpath = "*[name()='" + el.nodeName + "' and namespace-uri()='" + (el.namespaceURI === null ? '' : el.namespaceURI) + "'][" + pos + ']' + '/' + xpath;

    el = el.parentNode;
  }
  xpath = '/*' + "[name()='" + xml.documentElement.nodeName + "' and namespace-uri()='" + (el.namespaceURI === null ? '' : el.namespaceURI) + "']" + '/' + xpath;
  xpath = xpath.replace(/\/$/, '');
  return xpath;
}

var str1 = "He rose and began to walk uneasily up and down the room.  But the \
same vacant darkness was on his brow.  He had his hands in his \
pockets.  Hannele sat feeling helpless.  She couldn't help being in \
love with the man: with his hands, with his strange, fascinating \
physique, with his incalculable presence.  She loved the way he put \
his feet down, she loved the way he moved his legs";

var str2 = "with his strange, fascinating physique, with his incalculable";

var div = document.createElement('div');

document.body.appendChild(div)
div.textContent = str1;

var originalInnerHtml = div.innerHTML;


const stack = []

function getOverlaps(start) {
  return stack.filter((o, i) => {
    console.log("filtering", o, start)
    return start >= o.start && start <= o.end;
  });
}

function closestElement(node) {
  if (node.nodeType !== node.ELEMENT_NODE) {
    return closestElement(node.parentNode)
  }
  return node;
}

let tagOnMouseDown = null;

window.addEventListener('mousedown', e => {
  console.log(e.target.tagName)
  tagOnMouseDown = e.target;

  if (tagOnMouseDown.tagName === 'MARK') {
    //	unwrap(tagOnMouseDown)
    // window.clearSelection()
    return;
  }
})

function...