import { NodeSelection, Selection, TextSelection } from '@atlaskit/editor-prosemirror/state';
import { GapCursorSelection } from '../selection';
/**
 * Compute the new selection offsets after list items have been moved/indented/outdented.
 *
 * Uses the content start offsets computed during fragment rebuild to map each
 * selection endpoint to its new absolute position, accounting for the change
 * in the list structure.
 */
export function computeSelectionOffsets(_ref) {
  var items = _ref.items,
    startIndex = _ref.startIndex,
    endIndex = _ref.endIndex,
    originalFrom = _ref.originalFrom,
    originalTo = _ref.originalTo,
    contentStartOffsets = _ref.contentStartOffsets,
    rootListStart = _ref.rootListStart,
    docSize = _ref.docSize;
  // +1 shifts from the outer edge of the list item node to the start of the content within
  var fromContentStart = items[startIndex].pos + 1;
  var toContentStart = items[endIndex].pos + 1;
  var fromOffset = originalFrom - fromContentStart;
  var toOffset = originalTo - toContentStart;
  var clamp = function clamp(pos) {
    return Math.min(Math.max(0, pos), docSize);
  };
  return {
    from: clamp(rootListStart + contentStartOffsets[startIndex] + fromOffset),
    to: clamp(rootListStart + contentStartOffsets[endIndex] + toOffset)
  };
}

/**
 * Restore the transaction's selection after a list structural change
 * (indent/outdent of list items or task list items).
 *
 * Uses the content start offsets computed during fragment rebuild to
 * map each selection endpoint to its new absolute position.
 *
 * Handles NodeSelection, GapCursorSelection, and TextSelection.
 */
// eslint-disable-next-line @atlaskit/volt-strict-mode/no-multiple-exports
export function restoreSelection(_ref2) {
  var tr = _ref2.tr,
    originalSelection = _ref2.originalSelection,
    from = _ref2.from,
    to = _ref2.to;
  var maxPos = tr.doc.content.size;
  if (originalSelection instanceof NodeSelection) {
    try {
      tr.setSelection(NodeSelection.create(tr.doc, Math.min(from, maxPos - 1)));
    } catch (_unused) {
      tr.setSelection(Selection.near(tr.doc.resolve(from)));
    }
  } else if (originalSelection instanceof GapCursorSelection) {
    tr.setSelection(new GapCursorSelection(tr.doc.resolve(from), originalSelection.side));
  } else {
    tr.setSelection(TextSelection.create(tr.doc, from, to));
  }
}