motion-spring.tsx 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. import { attachSpring, motionValue } from "motion"
  2. import type { SpringOptions } from "motion"
  3. import { createComputed, createEffect, createSignal, onCleanup } from "solid-js"
  4. type Opt = Partial<Pick<SpringOptions, "visualDuration" | "bounce" | "stiffness" | "damping" | "mass" | "velocity">>
  5. const eq = (a: Opt | undefined, b: Opt | undefined) =>
  6. a?.visualDuration === b?.visualDuration &&
  7. a?.bounce === b?.bounce &&
  8. a?.stiffness === b?.stiffness &&
  9. a?.damping === b?.damping &&
  10. a?.mass === b?.mass &&
  11. a?.velocity === b?.velocity
  12. export function useSpring(target: () => number, options?: Opt | (() => Opt), snapKey?: () => unknown) {
  13. const read = () => (typeof options === "function" ? options() : options)
  14. const [value, setValue] = createSignal(target())
  15. const source = motionValue(value())
  16. const spring = motionValue(value())
  17. let config = read()
  18. let snapValue = snapKey?.()
  19. let stop = attachSpring(spring, source, config)
  20. let off = spring.on("change", (next: number) => setValue(next))
  21. createComputed(() => {
  22. const next = target()
  23. const nextSnap = snapKey?.()
  24. if (snapKey && nextSnap !== snapValue) {
  25. // State boundaries should adopt their target without animating from the previous context.
  26. snapValue = nextSnap
  27. stop()
  28. spring.jump(next)
  29. source.jump(next)
  30. stop = attachSpring(spring, source, config)
  31. setValue(next)
  32. return
  33. }
  34. source.set(next)
  35. })
  36. createEffect(() => {
  37. if (!options) return
  38. const next = read()
  39. if (eq(config, next)) return
  40. config = next
  41. stop()
  42. stop = attachSpring(spring, source, next)
  43. setValue(spring.get())
  44. })
  45. onCleanup(() => {
  46. off()
  47. stop()
  48. spring.destroy()
  49. source.destroy()
  50. })
  51. return value
  52. }