fit-list.tsx 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. "use client";
  2. import { useEffect, useRef, type ReactNode } from "react";
  3. import { cn } from "@/lib/utils";
  4. /**
  5. * A list that shows only the rows that fit its height, so a card never ends
  6. * on half a row or on a gap. Rows that don't fit are hidden outright, which
  7. * also takes their links out of the tab order.
  8. */
  9. export function FitList({
  10. className,
  11. children,
  12. }: {
  13. className?: string;
  14. children: ReactNode;
  15. }) {
  16. const ref = useRef<HTMLUListElement>(null);
  17. useEffect(() => {
  18. const list = ref.current;
  19. if (!list) return;
  20. const fit = () => {
  21. const rows = [...list.children] as HTMLElement[];
  22. rows.forEach((row) => (row.hidden = false));
  23. const limit = list.clientHeight + 0.5;
  24. rows.forEach((row) => {
  25. row.hidden = row.offsetTop + row.offsetHeight > limit;
  26. });
  27. };
  28. const observer = new ResizeObserver(fit);
  29. fit();
  30. observer.observe(list);
  31. return () => observer.disconnect();
  32. }, []);
  33. return (
  34. <ul ref={ref} className={cn("relative overflow-hidden", className)}>
  35. {children}
  36. </ul>
  37. );
  38. }