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

useDraftHeroLayoutTransition.ts

69 lines2.7 KB

1import { useStableCallback } from "../../hooks/useStableCallback";
2import { useLayoutEffect, useRef } from "react";
3import {
4 DRAFT_HERO_TRANSITION_ANIMATION_ID,
5 DRAFT_HERO_TRANSITION_EASING,
6} from "./draftHeroTransition";
7​
8export function useDraftHeroLayoutTransition(
9 isDraftHeroState: boolean,
10 animationsActive: boolean,
11 animationDurationMs: number,
12) {
13 const transitionGroupRef = useRef<HTMLDivElement | null>(null);
14 const composerAnchorRef = useRef<HTMLDivElement | null>(null);
15 const previousStateRef = useRef(isDraftHeroState);
16 const previousComposerRectRef = useRef<DOMRect | null>(null);
17 const animationRef = useRef<Animation | null>(null);
18 const captureComposerRect = useStableCallback(() => {
19 previousComposerRectRef.current = composerAnchorRef.current?.getBoundingClientRect() ?? null;
20 });
21​
22 useLayoutEffect(() => {
23 const transitionGroup = transitionGroupRef.current;
24 const nextComposerRect = composerAnchorRef.current?.getBoundingClientRect() ?? null;
25 const stateChanged = previousStateRef.current !== isDraftHeroState;
26 const mobileComposerTransitionActive =
27 typeof document !== "undefined" &&
28 document.documentElement.dataset.mobileComposerRouteTransition === "true";
29​
30 animationRef.current?.cancel();
31 animationRef.current = null;
32 const previousComposerRect = previousComposerRectRef.current;
33 if (
34 stateChanged &&
35 animationsActive &&
36 !mobileComposerTransitionActive &&
37 transitionGroup &&
38 previousComposerRect &&
39 nextComposerRect &&
40 typeof transitionGroup.animate === "function"
41 ) {
42 const translateX = previousComposerRect.left - nextComposerRect.left;
43 const translateY = previousComposerRect.top - nextComposerRect.top;
44 if (Math.abs(translateX) >= 0.5 || Math.abs(translateY) >= 0.5) {
45 const animation = transitionGroup.animate(
46 [
47 { transform: `translate3d(${translateX}px, ${translateY}px, 0)` },
48 { transform: "translate3d(0, 0, 0)" },
49 ],
50 {
51 duration: animationDurationMs,
52 easing: DRAFT_HERO_TRANSITION_EASING,
53 },
54 );
55 animation.id = DRAFT_HERO_TRANSITION_ANIMATION_ID;
56 animationRef.current = animation;
57 void animation.finished
58 .catch(() => undefined)
59 .then(() => {
60 if (animationRef.current === animation) animationRef.current = null;
61 });
62 }
63 }
64 previousStateRef.current = isDraftHeroState;
65 previousComposerRectRef.current = nextComposerRect;
66 }, [animationDurationMs, animationsActive, isDraftHeroState]);
67​
68 return { transitionGroupRef, composerAnchorRef, captureComposerRect } as const;