theme-transition.ts 1.5 KB

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