Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

1.4 KB
Raw Blame
export interface SelectionToolbarPosition {
  left: number;
  top: number;
}

const TOOLBAR_OFFSET = 12;
const VIEWPORT_MARGIN = 12;
const LINE_TOP_TOLERANCE = 3;

export const getSelectionToolbarPosition = (
  rect: DOMRect,
  viewportWidth: number,
): SelectionToolbarPosition => {
  const center = rect.left + rect.width / 2;

  return {
    left: Math.min(Math.max(center, VIEWPORT_MARGIN), viewportWidth - VIEWPORT_MARGIN),
    top: Math.max(rect.top - TOOLBAR_OFFSET, VIEWPORT_MARGIN),
  };
};

const mergeRects = (rects: DOMRect[]): DOMRect => {
  const left = Math.min(...rects.map((rect) => rect.left));
  const right = Math.max(...rects.map((rect) => rect.right));
  const top = Math.min(...rects.map((rect) => rect.top));
  const bottom = Math.max(...rects.map((rect) => rect.bottom));

  return DOMRect.fromRect({
    height: bottom - top,
    width: right - left,
    x: left,
    y: top,
  });
};

export const getRangeFirstLineRect = (range: Range): DOMRect | undefined => {
  const rects = [...range.getClientRects()].filter((rect) => rect.width > 0 && rect.height > 0);

  if (rects.length === 0) {
    const rect = range.getBoundingClientRect();
    return rect.width > 0 || rect.height > 0 ? rect : undefined;
  }

  const firstTop = Math.min(...rects.map((rect) => rect.top));
  const firstLineRects = rects.filter(
    (rect) => Math.abs(rect.top - firstTop) <= LINE_TOP_TOLERANCE,
  );

  return mergeRects(firstLineRects);
};