Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

1.8 KB
Raw Blame
type Box = { getBoundingClientRect(): { top: number } };

function topIn(scroller: Box & { scrollTop: number }, target: Box): number {
  return target.getBoundingClientRect().top - scroller.getBoundingClientRect().top + scroller.scrollTop;
}

/** Moves `scroller` alone so `target` sits at its top or centre. Element.scrollIntoView would also scroll every
 * overflow-hidden ancestor, sliding a dialog's frame and its header out of view. */
export function scrollWithin(
  scroller: Box & { scrollTop: number; clientHeight: number },
  target: Box & { offsetHeight?: number },
  block: "start" | "center" = "start",
  margin = 0,
): void {
  const top = topIn(scroller, target);
  scroller.scrollTop = Math.max(0, block === "center" ? top - (scroller.clientHeight - (target.offsetHeight ?? 0)) / 2 : top - margin);
}

export function scrollParent(element: Element): HTMLElement | null {
  for (let node = element.parentElement; node; node = node.parentElement) {
    const overflow = getComputedStyle(node).overflowY;
    if ((overflow === "auto" || overflow === "scroll") && node.scrollHeight > node.clientHeight) return node;
  }
  return null;
}

/** Centres `target` in its nearest scrolling ancestor only, within that scroller's scroll-padding (the docked
 * composer's room), so the page and the app's frames stay where they are. */
export function scrollToCenter(target: HTMLElement, behavior: ScrollBehavior): void {
  const scroller = scrollParent(target);
  if (!scroller) return;
  const style = getComputedStyle(scroller);
  const padTop = parseFloat(style.scrollPaddingTop) || 0;
  const visible = scroller.clientHeight - padTop - (parseFloat(style.scrollPaddingBottom) || 0);
  scroller.scrollTo({ top: Math.max(0, topIn(scroller, target) - padTop - (visible - target.offsetHeight) / 2), behavior });
}