import {
  $getSelection,
  ElementPoint,
  PointType,
  RangeSelection,
  TextPoint,
} from 'lexical';

export default function $getSelectionStartEnd(): {
  start: (TextPoint | ElementPoint) | null;
  end: (TextPoint | ElementPoint) | null;
} {
  const lexicalSelection = $getSelection() as RangeSelection | null;
  if (!lexicalSelection) return { start: null, end: null };
  const startEndPoints = lexicalSelection.getStartEndPoints() as
    | [PointType, PointType]
    | null;
  if (!startEndPoints) return { start: null, end: null };
  const start = startEndPoints[0].isBefore(startEndPoints[1])
    ? startEndPoints[0]
    : startEndPoints[1];
  const end = startEndPoints[0].isBefore(startEndPoints[1])
    ? startEndPoints[1]
    : startEndPoints[0];
  return {
    start: start as TextPoint | ElementPoint,
    end: end as TextPoint | ElementPoint,
  };
}
