Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

useTallEnoughToFold.ts

28 lines1.3 KB

1import { useLayoutEffect, useRef, useState } from "react";
2​
3import { observeResize } from "~/lib/observeResize";
4​
5// The folds clip with `max-h-44`, which is 11rem.
6const FOLDED_HEIGHT_REM = 11;
7​
8/**
9 * Put `ref` on the unclipped content inside a fold. `tallEnough` is true when that content is at
10 * least twice the folded height, so opening a fold always at least doubles what was on screen.
11 */
12export function useTallEnoughToFold(enabled = true) {
13 const ref = useRef<HTMLDivElement>(null);
14 const [tallEnough, setTallEnough] = useState(false);
15 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- the fold depends on the rendered height, which only the DOM knows
16 useLayoutEffect(() => {
17 const content = ref.current;
18 if (!enabled || !content) return;
19 // The observer reports after the browser's own layout and flushes before paint, so the first
20 // frame is already folded. Measuring here instead would force a layout mid-commit.
21 return observeResize(content, (entries) => {
22 const height = entries.at(-1)?.borderBoxSize[0]?.blockSize ?? content.offsetHeight;
23 const remPx = Number.parseFloat(getComputedStyle(document.documentElement).fontSize) || 16;
24 setTallEnough(height >= FOLDED_HEIGHT_REM * 2 * remPx);
25 });
26 }, [enabled]);
27 return { ref, tallEnough: enabled && tallEnough };