Open History to see the last commit
1export const DRAFT_HERO_TRANSITION_ANIMATION_ID = "t3-draft-hero-transition";
2export const DRAFT_HERO_TRANSITION_DURATION_MS = 180;
3export const DRAFT_HERO_TRANSITION_EASING = "cubic-bezier(0.4, 0, 0.2, 1)";
4export const MOBILE_COMPOSER_VIEW_TRANSITION_NAME = "t3-mobile-composer";
5export const MOBILE_DRAFT_HEADLINE_VIEW_TRANSITION_NAME = "t3-mobile-draft-headline";
6
7type ComposerViewTransition = {
8 readonly finished: Promise<void>;
9};
10
11let activeMobileComposerTransition: Promise<void> | null = null;
12
13type ComposerViewTransitionDocument = Document & {
14 startViewTransition?: (update: () => void | Promise<void>) => ComposerViewTransition;
15};
16
17export async function waitForDraftHeroTransition(): Promise<void> {
18 const mobileComposerTransition = activeMobileComposerTransition;
19 if (typeof document === "undefined" || typeof document.getAnimations !== "function") {
20 await mobileComposerTransition;
21 return;
22 }
23
24 const activeTransitions = document
25 .getAnimations()
26 .filter((animation) => animation.id === DRAFT_HERO_TRANSITION_ANIMATION_ID);
27
28 await Promise.all([
29 mobileComposerTransition,
30 ...activeTransitions.map(async (animation) => {
31 try {
32 await animation.finished;
33 } catch {
34 // A cancelled transition is already safe to hand off.
35 }
36 }),
37 ]);
38}
39
40export async function runMobileComposerTransition(
41 update: () => void | Promise<void>,
42): Promise<void> {
43 if (typeof document === "undefined" || typeof window === "undefined") {
44 await update();
45 return;
46 }
47
48 const transitionDocument = document as ComposerViewTransitionDocument;
49 const mobileViewport = window.matchMedia?.("(max-width: 639px)").matches ?? false;
50 const prefersReducedMotion =
51 window.matchMedia?.("(prefers-reduced-motion: reduce)").matches ?? false;
52 if (!mobileViewport || prefersReducedMotion || !transitionDocument.startViewTransition) {
53 await update();
54 return;
55 }
56
57 let updateStarted = false;
58 const runUpdate = async () => {
59 if (updateStarted) return;
60 updateStarted = true;
61 await update();
62 };
63 let transitionFinished: Promise<void> | null = null;
64 transitionDocument.documentElement.dataset.mobileComposerRouteTransition = "true";
65 try {
66 const transition = transitionDocument.startViewTransition(runUpdate);
67 transitionFinished = transition.finished.catch(() => undefined);
68 activeMobileComposerTransition = transitionFinished;
69 try {
70 await transition.finished;
71 } catch {
72 await runUpdate();
73 }
74 } catch {
75 await runUpdate();
76 } finally {
77 if (activeMobileComposerTransition === transitionFinished) {
78 activeMobileComposerTransition = null;
79 }
80 delete transitionDocument.documentElement.dataset.mobileComposerRouteTransition;
81 }
82}