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

AnimatedHeight.tsx

91 lines2.9 KB

1"use client";
2​
3import { type ReactNode, useEffect, useLayoutEffect, useRef, useState } from "react";
4​
5const HEIGHT_TRANSITION_FALLBACK_MS = 250;
6​
7export function AnimatedHeight({ children }: { readonly children: ReactNode }) {
8 const contentRef = useRef<HTMLDivElement>(null);
9 const [heightState, setHeightState] = useState<{
10 readonly height: number | null;
11 readonly isClipping: boolean;
12 }>({ height: null, isClipping: false });
13​
14 useEffect(() => {
15 if (!heightState.isClipping) return;
16 const timeoutId = window.setTimeout(() => {
17 setHeightState((currentState) =>
18 currentState.isClipping ? { ...currentState, isClipping: false } : currentState,
19 );
20 }, HEIGHT_TRANSITION_FALLBACK_MS);
21 return () => window.clearTimeout(timeoutId);
22 }, [heightState.height, heightState.isClipping]);
23​
24 useLayoutEffect(() => {
25 const element = contentRef.current;
26 if (!element) return;
27 let firstFrameId: number | null = null;
28 let secondFrameId: number | null = null;
29​
30 const updateHeight = () => {
31 const nextHeight = Math.ceil(element.scrollHeight || element.getBoundingClientRect().height);
32 setHeightState((currentState) => {
33 if (currentState.height === nextHeight) return currentState;
34 return {
35 height: nextHeight,
36 isClipping: currentState.height !== null,
37 };
38 });
39 };
40 const cancelPendingFrames = () => {
41 if (firstFrameId !== null) {
42 window.cancelAnimationFrame(firstFrameId);
43 firstFrameId = null;
44 }
45 if (secondFrameId !== null) {
46 window.cancelAnimationFrame(secondFrameId);
47 secondFrameId = null;
48 }
49 };
50 const updateHeightAfterPaint = () => {
51 cancelPendingFrames();
52 updateHeight();
53 firstFrameId = window.requestAnimationFrame(() => {
54 firstFrameId = null;
55 updateHeight();
56 secondFrameId = window.requestAnimationFrame(() => {
57 secondFrameId = null;
58 updateHeight();
59 });
60 });
61 };
62​
63 updateHeightAfterPaint();
64 const resizeObserver = new ResizeObserver(updateHeightAfterPaint);
65 resizeObserver.observe(element);
66 return () => {
67 resizeObserver.disconnect();
68 cancelPendingFrames();
69 };
70 }, []);
71​
72 return (
73 <div
74 data-slot="animated-height"
75 className="transition-[height] duration-200 ease-out motion-reduce:transition-none"
76 style={
77 heightState.height === null
78 ? undefined
79 : { height: heightState.height, overflow: heightState.isClipping ? "hidden" : "visible" }
80 }
81 onTransitionEnd={(event) => {
82 if (event.target !== event.currentTarget || event.propertyName !== "height") return;
83 setHeightState((currentState) =>
84 currentState.isClipping ? { ...currentState, isClipping: false } : currentState,
85 );
86 }}
87 >
88 <div ref={contentRef}>{children}</div>
89 </div>
90 );