theme-transition.ts 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. "use client";
  2. import { flushSync } from "react-dom";
  3. import { isWebKit, prefersReducedMotion } from "@/lib/utils";
  4. type ViewTransitionDoc = Document & {
  5. startViewTransition?: (update: () => void) => { ready: Promise<void> };
  6. };
  7. /**
  8. * WebKit (Safari, and every browser on iOS) paints view-transition snapshots
  9. * without backdrop blur, so the glass nav and cards turned clear for the
  10. * length of the reveal and flashed back. There the theme switches at once.
  11. */
  12. const snapshotsDropGlass = isWebKit;
  13. /**
  14. * Switches the theme with a circular reveal that grows from `origin`
  15. * (usually the button that was clicked). Falls back to an instant switch.
  16. */
  17. export function switchTheme(
  18. next: "light" | "dark",
  19. setTheme: (theme: string) => void,
  20. origin?: { x: number; y: number },
  21. ) {
  22. const doc = document as ViewTransitionDoc;
  23. const apply = () => {
  24. document.documentElement.classList.toggle("dark", next === "dark");
  25. document.documentElement.style.colorScheme = next;
  26. flushSync(() => setTheme(next));
  27. };
  28. if (
  29. !doc.startViewTransition ||
  30. prefersReducedMotion() ||
  31. snapshotsDropGlass()
  32. ) {
  33. apply();
  34. return;
  35. }
  36. const x = origin?.x ?? window.innerWidth / 2;
  37. const y = origin?.y ?? 0;
  38. const radius = Math.hypot(
  39. Math.max(x, window.innerWidth - x),
  40. Math.max(y, window.innerHeight - y),
  41. );
  42. const transition = doc.startViewTransition(apply);
  43. transition.ready
  44. .then(() => {
  45. document.documentElement.animate(
  46. {
  47. clipPath: [
  48. `circle(0px at ${x}px ${y}px)`,
  49. `circle(${radius}px at ${x}px ${y}px)`,
  50. ],
  51. },
  52. {
  53. duration: 700,
  54. easing: "cubic-bezier(0.65, 0, 0.35, 1)",
  55. pseudoElement: "::view-transition-new(root)",
  56. },
  57. );
  58. })
  59. .catch(() => {});
  60. }