Skip to content

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

1.1 KB
Raw Blame
import { useLayoutEffect, useRef, useState } from "react";

export function fitBrowserPage(width: number, height: number): { width: number; height: number } | null {
  if (!Number.isFinite(width) || !Number.isFinite(height) || width < 1 || height < 1) return null;
  const ratio = width < 560 ? 9 / 16 : width < 880 ? 1 : 16 / 9;
  const fittedWidth = Math.min(width, height * ratio);
  return { width: Math.max(1, Math.floor(fittedWidth)), height: Math.max(1, Math.floor(fittedWidth / ratio)) };
}

export function useBrowserPageSize() {
  const ref = useRef<HTMLDivElement>(null);
  const [size, setSize] = useState<{ width: number; height: number } | null>(null);
  useLayoutEffect(() => {
    const element = ref.current;
    if (!element || typeof ResizeObserver === "undefined") return;
    const measure = () => {
      const { width, height } = element.getBoundingClientRect();
      setSize(fitBrowserPage(width, height));
    };
    measure();
    const observer = new ResizeObserver(measure);
    observer.observe(element);
    return () => observer.disconnect();
  }, []);
  return { ref, size };
}