theme-transition.ts 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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. * 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 = () => {
  13. const ua = navigator.userAgent;
  14. return /AppleWebKit/.test(ua) && !/(Chrome|Chromium|Edg|OPR)\//.test(ua);
  15. };
  16. /**
  17. * Switches the theme with a circular reveal that grows from `origin`
  18. * (usually the button that was clicked). Falls back to an instant switch.
  19. */
  20. export function switchTheme(
  21. next: "light" | "dark",
  22. setTheme: (theme: string) => void,
  23. origin?: { x: number; y: number },
  24. ) {
  25. const doc = document as ViewTransitionDoc;
  26. const apply = () => {
  27. document.documentElement.classList.toggle("dark", next === "dark");
  28. document.documentElement.style.colorScheme = next;
  29. flushSync(() => setTheme(next));
  30. };
  31. if (
  32. !doc.startViewTransition ||
  33. prefersReducedMotion() ||
  34. snapshotsDropGlass()
  35. ) {
  36. apply();
  37. return;
  38. }
  39. const x = origin?.x ?? window.innerWidth / 2;
  40. const y = origin?.y ?? 0;
  41. const radius = Math.hypot(
  42. Math.max(x, window.innerWidth - x),
  43. Math.max(y, window.innerHeight - y),
  44. );
  45. const transition = doc.startViewTransition(apply);
  46. transition.ready
  47. .then(() => {
  48. document.documentElement.animate(
  49. {
  50. clipPath: [
  51. `circle(0px at ${x}px ${y}px)`,
  52. `circle(${radius}px at ${x}px ${y}px)`,
  53. ],
  54. },
  55. {
  56. duration: 700,
  57. easing: "cubic-bezier(0.65, 0, 0.35, 1)",
  58. pseudoElement: "::view-transition-new(root)",
  59. },
  60. );
  61. })
  62. .catch(() => {});
  63. }