float.ts 3.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. import { useLayoutEffect, useRef, type RefObject } from "react";
  2. import type { Locate } from "#ui/viewers/types.ts";
  3. const EDGE = 8;
  4. export interface FloatOptions {
  5. /** Preferred side of the anchor; flips when there is no room. */
  6. side: "top" | "bottom";
  7. /** Gap between anchor and element (ZCode's popover uses 8). */
  8. offset?: number;
  9. /** With no anchor box, sit at the top centre of the frame instead of hiding. */
  10. dock?: boolean;
  11. }
  12. /**
  13. * Keep an absolutely positioned element next to an anchor inside `frame` while the document
  14. * scrolls, like ZCode's Radix popovers (collision padding 8, hidden when the anchor leaves view).
  15. * Positions are written straight to the element every frame, so scrolling never re-renders React.
  16. * The element gets `data-side` ("top" | "bottom" | "none") and `--tip` for its arrow.
  17. */
  18. export function useFloating<T extends HTMLElement>(
  19. frame: RefObject<HTMLElement | null>,
  20. locate: Locate | null | undefined,
  21. options: FloatOptions,
  22. ) {
  23. const ref = useRef<T>(null);
  24. const { side, offset = 8, dock = false } = options;
  25. useLayoutEffect(() => {
  26. const element = ref.current;
  27. const container = frame.current;
  28. if (!element || !container) return;
  29. let frameId = 0;
  30. const place = () => {
  31. frameId = 0;
  32. const bounds = container.getBoundingClientRect();
  33. const width = element.offsetWidth;
  34. const height = element.offsetHeight;
  35. const box = locate?.() ?? null;
  36. const show = (left: number, top: number, placed: string, centre: number) => {
  37. element.style.visibility = "";
  38. element.style.left = `${Math.round(left)}px`;
  39. element.style.top = `${Math.round(top)}px`;
  40. element.dataset.side = placed;
  41. element.style.setProperty(
  42. "--tip",
  43. `${Math.round(Math.max(14, Math.min(width - 14, centre - left)))}px`,
  44. );
  45. };
  46. if (!box) {
  47. if (dock) show((bounds.width - width) / 2, EDGE, "none", bounds.width / 2);
  48. else element.style.visibility = "hidden";
  49. return;
  50. }
  51. if (box.bottom < bounds.top + 4 || box.top > bounds.bottom - 4) {
  52. element.style.visibility = "hidden";
  53. return;
  54. }
  55. const centre = (box.left + box.right) / 2 - bounds.left;
  56. const left = Math.max(EDGE, Math.min(bounds.width - width - EDGE, centre - width / 2));
  57. const above = box.top - bounds.top - height - offset;
  58. const below = box.bottom - bounds.top + offset;
  59. const fitsAbove = above >= EDGE;
  60. const fitsBelow = below + height <= bounds.height - EDGE;
  61. if (side === "top" ? fitsAbove : !fitsBelow && fitsAbove) show(left, above, "top", centre);
  62. else if (fitsBelow) show(left, below, "bottom", centre);
  63. // A tall anchor (a whole page): pin to the visible edge nearest the preferred side.
  64. else show(left, side === "top" ? EDGE : bounds.height - height - EDGE, "none", centre);
  65. };
  66. const schedule = () => {
  67. if (!frameId) frameId = requestAnimationFrame(place);
  68. };
  69. place();
  70. container.addEventListener("scroll", schedule, { capture: true, passive: true });
  71. const resize = new ResizeObserver(schedule);
  72. resize.observe(container);
  73. resize.observe(element);
  74. // Rendering (fonts, lazy pages, zoom) can move the anchor without a scroll.
  75. const settle = setInterval(schedule, 250);
  76. return () => {
  77. container.removeEventListener("scroll", schedule, { capture: true });
  78. resize.disconnect();
  79. clearInterval(settle);
  80. if (frameId) cancelAnimationFrame(frameId);
  81. };
  82. }, [frame, locate, side, offset, dock]);
  83. return ref;
  84. }