"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.getDomRefFromSelection = void 0;
var _utils = require("@atlaskit/editor-prosemirror/utils");
var _analytics = require("../analytics");
var getDomRefFromSelection = exports.getDomRefFromSelection = function getDomRefFromSelection(view, actionSubjectId, editorAnalyticsAPI) {
  try {
    var domRef = (0, _utils.findDomRefAtPos)(view.state.selection.from, view.domAtPos.bind(view));
    if (domRef instanceof HTMLElement) {
      // If element is not a paragraph, we need to find the closest paragraph parent
      if (domRef.nodeName !== 'P') {
        var paragraphRef = domRef.closest('p');
        if (paragraphRef) {
          return paragraphRef;
        }
      }
      return domRef;
    } else {
      throw new Error('Invalid DOM reference');
    }
  } catch (error) {
    if (editorAnalyticsAPI) {
      var payload = {
        action: _analytics.ACTION.ERRORED,
        actionSubject: _analytics.ACTION_SUBJECT.PICKER,
        actionSubjectId: actionSubjectId,
        eventType: _analytics.EVENT_TYPE.OPERATIONAL,
        attributes: {
          error: 'Error getting DOM reference from selection'
        }
      };
      editorAnalyticsAPI.fireAnalyticsEvent(payload);
    }
  }
};