/**
 * Finds the direct child of the ProseMirror root element that contains the current selection.
 *
 * Starting from the DOM node at the selection position, this function walks up the DOM tree
 * until it reaches the ProseMirror root, then returns the last element before the root
 * (i.e., the second top-level ancestor).
 *
 * This is useful for attaching MutationObservers to the narrowest subtree that contains
 * the selection, while still capturing all relevant mutations within that branch.
 *
 * @param editorView - The ProseMirror EditorView instance
 * @returns The direct child of PM root containing the selection, or null if not found
 */
export var getSelectionAncestorDOM = function getSelectionAncestorDOM(editorView) {
  if (!editorView) {
    return null;
  }
  var pmDom = editorView.dom;
  var selection = editorView.state.selection;

  // nodeDOM can return null when editor loses focus (e.g. toolbar click) or for certain positions.
  // Fall back to domAtPos which resolves the DOM node at the given position.
  var currentNode = editorView.nodeDOM(selection.from);
  if (!currentNode) {
    try {
      var _editorView$domAtPos = editorView.domAtPos(selection.from),
        node = _editorView$domAtPos.node;
      currentNode = node instanceof HTMLElement ? node : node.parentElement;
    } catch (_unused) {
      return null;
    }
  }
  var lastValidAncestor = currentNode;
  while (currentNode instanceof HTMLElement && currentNode !== pmDom) {
    lastValidAncestor = currentNode;
    currentNode = currentNode.parentElement;
  }
  return lastValidAncestor instanceof HTMLElement ? lastValidAncestor : null;
};