use-motion-template.mjs 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. import { useCombineMotionValues } from './use-combine-values.mjs';
  2. import { isMotionValue } from './utils/is-motion-value.mjs';
  3. /**
  4. * Combine multiple motion values into a new one using a string template literal.
  5. *
  6. * ```jsx
  7. * import {
  8. * motion,
  9. * useSpring,
  10. * useMotionValue,
  11. * useMotionTemplate
  12. * } from "framer-motion"
  13. *
  14. * function Component() {
  15. * const shadowX = useSpring(0)
  16. * const shadowY = useMotionValue(0)
  17. * const shadow = useMotionTemplate`drop-shadow(${shadowX}px ${shadowY}px 20px rgba(0,0,0,0.3))`
  18. *
  19. * return <motion.div style={{ filter: shadow }} />
  20. * }
  21. * ```
  22. *
  23. * @public
  24. */
  25. function useMotionTemplate(fragments, ...values) {
  26. /**
  27. * Create a function that will build a string from the latest motion values.
  28. */
  29. const numFragments = fragments.length;
  30. function buildValue() {
  31. let output = ``;
  32. for (let i = 0; i < numFragments; i++) {
  33. output += fragments[i];
  34. const value = values[i];
  35. if (value) {
  36. output += isMotionValue(value) ? value.get() : value;
  37. }
  38. }
  39. return output;
  40. }
  41. return useCombineMotionValues(values.filter(isMotionValue), buildValue);
  42. }
  43. export { useMotionTemplate };