motion.ts 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. /**
  2. * The site's motion language: three springs, and everything that moves uses
  3. * one of them. The same curves exist as CSS custom properties
  4. * (`--ease-snap`, `--ease-glide`, `--ease-wobble` in styles/globals.css) so
  5. * plain CSS transitions and script animations feel identical.
  6. *
  7. * - snap: feedback (presses, hovers, toggles). Quick and exact.
  8. * - glide: layout (cards moving to new slots, drops, sheets). Smooth, with a
  9. * hair of overshoot.
  10. * - wobble: liquid things (the nav droplet, glass beads). Visible, playful
  11. * overshoot, like a drop of water settling.
  12. */
  13. export const SPRINGS = {
  14. snap: [520, 42],
  15. glide: [240, 25],
  16. wobble: [300, 17],
  17. } as const;
  18. /**
  19. * Builds a CSS `linear()` easing that follows a damped spring, so plain CSS
  20. * transitions and WAAPI animations get physical motion.
  21. */
  22. export function springEasing(
  23. stiffness = 170,
  24. damping = 18,
  25. mass = 1,
  26. steps = 48,
  27. ) {
  28. const w0 = Math.sqrt(stiffness / mass);
  29. const zeta = damping / (2 * Math.sqrt(stiffness * mass));
  30. const wd = w0 * Math.sqrt(Math.max(0, 1 - zeta * zeta));
  31. const duration = settleTime(w0, zeta);
  32. const points: string[] = [];
  33. for (let i = 0; i < steps; i++) {
  34. const t = (i / steps) * duration;
  35. let x: number;
  36. if (zeta < 1) {
  37. x =
  38. 1 -
  39. Math.exp(-zeta * w0 * t) *
  40. (Math.cos(wd * t) + ((zeta * w0) / wd) * Math.sin(wd * t));
  41. } else {
  42. x = 1 - Math.exp(-w0 * t) * (1 + w0 * t);
  43. }
  44. points.push(x.toFixed(4));
  45. }
  46. // End exactly at rest so nothing jumps on the last frame.
  47. points.push("1");
  48. return {
  49. easing: `linear(${points.join(", ")})`,
  50. duration: Math.round(duration * 1000),
  51. };
  52. }
  53. function settleTime(w0: number, zeta: number) {
  54. // Time for the envelope to fall under 0.1% of the initial displacement.
  55. return Math.min(2, Math.max(0.35, Math.log(1000) / (zeta * w0)));
  56. }
  57. const fallback = "cubic-bezier(0.2, 0.9, 0.25, 1)";
  58. let supportsLinear: boolean | undefined;
  59. export function spring(stiffness?: number, damping?: number) {
  60. if (supportsLinear === undefined) {
  61. supportsLinear =
  62. typeof CSS !== "undefined" &&
  63. CSS.supports("animation-timing-function", "linear(0, 1)");
  64. }
  65. const s = springEasing(stiffness, damping);
  66. return supportsLinear ? s : { easing: fallback, duration: s.duration };
  67. }
  68. /** Easing and duration for one of the site's springs, ready for `el.animate()`. */
  69. export const springs = {
  70. snap: () => spring(...SPRINGS.snap),
  71. glide: () => spring(...SPRINGS.glide),
  72. wobble: () => spring(...SPRINGS.wobble),
  73. };