function snapBoundaryPointToTextNode()

in packages/dom/src/normalize-range.ts [120:156]


function snapBoundaryPointToTextNode(
  node: Node,
  offset: number,
): [Text, number] {
  if (isText(node)) return [node, offset];

  // Find the node at or right after the boundary point.
  let curNode: Node;
  if (isCharacterData(node)) {
    curNode = node;
  } else if (offset < node.childNodes.length) {
    curNode = node.childNodes[offset];
  } else {
    curNode = node;
    while (curNode.nextSibling === null) {
      if (curNode.parentNode === null)
        // Boundary point is at end of document
        throw new Error('not implemented'); // TODO
      curNode = curNode.parentNode;
    }
    curNode = curNode.nextSibling;
  }

  if (isText(curNode)) return [curNode, 0];

  // Walk to the next text node, or the last if there is none.
  const document = node.ownerDocument ?? (node as Document);
  const walker = document.createTreeWalker(document, NodeFilter.SHOW_TEXT);
  walker.currentNode = curNode;
  if (walker.nextNode() !== null) {
    return [walker.currentNode as Text, 0];
  } else if (walker.previousNode() !== null) {
    return [walker.currentNode as Text, (walker.currentNode as Text).length];
  } else {
    throw new Error('Document contains no text nodes.');
  }
}