"use client"; import Image, { getImageProps } from "next/image"; import { useCallback, useEffect, useRef, useState, type CSSProperties, } from "react"; import { useT } from "@/components/locale-provider"; import { cn, onIdle } from "@/lib/utils"; /** * Each face is hidden outright while it's turned away, switching as the flip * passes edge-on (114 ms into the spring below). backface-visibility alone isn't * enough: the theme switch's snapshot ignores it, which showed Bert. */ const face = (shown: boolean): CSSProperties => ({ visibility: shown ? "visible" : "hidden", transition: "visibility 0s linear 114ms", }); /** Tap the avatar to flip it over and meet Bert. */ export function AvatarFlip({ avatarUrl, dogUrl, }: { avatarUrl: string; dogUrl: string; }) { const { avatar } = useT(); const [flipped, setFlipped] = useState(false); // Bert is only in the page while he's showing or turning away, so nothing // (a theme switch, a browser's snapshot of the page) can paint him over Eric. const [dogIn, setDogIn] = useState(false); const warmed = useRef(false); // Fetches Bert at the size his face will ask for, so he's there on the flip. const warm = useCallback(() => { if (warmed.current) return; warmed.current = true; const { props } = getImageProps({ alt: "", fill: true, sizes: "60px", src: dogUrl, }); const img = new window.Image(); img.sizes = props.sizes ?? ""; img.srcset = props.srcSet ?? ""; img.src = props.src; }, [dogUrl]); useEffect(() => { const meet = () => { setDogIn(true); setFlipped(true); }; const cancelIdle = onIdle(warm, 5000); window.addEventListener("eric:bert", meet); return () => { window.removeEventListener("eric:bert", meet); cancelIdle(); }; }, [warm]); // Once Bert has turned away (his face hides 114 ms in), take him out. useEffect(() => { if (flipped) return; const id = setTimeout(() => setDogIn(false), 250); return () => clearTimeout(id); }, [flipped]); return ( ); }